Jump to content

Recommended Posts

Posted (edited)

Has anyone ever used xmlhttp before? I'm trying to make a simple GET request and then refresh the current page. I know thats not really what you're supposed to do, you're normally supposed to grab the returned contents and use it somewhere on the current page. Nevertheless, the code i'm using is as follows.

 

> xmlhttp.open("GET", url,  true);
 xmlhttp.send(null);
 window.location.reload();

 

This code works most of the time, but every so often the request doesn't get made before the page reloads. Any ideas on how I can get something like this working 100% of the time.

 

Here are some of the sites i'm looking at.

http://www.web-design-forum.com/article_554

http://jibbering.com/2002/4/httprequest.html

Edited by section31
Posted

I've never used it, but I did a little searching on the net and I believe I know what your problem is.

>xmlhttp.open("GET", url,  true);

The third parameter ('true' in this case) specifies whether the request is made synchronously (false) or asynchronously (true). Asynchronous requests are done "in the background" and execution of your script continues while the request is processing. Your window.location.reload(); will execute unless the page request finishes before the script gets to that line.

 

You need to either wait for the asynchronous open command to finish before reloading your page, or you need to execute a synchronous open command, which will halt code execution until the page load completes (but may make the browser appear to be hung, depending on how long the page request takes).

 

Asynchronous open - Using event to trigger window reload when page request is complete:

>xmlhttp.open("GET", url,  true);
xmlhttp.onreadystatechange = handleResponse;
xmlhttp.send(null);

// Script execution continues...

function handleResponse() {
  if ( xmlhttp.readyState == 4 ) {
      window.location.reload();
  }
}

 

Synchronous open - Script execution stops until page request is complete:

>xmlhttp.open("GET", url,  false);
xmlhttp.send(null);
window.location.reload();

Hope this helps...

Posted (edited)

Wow, I think it worked...so far so good. For some reason I didn't even think about changing that parameter. Thanks a lot David. If the problem recurs, I'll let you know :thumbup1:

Edited by section31

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...