I have the following script working in all major browsers except for Internet Explorer. All of my variables are coming back undefined.
{
if (window.XMLHttpRequest)
{
xhttp=new XMLHttpRequest();
}
else
{
xhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.open("GET",dname,false);
xhttp.send();
return xhttp.responseXML;
}
var xmlDoc = loadXMLDoc("nhl_standings_xml.xml");
var x = xmlDoc.getElementsByTagName("nhlall");
Some other info..
xhttp.readystate = 4
xhttp.status=200
I am using .textContent to get the variables, however, I have read that sometimes IE has problems with that. Can someone maybe give me some ideas about alternatives to .textContent?
here is what the rest of code looks like:
document.getElementById('PensWins').innerHTML = var1;
document.getElementById('PensLoses').innerHTML = var3;
document.getElementById('PensOTWins').innerHTML = var8;
var var1 = x[i+3].textContent;
var var3 = x[i+4].textContent;
var var8 = x[i+5].textContent;
'i' is coming from a loop
im asking is there any part of the above IE8 doesn't like? (obviously there is)
Related
I have the following code :
<head>
<script>
function startChanging() {
var elems = document.getElementsByTagName("img");
for(var i=0; i < elems.length; i++)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp["elem"] = elems[i];
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
this["elem"].src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://myurl.com/somescript.php", true);
xmlhttp.send();
}
};
</script>
</head>
<body onload="startChanging()">
<img src="https://www.google.com/images/srpr/logo11w.png">
<br/>
<img src="https://www.google.com/images/srpr/logo11w.png">
<br/>
<img src="https://www.google.com/images/srpr/logo11w.png">
</body>
Even though I create a new instance of XMLHttpRequest for each iteration and add the current element to an attribute, when the request returns a response only the last img element is changed.
I am looking for a simple solution to change the src of the img element without iterating through all the elements again when the response comes. I would like a pure Javascript solution (read: no JQuery).
I am certainly doing something wrong here I just don't understand what. Any help would be appreciated.
In your for loop, you are overwriting the xmlhttp variable so when you get into the onreadystatechage function and you check the value of xmlhttp.readyState, it will not be checking the right object.
I'd suggest this fix which changes two things:
It puts each ajax call into it's own IIFE which keeps the xmlhttp variable separate for each ajax call.
It passes elems[i] into the closure so you don't have to do the property saving hack.
Code:
function startChanging() {
var elems = document.getElementsByTagName("img");
for(var i=0; i < elems.length; i++)
{
(function(obj) {
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
obj.src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "http://myurl.com/somescript.php", true);
xmlhttp.send();
})(elems[i]);
}
};
One possible approach:
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
this.elem.src = this.responseText;
}
}
As you see, I've replaced all the references to xmlhttp within that handler function to this.
The problem is even though you've created a new AJAX-serving object at each step of the loop, each newly-created 'readystatechange' handler function referred to the same object known under xmlhttp variable.
In general, this is quite a common problem when someone works with a variable declared within a loop yet referred by functions created in the same loop. Stumble upon this once or twice, and you'll begin to see the pattern. )
xmlhttp.send();
Put data into the send method:
xmlhttp.send(data);
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
void send();
void send(ArrayBuffer data);
void send(ArrayBufferView data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);
Where data is a JavaScript variable, you can put anything into. If you want multipart message, you'd use var data = new FormData(); and put data into it using data.append('image', file); for file upload via ajax for example.
If no multipart, simply put anything in like:
data = { images: document.getElementsByTagName("img") }
I want to display the binary code of a music file. But somehow the code below doesn't seem to work. Any suggestions??
function binary() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","1.wav",true);
xmlhttp.overrideMimeType("text/plain; charset=x-user-defined");
xmlhttp.onreadystatechange = function(buffer) {
var binaryCode = "";
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var binStr = this.responseText;
for (var i=0; i<binStr.length; i++) {
var byte = binStr.charCodeAt(i) & 0xff; // get byte at i
binaryCode += byte;
}
}
document.getElementById("result").innerHTML = binaryCode; // should display binary code
};
xmlhttp.send();
}
Not all byte values are expressible in a string and will not appear or cause the string to cut off short.
XMLHttpResponse.ResponseText/ResponseXML will return the http response content as a string. Any byte values of 0 for example will terminate the string.
Have the server return a Base64 representation of the bytes and decode into byte values on the client side.
Your code seems to be working fine on my chrome browser.
What is exactly the problem your are experimenting ?
You may want to display the binary in an hexadecimal form by doing something like:
binaryCode += '0x' + byte.toString(16) + ' '
edit:
this jsfiddle works on my chrome:
http://jsfiddle.net/e6Kfk/
However, i do not think that this method is crossbrowser, especially if you want to deal with ie (haven't tested it though)
I am busy developing a chrome extension.
What it will do:
Get data from a PHP page (XMLHttpRequest)
Split the result variable using .split
And when someone clicks on a div, it will call a function to insert a css file with that name I got in number 1.
My problem:
Well nothing happens when I click that button. It works when I used the variable, "newvar", instead of the variable, "currenttheme" from the XMLHttpRequest. I tried converting it to a string as well using .toString. Oh, alerting the variable does work and gives exactly the same response as newvar.
My code: (Sigh!)
//My XMLHttpRequest
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
user_data = xmlhttp.responseText;
window.user_data = user_data;
processdata();
}
}
xmlhttp.open("GET","http://localhost:8888/myphppage.php",true);
xmlhttp.send();
function processdata() {
//split result variable from PHP
var downdata = user_data.split('|||||');
var installedthemes = downdata[0];
currenttheme = downdata[1].toString();
window.currenttheme = currenttheme.toString();
}
function click(e) {
newvar = "001";
//insert css - works with variable newvar but not with this one
chrome.tabs.insertCSS(null,
{file:currenttheme + ".css"});
//alerting the variable works, exactly the same as newvar
alert (currenttheme);
}
document.addEventListener('DOMContentLoaded', function () {
var divs = document.querySelectorAll('div');
for (var i = 0; i < divs.length; i++) {
divs[i].addEventListener('click', click);
}
});
window.user_data = user_data;// <- not required. user_data = xmlhttp.responseText implies user_data is global to this window.
window.currenttheme = currenttheme.toString(); <<- not required too
also downdata[1] IS a string so replace
currenttheme = downdata[1].toString();
with
currenttheme = downdata[1];
If this doesn't help, try alert(currenttheme); and see if you are getting the required theme name, because sometimes PHP can throw errors and die which may not produce a "|||||". Check the php output and alert the xmlhttp.responseText too to see if everything is OK.
I am pretty new to Javascript and cannot for my life figure out why the following object properties are not transferring.
I am calling the object as follows:
var URL = "TABLE=_Products&COLUMNS=price_Qty,Sale&MATCH=internal_Model&ROWS="+itemnum ;
var ITEM = new get_Database_Info(URL) ;
and the get_Database_Info is:
function get_Database_Info(PARAMS) {
alert(toString(this));
var URL = document.location.protocol+'//'+document.location.host+'/Catalog/Tools/ajax_Database_Request.php' ;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if(!xmlhttp){alert('Error: Cannot send XML request.');}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(toString(this));
var RESPONSE = xmlhttp.responseText ;
RESPONSE = RESPONSE.replace(/^\s+/, '');
var ARR = RESPONSE.split('||') ;
ARR.pop() ;
for(var i=0; i<ARR.length; i++){
var temparr1 = ARR[i].split('=') ;
var NUM = temparr1[0] ;
this[NUM] = new Array() ;
var temparr2 = temparr1[1].split('/|') ;
temparr2.shift() ;
for(var x=0; x<temparr2.length; x++){
var temparr3 = temparr2[x].split('??') ;
this[NUM][temparr3[0]] = temparr3[1] ;
}
}
}
}
xmlhttp.open("POST", URL, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", PARAMS.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(PARAMS);
}
I have verified that all the properties are in 'this' within the scope of get_Database_Info but they are not transferring back to ITEM.
When are you checking the contents of the object? The request is asynchronous, so you have to wait until the callback has processed the response before there are any properties in the object.
If you look for the properties immediately after the object is created, they will never be there. Even if the response is really quick, the first time that the callback can run is when you exit the function where you created the object, so the browser gets the control back.
I would venture to guess that the when the function that is attached to onreadystatechange runs that this is no longer attached to the object that is being created in the constructor but is probably attached to the global object or the xmlhttp object. I would try using the var that=this pattern:
function get_Database_Info(PARAMS) {
alert(toString(this));
var URL = document.location.protocol+'//'+document.location.host+'/Catalog/Tools/ajax_Database_Request.php' ;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var that=this; // value of that will be stored in the closure
if(!xmlhttp){alert('Error: Cannot send XML request.');}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200){
alert(toString(that));
var RESPONSE = xmlhttp.responseText ;
RESPONSE = RESPONSE.replace(/^\s+/, '');
var ARR = RESPONSE.split('||') ;
ARR.pop();
var arrLength = ARR.length; // always precompute array length
for(var i=0; i<ARR.length; i++){
var temparr1 = ARR[i].split('=') ;
var NUM = temparr1[0] ;
// that is actually equal to the object that I created
// in the constructor.
that[NUM] = new Array() ;
var temparr2 = temparr1[1].split('/|') ;
temparr2.shift() ;
var arrayLength = temparr2.length; // always precompute length
for(var x=0; x<arrayLength; x++){
var temparr3 = temparr2[x].split('??') ;
that[NUM][temparr3[0]] = temparr3[1] ;
}
}
}
}
xmlhttp.open("POST", URL, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", PARAMS.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(PARAMS);
Also, as noted in the comments, when you are iterating over the values in an array for a for loop, you should not use array.length directly, as the length method will be called every time through the loop, adding a great deal of unnecessary work.
Also, as #Guffa notes, the function that adds the values is called asynchronously, so the properties will not exist until the XmlHttpRequest has completed, and that is a very dangerous anti-pattern. I would strongly advise against it. It's better to have your constructor make a synchronous request for the data.
Can anyone figure out why this is throwing a syntax error? All of the code looks correct to me.
<script type="text/javascript">
var rootdomain="http://"+window.location.hostname;
function ajaxinclude(url)
{
var pagerequest = false;
if (window.XMLHttpRequest) // if Mozilla, Safari etc
pagerequest = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
pagerequest = new ActiveXObject("Msxml2.XMLHTTP")
}
catch (e){
try{
pagerequest = new ActiveXObject("Microsoft.XMLHTTP")
}
catch (e){}
}
}
else
return false
pagerequest.open('GET', url, false) //get page synchronously
pagerequest.send(null)
writecontent(pagerequest)
}
function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 || pagerequest.status==200)
document.getElementById("page1").innerHTML = pagerequest.responseText;
}
It's throwing an error on line 7 -- var pagerequest = false;
If you comment it out, it just throws an error on the next line. Any ideas?
Thanks in advance for your help!!
Yopur writecontent is wronge (argument naming) try:
function writecontent(page_request){
if (window.location.href.indexOf("http")==-1 || page_request.status==200)
document.getElementById("page1").innerHTML = page_request.responseText;
}
Also, there's no real value to this:
var pagerequest = false;
Since you never return it without setting it somewhere else in your code might as well just be:
var pagerequest;
In your writecontent function, you call the argument page_request, but then refer to it in the function body as pagerequest (without the underscore).
Otherwise, your code should be working -- see http://jsfiddle.net/2eynH/ for an example.
First things first - utilize http://jslint.com/
It does not like your writecontent function.
And pagerequest = new XMLHttpRequest() is missing a semicolon.
Also, I also like to "rip" my javascript through YUI Compressor to help reveal syntax errors.
http://developer.yahoo.com/yui/compressor/
Some more missing semicolons:
pagerequest = new ActiveXObject("Msxml2.XMLHTTP")
pagerequest = new ActiveXObject("Microsoft.XMLHTTP")
One more thing. Even though javascript allows you to do something, does not mean that you should. Declaring pagerequest as a boolean, then setting it to an ActiveXObject is a little confusing. I would probably initialize it to null. Then "test" for null later on down in the code.
You are missing semicolons on almost all lines.
Cleaned up code:
function ajaxinclude(url) {
var pagerequest;
if (window.XMLHttpRequest) { // if Mozilla, Safari etc
pagerequest = new XMLHttpRequest();
} else if (window.ActiveXObject){ // if IE
try {
pagerequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
pagerequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (ec) {}
}
}
else {
return false;
}
pagerequest.open('GET', url, false); // get page synchronously
pagerequest.send();
writecontent(pagerequest);
}
function writecontent (page_request) {
if (window.location.href.indexOf("http") == -1 || page_request.status == 200) {
document.getElementById("page1").innerHTML = page_request.responseText;
}
}
Your code is not valid. Semi-colons are added to your code when doesnt have it or it thinks it should have it.
So in
function ajaxinclude(url)
{
var pagerequest = false;
if (window.XMLHttpRequest) // if Mozilla, Safari etc
pagerequest = new XMLHttpRequest()
else if (window.ActiveXObject){ // if IE
try {
the javascript compiler will do the following
function ajaxinclude(url); // note the semi-color meaning the { starts floating in the middle of nowhere
{
var pagerequest = false;
if (window.XMLHttpRequest) // if Mozilla, Safari etc
pagerequest = new XMLHttpRequest();
else if (window.ActiveXObject){ // if IE
try { //and so on
As most people have suggested run JSLint over it to see the mistakes.
Edit from comment
You can see the Semi-colon insertion details in the blog