Rhyono
Rhyono

Reputation: 2468

Update portion of page using Ajax without jQuery

The page is mostly in PHP and only lightly uses any JavaScript, so I do not wish to use jQuery when it must be possible without it. I want to update a portion of a page, but I'm not very experienced with Ajax. jQuery's method was to use the page's URL with "#sectionid" after it.

Upvotes: 2

Views: 553

Answers (1)

Matt Wonlaw
Matt Wonlaw

Reputation: 12473

All the information you'd need to know to hand-roll your own is here:

https://developer.mozilla.org/en/XMLHttpRequest

You'll be interested in the send, open, response, readyState and onreadystatechange sections of the documentation.

onreadystatechange will fire whenever the readyState of your request changes. Once your readyState has changed to done you can check the response you received.

Make sure when you open you open in async mode. You don't want to freeze your page by making synchronous http requests.

if you need it running on older versions of I.E. wikipedia has some good information: http://en.wikipedia.org/wiki/XMLHttpRequest#Support_in_Internet_Explorer_versions_5.2C_5.5_and_6

I assume you know how to use document.getElementById and element.innerHTML to set the content of your element.


EDIT Went ahead and added a basic implementation:

if (window.XMLHttpRequest) {// IE7+, Firefox, Webkit, Opera
  window.xmlhttp = new XMLHttpRequest();
} else {// IE6, 5
  window.xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
     document.getElementById("someId").innerHTML = xmlhttp.responseText;
  }
}

xmlhttp.open("GET", "pageUrl", true);
xmlhttp.send();

Upvotes: 4

Related Questions