Possible Duplicate:
How to make an ajax call without jquery?
How do I asynchronously update a webpage using ajax without using jQuery?
Possible Duplicate:
How to make an ajax call without jquery?
How do I asynchronously update a webpage using ajax without using jQuery?
As a young new developer, I've gotten so used to JQuery that I've become intimidated of JavaScript (not like GetElementById JavaScript, but object oriented, passing functions on the fly and closures being the difference between failure and crying-with-joy JavaScript).
I'm providing this copy/pasteable POST ajax form, ignoring Microsoft's nuances, with minimal comments to help others like me learn by example:
//ajax.js
function myAjax() {
var xmlHttp = new XMLHttpRequest();
var url="serverStuff.php";
var parameters = "first=barack&last=obama";
xmlHttp.open("POST", url, true);
//Black magic paragraph
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", parameters.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
document.getElementById('ajaxDump').innerHTML+=xmlHttp.responseText+"<br />";
}
}
xmlHttp.send(parameters);
}
Here's the server code:
<?php
//serverStuff.php
$lastName= $_POST['last'];
$firstName = $_POST['first'];
//everything echo'd becomes responseText in the JavaScript
echo "Welcome, " . ucwords($firstName).' '.ucwords($lastName);
?>
and the HTML:
<!--Just doing some ajax over here...-->
<a href="#" onclick="myAjax();return false">Just trying out some Ajax here....</a><br />
<br />
<span id="ajaxDump"></span>
Hopefully having a POST ajax example to copy/paste, other new developers will have one less excuse to try JavaScript without the JQuery training wheels.
Get familiar with the XMLHttpRequest object then you can make good decisions about what (if any) JavaScript framework to use to work with it.
The best way to make an AJAX call these days is using JQuery. Anyway, here is an example for you from W3schools.com
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>