Javascript working in Dreamweaver but not in Browser [duplicate] - javascript

I used the .load() function. It works in Dreamweaver's Live View, but not in Firefox, Chrome, or IE.
Here is my HTML section:
<script src="js/jquery.js"></script>
<script src="tabsPull.js"></script>
<h1>Homework Assignments</h1>
<ul id="button-menu">
<li id="a1"><input class="no" type="button" onClick="ChangeActive(1)" value="Mon"></li>
<li id="a2"><input class="no" type="button" onClick="ChangeActive(2)" value="Tues/Wed"></li>
<li id="a3"><input c lass="no" type="button" onClick="ChangeActive(3)" value="Thurs/Fri"></li>
</ul>
<div id="tabInner" class="tabInner">
</div>
The ChangeActive() is in a separate JS file (tabsPull.js):
var active = 0
function ChangeActive(active){
if (active==1) {
document.getElementById("a1").className = "active";
document.getElementById("a2").className = "";
document.getElementById("a3").className = "";
$('#tabInner').load('http://axoplanner.weebly.com/monday.html #content');
} else if (active==2) {
document.getElementById("a2").className = "active";
document.getElementById("a1").className = "";
document.getElementById("a3").className = "";
$('#tabInner').load('http://axoplanner.weebly.com/tuesdaywednesday.html #content');
} else if (active==3) {
document.getElementById("a3").className = "active";
document.getElementById("a1").className = "";
document.getElementById("a2").className = "";
$('#tabInner').load('http://axoplanner.weebly.com/thursdayfriday.html #content');
}
}
What's the problem? It works in DW, but why not the browsers??? The reason I pull things from Weebly is because I need others to update it, and Weebly is easier.

See this page from the jQUery documentation.
From the Documentation:
"Due to browser security restrictions, most "Ajax" requests are subject to the same origin policy; the request can not successfully retrieve data from a different domain, subdomain, or protocol."
So, DreamWeaver must not have the security restrictions that most browsers have, so it works in DreamWeaver. But an absolute path will not work as an argument for .load() in most browsers.

Related

How to render HTML file using JavaScript [duplicate]

I want home.html to load in <div id="content">.
<div id="topBar"> HOME </div>
<div id ="content"> </div>
<script>
function load_home(){
document.getElementById("content").innerHTML='<object type="type/html" data="home.html" ></object>';
}
</script>
This works fine when I use Firefox. When I use Google Chrome, it asks for plug-in. How do I get it working in Google Chrome?
I finally found the answer to my problem. The solution is
function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}
Fetch API
function load_home (e) {
(e || window.event).preventDefault();
fetch("http://www.yoursite.com/home.html" /*, options */)
.then((response) => response.text())
.then((html) => {
document.getElementById("content").innerHTML = html;
})
.catch((error) => {
console.warn(error);
});
}
XHR API
function load_home (e) {
(e || window.event).preventDefault();
var con = document.getElementById('content')
, xhr = new XMLHttpRequest();
xhr.onreadystatechange = function (e) {
if (xhr.readyState == 4 && xhr.status == 200) {
con.innerHTML = xhr.responseText;
}
}
xhr.open("GET", "http://www.yoursite.com/home.html", true);
xhr.setRequestHeader('Content-type', 'text/html');
xhr.send();
}
based on your constraints you should use ajax and make sure that your javascript is loaded before the markup that calls the load_home() function
Reference - davidwalsh
MDN - Using Fetch
JSFIDDLE demo
You can use the jQuery load function:
<div id="topBar">
HOME
</div>
<div id ="content">
</div>
<script>
$(document).ready( function() {
$("#load_home").on("click", function() {
$("#content").load("content.html");
});
});
</script>
Sorry. Edited for the on click instead of on load.
Fetching HTML the modern Javascript way
This approach makes use of modern Javascript features like async/await and the fetch API. It downloads HTML as text and then feeds it to the innerHTML of your container element.
/**
* #param {String} url - address for the HTML to fetch
* #return {String} the resulting HTML string fragment
*/
async function fetchHtmlAsText(url) {
return await (await fetch(url)).text();
}
// this is your `load_home() function`
async function loadHome() {
const contentDiv = document.getElementById("content");
contentDiv.innerHTML = await fetchHtmlAsText("home.html");
}
The await (await fetch(url)).text() may seem a bit tricky, but it's easy to explain. It has two asynchronous steps and you could rewrite that function like this:
async function fetchHtmlAsText(url) {
const response = await fetch(url);
return await response.text();
}
See the fetch API documentation for more details.
I saw this and thought it looked quite nice so I ran some tests on it.
It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.
I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.
In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.
Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<div id="content"></div>
<script>
/**
* Test harness to find out the best method for dynamically loading a
* html page into your app.
*/
var test_times = {};
var test_page = 'testpage.htm';
var content_div = document.getElementById('content');
// TEST 1 = use jQuery to load in testpage.htm and time it.
/*
function test_()
{
var start = new Date().getTime();
$(content_div).load(test_page, function() {
alert(new Date().getTime() - start);
});
}
// 1044
*/
// TEST 2 = use <object> to load in testpage.htm and time it.
/*
function test_()
{
start = new Date().getTime();
content_div.innerHTML = '<object type="text/html" data="' + test_page +
'" onload="alert(new Date().getTime() - start)"></object>'
}
//1579
*/
// TEST 3 = use httpObject to load in testpage.htm and time it.
function test_()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
{
content_div.innerHTML = xmlHttp.responseText;
alert(new Date().getTime() - start);
}
};
start = new Date().getTime();
xmlHttp.open("GET", test_page, true); // true for asynchronous
xmlHttp.send(null);
// 1039
}
// Main - run tests
test_();
</script>
</body>
</html>
try
async function load_home(){
content.innerHTML = await (await fetch('home.html')).text();
}
async function load_home() {
let url = 'https://kamil-kielczewski.github.io/fractals/mandelbulb.html'
content.innerHTML = await (await fetch(url)).text();
}
<div id="topBar"> HOME </div>
<div id="content"> </div>
When using
$("#content").load("content.html");
Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server
You can use the jQuery :
$("#topBar").on("click",function(){
$("#content").load("content.html");
});
$("button").click(function() {
$("#target_div").load("requesting_page_url.html");
});
or
document.getElementById("target_div").innerHTML='<object type="text/html" data="requesting_page_url.html"></object>';
<script>
var insertHtml = function (selector, argHtml) {
$(document).ready(function(){
$(selector).load(argHtml);
});
var targetElem = document.querySelector(selector);
targetElem.innerHTML = html;
};
var sliderHtml="snippets/slider.html";//url of slider html
var items="snippets/menuItems.html";
insertHtml("#main",sliderHtml);
insertHtml("#main2",items);
</script>
this one worked for me when I tried to add a snippet of HTML to my main.html.
Please don't forget to add ajax in your code
pass class or id as a selector and the link to the HTML snippet as argHtml
There is this plugin on github that load content into an element. Here is the repo
https://github.com/abdi0987/ViaJS
load html form a remote page ( where we have CORS access )
parse the result-html for a specific portion of the page
insert that part of the page in a div on current-page
//load page via jquery-ajax
$.ajax({
url: "https://stackoverflow.com/questions/17636528/how-do-i-load-an-html-page-in-a-div-using-javascript",
context: document.body
}).done(function(data) {
//the previous request fails beceaus we dont have CORS on this url.... just for illlustration...
//get a list of DOM-Nodes
var dom_nodes = $($.parseHTML(data));
//find the question-header
var content = dom_nodes.find('#question-header');
//create a new div and set the question-header as it's content
var newEl = document.createElement("div");
$(newEl).html(content.html());
//on our page, insert it in div with id 'inserthere'
$("[id$='inserthere']").append(newEl);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>part-result from other page:</p>
<div id="inserthere"></div>
Use this simple code
<div w3-include-HTML="content.html"></div>
<script>w3.includeHTML();</script>
</body>```
This is usually needed when you want to include header.php or whatever page.
In Javascript it's easy especially if you have HTML page and don't want to use php include function but at all you should write php function and add it as Javascript function in script tag.
In this case you should write it without function followed by name Just. Script rage the function word and start the include header.php
i.e convert the php include function to Javascript function in script tag and place all your content in that included file.
I use jquery, I found it easier
$(function() {
$("#navigation").load("navbar.html");
});
in a separate file and then load javascript file on html page
showhide.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showHide(switchTextDiv, showHideDiv)
{
var std = document.getElementById(switchTextDiv);
var shd = document.getElementById(showHideDiv);
if (shd.style.display == "block")
{
shd.style.display = "none";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Show</span>";
}
else
{
if (shd.innerHTML.length <= 0)
{
shd.innerHTML = "<object width=\"100%\" height=\"100%\" type=\"text/html\" data=\"showhide_embedded.html\"></object>";
}
shd.style.display = "block";
std.innerHTML = "<span style=\"display: block; background-color: yellow\">Hide</span>";
}
}
</script>
</head>
<body>
<a id="switchTextDiv1" href="javascript:showHide('switchTextDiv1', 'showHideDiv1')">
<span style="display: block; background-color: yellow">Show</span>
</a>
<div id="showHideDiv1" style="display: none; width: 100%; height: 300px"></div>
</body>
</html>
showhide_embedded.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function load()
{
var ts = document.getElementById("theString");
ts.scrollIntoView(true);
}
</script>
</head>
<body onload="load()">
<pre>
some text 1
some text 2
some text 3
some text 4
some text 5
<span id="theString" style="background-color: yellow">some text 6 highlight</span>
some text 7
some text 8
some text 9
</pre>
</body>
</html>
If your html file resides locally then go for iframe instead of the tag. tags do not work cross-browser, and are mostly used for Flash
For ex : <iframe src="home.html" width="100" height="100"/>

My javascript is returning this error: $.ajax is not a function

Not sure what's wrong but I'm getting this error from my chrome console:
jquery-3.2.1.slim.min.js:1244 jQuery.Deferred exception: $.ajax is not a function TypeError: $.ajax is not a function
at HTMLDocument.<anonymous> (file:///C:/Users/Adam/Desktop/UseTime/js/example.js:3:7)
at j (file:///C:/Users/Adam/Desktop/UseTime/js/jquery-3.2.1.slim.min.js:1193:55)
at k (file:///C:/Users/Adam/Desktop/UseTime/js/jquery-3.2.1.slim.min.js:1199:45) undefined
r.Deferred.exceptionHook # jquery-3.2.1.slim.min.js:1244
jquery-3.2.1.slim.min.js:1247 Uncaught TypeError: $.ajax is not a function
at HTMLDocument.<anonymous> (example.js:3)
at j (jquery-3.2.1.slim.min.js:1193)
at k (jquery-3.2.1.slim.min.js:1199)
From this JavaScript:
$(function() { //when the DOM is ready
var times; //declare global variable
$.ajax({ //set up request
beforeSend: function (xhr) { //before requesting data
if (xhr.overrideMimeType) { //if supported
xhr.overrideMimeType("application/json"); // set MIME to prevent errors
}
}
});
//funciton that collect data from the json file
function loadTimetable() { //decalre function
$.getJSON('data/example.json') //try to collect json data
.done(function (data) { //if succesful
times = data; //store in variable
}).fail(function () { //if a problem: show message
$('#event').html('Sorry! we couldnt load your time table at the moment');
});
}
loadTimetable(); //call the function
//CLICK ON TEH EVENT TO LOAD A TIME TABLE
$('#content').on('click', '#event a', function (e) { //user clicks on place
e.preventDefault(); //prevent loading page
var loc = this.id.toUpperCase(); //get value of id attr
var newContent = "";
for (var i = 0; i < times[loc].length; i++) { // loop through sessions
newContent += '<li><span class = "time">' + times[loc][i].time + '</span>';
newContent += '<a href = "descriptions.html#';
newContent += times[loc][i].title.replace(/ /g, '-') + '">';
newContent += times[loc][i].title + '</a></li>';
}
$('#sessions').html('<ul>' + newContent + '</ul>'); // Display Time
$('#event a.current').removeClass('current'); // update selected link
$(this).addClass('current');
$('#details').text('');
});
//CLICK ON A SESSION TO LEAD THE DESCRIPTION
$('#content').on('click', '#sessions li a', function (e) { //click on session
e.preventDefault(); // prevent loading
var fragment = this.href; //title is in href
fragment = fragment.replace('#', ' #'); //Add Space before #
$('#details').load(fragment); //to load info
$('#sessions a.current').removeClass('current'); //update selected
});
//CLICK ON PRIMARY NAVIGATION
$('nav a').on('click', function (e) { //click on nav
e.preventDefault(); //prevent loading
var url = this.href; //get UR: to load
$('nav a.current').removeClass('current');
$(this).addClass('current');
$('#container').remove(); //remove old
$('#content').load(url + ' #container').hide().fadeIn('slow'); // add new
});
});
I'm not sure if it's an issue with the way I'm initiating .ajax or if my jquery isn't correctly implemented. I think it is. Any Thoughts?
edit: here's the html that goes with the script above
<!DOCTYPE html>
<body>
<header>
<h1>UseTime</h1>
<nav>
HOME
PROFILE
MANAGE TASKS
TIME TABLE
</nav>
</header>
<section id="content">
<div id="container">
<div class="third">
<div id="event">
<a id="class1" href="class1.html"><img src="" alt="class1" /> Class 1 </a>
<a id="class2" href="class2.html"><img src="" alt="class2" /> Class 2 </a>
<a id="class3" href="class3.html"><img src="" alt="class3" /> Class 3 </a>
</div>
</div>
<div class="third">
<div id="sessions"> Select a Class from the left </div>
</div>
<div class="third">
<div id="details"> Details </div>
</div>
</div>
<!-- container -->
</section>
<!-- content -->
<script src="js/jquery-3.2.1.slim.min.js"></script>
<script src="js/example.js"></script>
</body>
You are using slim version of jQuery. It Doesn't support ajax Calling.
Use
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
instead of it.
Slim build
Sometimes you don’t need ajax, or you prefer to use one of the many
standalone libraries that focus on ajax requests. And often it is
simpler to use a combination of CSS and class manipulation for all
your web animations. Along with the regular version of jQuery that
includes the ajax and effects modules, we’ve released a “slim” version
that excludes these modules. All in all, it excludes ajax, effects,
and currently deprecated code. The size of jQuery is very rarely a
load performance concern these days, but the slim build is about 6k
gzipped bytes smaller than the regular version – 23.6k vs 30k. These
files are also available in the npm package and on the CDN:
https://code.jquery.com/jquery-3.1.1.slim.js
https://code.jquery.com/jquery-3.1.1.slim.min.js
Referred from jQuery Blog
jQuery 3 slim version doesn't support ajax.
According to the release docs,
Along with the regular version of jQuery that includes the ajax and
effects modules, we’re releasing a “slim” version that excludes these
modules. All in all, it excludes ajax, effects, and currently
deprecated code.
To use .ajax method, simply use the full version one.
Try this one (jquery-3.2.1.min.js) instead of slim (jquery-3.2.1.slim.min.js)
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

Reload A Div And Move Previous Content

I have an ERB document:
<!DOCTYPE html>
<html>
<head>
<script>
scrollDown = function() {
document.body.scrollTop = document.body.scrollHeight;
}
</script>
</head>
<body onload='scrollDown()'>
<div id='2'>
</div>
<div id='target'>
<%=#chat%> <!-- #chat is a variable from my ruby file -->
</div>
<form action="/addChat?n=<%=#name%>" method='post'>
<input name='nchat' type='text' onload='this.focus' autofill='no' style='width:100%;height:10em;vertical-align:top'>
<input type='submit'>
</form>
<a href='/home'>Go home!</a>
</body>
</html>
And I would like to have it so that every half of a second it will do two things. First it needs to move the contents of the <div id="target"> to <div id="2"> then reload the contents of <div id="target"> getting the variable #chat from another route (post \content do ... end).
I am using sinatra and heroku. PLEASE DO NOT ANSWER USING JQUERY. I DO NOT KNOW HOW TO USE JQUERY AND I WOULD LIKE TO UNDERSTAND HOW THE ANSWER WORKS.
I will be happy to add any resources you need to answer this question, and I will try to do so as promptly as possible.
Clarification
Here is my code which has been slightly modified since asking this question (I hope this code clarifies my question). When I enter the loop to move things from <div id="target"> to <div id="2"> into the console in browser (google chrome latest version) it runs fine and moves everything correctly. Here is the loop:
while (document.getElementById('target').childNodes.length > 0) {
document.getElementById("2").appendChild(document.getElementById('target').childNodes[0]);
}
Now my only remaining issue is reloading the content of <div id="target"> from the route in my app file post '/chatContent' do ... return #chat end where #chat is a dynamically changing variable every 0.5 seconds and before reloading each time running the above loop. Here is my current attempt at the reloading with the loop (also most of this is copy paste from various sources, so I don't really understand it):
var refreshDelay = 5000000;
function createRequestObject() {
var ro;
if(navigator.appName == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq() {
while (document.getElementById('target').childNodes.length > 0) {
document.getElementById("2").appendChild(document.getElementById('target').childNodes[0]);
}
http.open('post', '/chatContent?n=<%=#name%>');
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
while (document.getElementById('target').childNodes.length > 0) {
document.getElementById("2").appendChild(document.getElementById('target').childNodes[0]);
}
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('target').innerHTML = response;
setTimeout(sndReq, refreshDelay);
}
}
setTimeout(sndReq, refreshDelay);
</script>
<script>
scrollDown = function() {
document.body.scrollTop = document.body.scrollHeight;
}
function movethings() {
while (document.getElementById('target').childNodes.length > 0) {
document.getElementById("2").appendChild(document.getElementById('target').childNodes[0]);
}
}
Just to clarify, what I am looking for is a replacement for the above code, including 1st) Running the loop to move the contents of <div id="target"> to <div id="2"> then 2nd) reloading <div id='target'>. The order is important.
I hope that this clarification has narrowed the scope of my question. If it has not, please leave a comment about why it is too broad because I do not understand how it is.
Edit 2
In summary, each answer must, in order, do the following:
Move content of <div id="target"> to <div id="2">
Reload <div id="target"> so that it contains the return of my Sinatra route, post "/chatContent"

Get client hostname [duplicate]

How can I read the client's machine/computer name from the browser?
Is it possible using JavaScript and/or ASP.NET?
You can do it with IE 'sometimes' as I have done this for an internal application on an intranet which is IE only. Try the following:
function GetComputerName() {
try {
var network = new ActiveXObject('WScript.Network');
// Show a pop up if it works
alert(network.computerName);
}
catch (e) { }
}
It may or may not require some specific security setting setup in IE as well to allow the browser to access the ActiveX object.
Here is a link to some more info on WScript: More Information
Browser, Operating System, Screen Colors, Screen Resolution, Flash version, and Java Support should all be detectable from JavaScript (and maybe a few more). However, computer name is not possible.
EDIT: Not possible across all browser at least.
Well you could get the ip address using asp.net, then do a reverse DNS lookup on the ip to get the hostname.
From the ASP.NET Developer's cookbook ... Performing a Reverse-DNS Lookup.
It is not possible to get the users computer name with Javascript. You can get all details about the browser and network. But not more than that.
Like some one answered in one of the previous question today.
I already did a favor of visiting your website, May be I will return or refer other friends.. I also told you where I am and what OS, Browser and screen resolution I use Why do you want to know the color of my underwear? ;-)
You cannot do it using asp.net as well.
Try getting the client computer name in Mozilla Firefox by using the code given below.
netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
Also, the same piece of code can be put as an extension, and it can called from your web page.
Please find the sample code below.
Extension code:
var myExtension = {
myListener: function(evt) {
//netscape.security.PrivilegeManager.enablePrivilege( 'UniversalXPConnect' );
var dnsComp = Components.classes["#mozilla.org/network/dns-service;1"];
var dnsSvc = dnsComp.getService(Components.interfaces.nsIDNSService);
var compName = dnsSvc.myHostName;
content.document.getElementById("compname").value = compName ;
}
}
document.addEventListener("MyExtensionEvent", function(e) { myExtension.myListener(e); }, false, true); //this event will raised from the webpage
Webpage Code:
<html>
<body onload = "load()">
<script>
function showcomp()
{
alert("your computer name is " + document.getElementById("compname").value);
}
function load()
{
//var element = document.createElement("MyExtensionDataElement");
//element.setAttribute("attribute1", "foobar");
//element.setAttribute("attribute2", "hello world");
//document.documentElement.appendChild(element);
var evt = document.createEvent("Events");
evt.initEvent("MyExtensionEvent", true, false);
//element.dispatchEvent(evt);
document.getElementById("compname").dispatchEvent(evt); //this raises the MyExtensionEvent event , which assigns the client computer name to the hidden variable.
}
</script>
<form name="login_form" id="login_form">
<input type = "text" name = "txtname" id = "txtnamee" tabindex = "1"/>
<input type="hidden" name="compname" value="" id = "compname" />
<input type = "button" onclick = "showcomp()" tabindex = "2"/>
</form>
</body>
</html>
There is no way to do so, as JavaScript does not have an access to computer name, file system and other local info. Security is the main purpose.
No this data is not exposed. The only data that is available is what is exposed through the HTTP request which might include their OS and other such information. But certainly not machine name.
<html>
<body onload = "load()">
<script>
function load(){
try {
var ax = new ActiveXObject("WScript.Network");
alert('User: ' + ax.UserName );
alert('Computer: ' + ax.ComputerName);
}
catch (e) {
document.write('Permission to access computer name is denied' + '<br />');
}
}
</script>
</body>
</html>
There is some infos to parse into the webRTC header.
var p = new window.RTCPeerConnection();
p.createDataChannel(null);
p.createOffer().then((d) => p.setLocalDescription(d))
p.onicecandidate = (e) => console.log(p.localDescription)
An updated version from Kelsey :
$(function GetInfo() {
var network = new ActiveXObject('WScript.Network');
alert('User ID : ' + network.UserName + '\nComputer Name : ' + network.ComputerName + '\nDomain Name : ' + network.UserDomain);
document.getElementById('<%= currUserID.ClientID %>').value = network.UserName;
document.getElementById('<%= currMachineName.ClientID %>').value = network.ComputerName;
document.getElementById('<%= currMachineDOmain.ClientID %>').value = network.UserDomain;
});
To store the value, add these control :
<asp:HiddenField ID="currUserID" runat="server" /> <asp:HiddenField ID="currMachineName" runat="server" /> <asp:HiddenField ID="currMachineDOmain" runat="server" />
Where you also can calling it from behind like this :
Page.ClientScript.RegisterStartupScript(this.GetType(), "MachineInfo", "GetInfo();", true);
Erm is there any reason why you can't just use the HttpRequest? This would be on the server side but you could pass it to the javascript if you needed to?
Page.Request.UserHostName
HttpRequest.UserHostName
The one problem with this is it would only really work in an Intranet environment otherwise it would just end up picking up the users Router or Proxy address...

AJAX response not displayed immediately in IE8

I'm seeing a strange issue with my code below. The content received thru the xmlHttpRequest, is not being displayed in IE8, after clicking the link. It is displayed only after moving the mouse/cursor, after clicking the link.
<html>
<head>
<script language="javascript">
var xmlHttpfunction;
function ShowHint(str,id,currentid,count)
{
for(i = 0; i < count; i++)
{
if (i == currentid)
{
cellImg(i,'images/head_on.jpg');
}
else
{
cellImg(i,'images/btn_img.jpg');
}
}
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url = "myurl.php";
url = url+"?id="+id;
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
}
function cellImg(idCell, imgName)
{
document.getElementById(idCell).style.background = "url(" + imgName + ")";
}
function stateChanged()
{
if (xmlHttp.readyState === 1)
{
document.getElementById("element").innerHTML = "<p align='center'><img src='images/wait.gif'></p>";
}
else if (xmlHttp.readyState === 4)
{
document.getElementById("element").style.display = "block";
document.getElementById("element").innerHTML = xmlHttp.responseText;
}
}
</script>
</head>
<body>
<div id="navigation">
<ul >
<li id=1 >
<a href="#" onclick="ShowHint('menu',42,1,18);return false;">
Item 1
</a>
</li>
<li id=2 >
<a href="#" onclick="ShowHint('menu',11,2,18);return false;">
Item 2
</a>
</li>
<li id=3 >
<a href="#" onclick="ShowHint('menu',12,3,18);return false;">
Item 3
</a>
</li>
</ul>
</div>
<div class="element" id="element">
</div>
</body>
</html>
The above works on Firefox, Safari, Chrome and Opera. But on IE8, the content is not displayed (though it is loaded into the innerHTML of the div id="element"), if there is no cursor movement, after clicking the link.
I've tried putting alerts and debugging thru IE8's script debugger (in Tools->DeveloperTools), but could not find whats causing the issue.
Could anyone help me out on this, please ?
Many Thanks,
sgullap
Check to see if perhaps the responseText from the ajax call is starting with a carriage return. I had a similar issue today (which is how I found this question while googling) and discovered that my HTML code accidentally started with a blank line in the target page of the ajax call. Removing that extra line caused the innerHTML to be set correctly and to display.
I'm not sure I understand WHY this caused IE not to display the innerHTML that I assigned to the div, but know now to make doubly sure to avoid blank lines at the top of any HTML output retrieved through ajax!

Categories

Resources