...

View Full Version : AJAX function only works once!



TriKri
07-06-2007, 10:11 PM
Hello! I have written this test code:


<html>
<body>

<script type="text/javascript">

function ajaxFunction() {
var xmlHttp;
try { //Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
try { //Internet Explorer
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}

xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4) {
document.myForm.time.value = xmlHttp.responseText;
xmlHttp.responseText = "";
}
}
xmlHttp.open("get","time.php",true);
xmlHttp.send(null);
}

</script>

<form name="myForm">
Name: <input type="text" onkeyup="ajaxFunction();" name="username" />
Time: <input type="text" name="time" />
</form>

</body>
</html>

And in time.php:

<?php
echo date("H:i:s");
?>

And it works perfectly fine, the first time. But the second time and the rest of the times (after clearing the textboxes), the same time as before will continue to pop up, each time I release a key. But it should be the current time, not the same time as before! :( I would really appreciate some help here. What in my code is wrong? Or is it IE 7 that troubles me?

carlitos_way
07-06-2007, 11:50 PM
I think (but if i'm thinking wrong, correct me) that IE caches the result, so it's always the same.

this is a classical problem, that can be avoided by passing a random useless parameter, or a datetime, so that IE thinks that you're requesting something new, and it avoids to cache the result.

TriKri
07-07-2007, 01:12 AM
I think (but if i'm thinking wrong, correct me) that IE caches the result, so it's always the same.

this is a classical problem, that can be avoided by passing a random useless parameter, or a datetime, so that IE thinks that you're requesting something new, and it avoids to cache the result.

Wow, thanks! That worked! I just added a junk-counter and added it to the the adress as a GET-variable. :thumbsup: Do you know of some way to tell IE to reload the page anyway or maybe to clear that specific history so it will be reloaded?

carlitos_way
07-07-2007, 11:42 PM
When I use Firefox, I press ctrl+f5 to reload all the page without using the version cached. I think you can try the same on IE

this can be a solution for you, but not for the people who'll see your end application.. but i don't know any other answer, sorry :)

NancyJ
07-09-2007, 04:16 PM
I've got the exact same problem in IE, except adding a random number to the url isnt helping, any ideas?



var xmlHttp
var field

function suggest_weight()
{
frame = document.getElementById('users_frame_size')[document.getElementById('users_frame_size').selectedIndex].value;
height_feet = document.getElementById('users_height_feet')[document.getElementById('users_height_feet').selectedIndex].value;
height_inches = document.getElementById('users_height_inches')[document.getElementById('users_height_inches').selectedIndex].value;
url = '/suggest_weight.php?frame='+frame+'&height_feet='+height_feet+'&height_inches='+height_inches;
changeField(url, 'users_goal_weight');

}
function changeField(url,fieldName)
{
field = fieldName;
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url+'&rand='+Math.floor(Math.random()*100),true);
xmlHttp.send(null);
}

function stateChanged()
{

if (xmlHttp.readyState==4)
{
document.getElementById(field).value=xmlHttp.responseText;
}
}

onload = function()
{
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}

TriKri
07-09-2007, 04:37 PM
I've got the exact same problem in IE, except adding a random number to the url isnt helping, any ideas?

How random is the random number? (I haven't used that random generator before, I believe, if it isn't the same as in the C/C++ math library) could it maybe have happened that the rendom generator used the same random seed all the times?

Just taking a shot, try adding a counter instead as I did, there could be a chans that helps.

NancyJ
07-09-2007, 06:23 PM
I tried a counter and still no luck. And yes I checked that the counter was being incremented

TriKri
07-09-2007, 06:57 PM
I tried a counter and still no luck. And yes I checked that the counter was being incremented

You have? I was just gonna ask you that!

A1ien51
07-10-2007, 01:19 AM
Using POST would clear it up since GET is supposed to cache.

you could also do
xmlhttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");

Eric

NancyJ
07-10-2007, 04:56 PM
tried both the header and the post method - still no luck, it still only works the first time in IE

A1ien51
07-10-2007, 05:09 PM
Are you reusing the Object?

The correct order with IE is

open()
onreadystatechange
send()

If you have onreadystatechange before the open, IE will not work.

Eric

glenngv
07-10-2007, 09:51 PM
You're only setting the xmlHttp variables once. Try creating it everytime changeField function is called.

NancyJ
07-10-2007, 10:00 PM
alien51 had it - it was the ordering of open onreadystatechange and send, that'll teach me to grab code from w3schools rather than walking up to my pc and getting my own ;)

A1ien51
07-12-2007, 04:52 AM
A bunch of people complain about that issue with the W3Schools code. A bunch of pople have sent them emails telling them to change it, but they never did.

Eric

SquidScareMe
12-12-2007, 03:39 PM
Thanks Alien51. You just saved me.

cdigs
06-20-2008, 10:01 PM
Thanks Alien51. You just saved me.

I stumbled on this thread because I'm encountering the same issue.

The symptoms are exactly the same:

1) Works fine every time in FF3,
2) Works fine every time in IE if Fiddler is running (very odd)
3) Works fine every time in IE if I use CTRL+F5
4) Works only the first time in IE if I just hit refresh or use F5
5) Works fine in IE and I can make the same call over and over again as long as I don't refresh the page (then it breaks to scenario 4)

So the twist here is that I'm using prototype 1.6.0.2 (the latest release). To ensure that this isn't isolated to prototype, I also tried with the latest release of jQuery. Same deal.

I didn't check jQuery source, but at least with prototype, the order of operations seems to be correct. Here is the relevant section of code (lines 1214-1223 of prototype.js):



this.transport.open(this.method.toUpperCase(), this.url,
this.options.asynchronous);

if (this.options.asynchronous) this.respondToReadyState.bind(this).defer(1);

this.transport.onreadystatechange = this.onStateChange.bind(this);
this.setRequestHeaders();

this.body = this.method == 'post' ? (this.options.postBody || params) : null;
this.transport.send(this.body);


As I mentioned, since Fiddler interferes with the manifestation of this error, I used WireShark to trace the messages on the server. It seems that on the unsuccessful calls, the HTTP message has a content length header set to 0 (and thus, I'm assuming, the POST body content is not being supplied, even though I haven't changed the request). Of course the mystery is why this is the case considering that I'm able to use the ASP.NET AJAX libraries all day long without drama on IE.

I've added trace messages after the call to this.transport.send(this.body) just to ensure that the body content is indeed included and the result is positive (the intended content is there), however, the content length on the request (and possibly the content itself is not being sent) is 0.

So any help would be much appreciated.

Edit: To add a twist, it all works fine with the YUI connection manager...

Edit 2: I take it back...it doesn't work with YUI either...

abohmeed
09-08-2010, 11:11 PM
Are you reusing the Object?

The correct order with IE is

open()
onreadystatechange
send()

If you have onreadystatechange before the open, IE will not work.

Eric

Really a big thanks to you.. i registered in this forum just to tell you that! you saved me hours of useless searching.

P.S. hell with IE - all versions!

sgpayn0
11-29-2010, 12:50 AM
I resolved my own problem, stumbled upon the bug...bad data in bad data out of course. As you can see in my function I pass it a string, turns out my AJAX code is perfectly fine, the string was not being fully reset before being passed back in for the 2nd iteration...


I am expereicing the identical problem of AJAX only executing once. I was hopeful when I read this thread, particularly Alien51's response, but it isn't working for me.

Here is my code below...any help would be much appreciated. It works perfectly the first time, then nothing. I even tried adding the random parameter to be passed, still nothing...




function AJAX()
{
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser sucks, and doesn't support AJAX!");
return false;
}
}
}
return ajaxRequest;
}

function div_details(str)
{
var divid = "details";
var url = "StockDetails_ajax.jsp";

// Create xmlHttp
var xmlHttp_one = AJAX();
if(xmlHttp_one==null)
{
alert ("Your browser does not support AJAX!");
return;
}

xmlHttp_one.open("POST",url + str + "&r="+ Math.random(),true);
xmlHttp_one.onreadystatechange=function()
{
if(xmlHttp_one.readyState==4 && xmlHttp_one.status==200)
{
document.getElementById(divid).innerHTML=xmlHttp_one.responseText;
}
}
xmlHttp_one.send(null);

}

sgpayn0
12-02-2010, 01:10 AM
Ok, I'm back again. As I said in the previous post I got the AJAX code to work on the same div tag multiple times, and it works perfectly well, however I am now trying to expand this to update multiple div's on the same page when calling the same function (clicking the same button). It still updates the original div really well, however the other two are ignored and nothing is updated. I have tried rearanging the code, the sequence of div's, breaking out the functions and giving each one their own unique variables, etc. Still no luck. Alert messages following the execution of each div even say the code executed each function.....so why is the information not being updated on the screen?

Here is the code below, any help would be much appreciated.

Essentially my code is setup to where a table row, also tagged with a radio input button calls my doAJAX( value of radio button ) function. This function then sequentially calls each of the AJAX functions to update each div sequentially. I've tried rearanging these, and even commenting out the original div I setup to be updated using AJAX. Only the original function ever works. The other div's don't update even if they are the only active ones coded, yet the code/functions are identical other than changing some of the variable names to be unique.





<script type="text/javascript">
//AJAX scripts, base script fromhttp://www.aleixcortadellas.com/main/2009/02/25/refreshing-div-content-with-ajax-multiple-divs/

// Timestamp for preventing IE caching the GET request (common function)
function fetch_unix_timestamp()
{
return parseInt(new Date().getTime().toString().substring(0, 10))
}


function AJAX()
{
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser sucks, and doesn't support AJAX!");
return false;
}
}
}
return ajaxRequest;
}


function div_details(str)
{
var divid = "details";
var url = "StockDetails_ajax.jsp";

// Create xmlHttp
var xmlHttp_one = AJAX();
if(xmlHttp_one==null)
{
alert ("Your browser does not support AJAX!");
return;
}

xmlHttp_one.open("POST",url + str + "&r="+ Math.random(),true);
xmlHttp_one.onreadystatechange=function()
{
if(xmlHttp_one.readyState==4 && xmlHttp_one.status==200)
{
document.getElementById(divid).innerHTML=xmlHttp_one.responseText;
}
}
xmlHttp_one.send(null);

}


function div_news(str_news)
{
var divid_news = "news";
var url_news = "StockNewsTable_Search_ajax.jsp";

// Create xmlHttp
var xmlHttp_two = AJAX();

// No cache
var timestamp = fetch_unix_timestamp();
var nocacheurl = url_news+"?t="+timestamp;


if(xmlHttp_two==null)
{
alert ("Your browser does not support AJAX!");
return;
}

xmlHttp_two.open("POST",nocacheurl + str_news + "&r="+ Math.random(),true);
xmlHttp_two.onreadystatechange=function()
{
if(xmlHttp_two.readyState==4 && xmlHttp_two.status==200)
{
document.getElementById(divid_news).innerHTML=xmlHttp_two.responseText;
}
}
xmlHttp_two.send(null);

}

function div_chart1(str_chart)
{
var divid_chart = "stockChart1";
var url_chart = "ChartGenerator_ajax.jsp";

// Create xmlHttp
var xmlHttp_three = AJAX();

// No cache
var timestamp = fetch_unix_timestamp();
var nocacheurl = url_chart+"?t="+timestamp;

if(xmlHttp_three==null)
{
alert ("Your browser does not support AJAX!");
return;
}

xmlHttp_three.open("POST",nocacheurl + str_chart + "&r="+ Math.random(),true);
xmlHttp_three.onreadystatechange=function()
{
if(xmlHttp_three.readyState==4 && xmlHttp_three.status==200)
{
document.getElementById(divid_chart).innerHTML=xmlHttp_three.responseText;
}
}
xmlHttp_three.send(null);

}

</script>

<script language="JavaScript">

function selectRowRadio(row) {
var radio = row.getElementsByTagName("input")[0];
radio.checked = true;

//do AJAX stuff when row selected
doAJAX(radio.value);
}


//set some global variables to be able to pass
var member = "MemberID="+<%= MemberID %>;

var param = "";


function doAJAX(string)
{
param = member + "&SearchStock="+string + "&t="+ Math.random(); //add random variable to prevent cashing

div_details("?" + param);
div_chart1("?" + param);

div_news("?" + param);

//reset the parameter so not to mess up the next request
param = "";
}


</script>

sgpayn0
12-03-2010, 12:42 AM
anyone familiar enough with AJAX to help me with this problem of getting more than 1 div block on a page updating at the same time using AJAX?

karlosdpm
11-16-2012, 10:58 PM
This post might be helpful for you:
http://www.kmbytes.com/blog/how-to-make-ajax-to-work-in-internet-explorer/

It worked for me!



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum