Basic AJAX connection using the POST method to retrieve content
Hello guys,
I have been working on a project for school which used AJAX and I just wanted you guys to have this code for reference. This code basically makes a call to a PHP script which gets Zip Code information (city and state) and then adds them into your web page. I used a span tag with id of ???zipinfo??? to act as a holder for the content that was going to be retrieved. Hopefully this helps some of you in your projects.
//Get Zip Code Information
function zipInfo(zipcode) {
fieldValue = ???connection=zipInfo&zip=???+zipcode;
var url=???includes/management.php???;
httpRequest(???POST???, url, true, fieldValue, function(result){
document.getElementById(???zipInfo???).innerHTML = result;
});
}
//AJAX Request
function httpRequest(reqType, url, asynch, fieldValue, callback) {
request = new XMLHttpRequest();
request.open(reqType,url,asynch);
request.setRequestHeader(???Content-type???, ???application/x-www-form-urlencoded???);
request.setRequestHeader(???Content-length???, fieldValue.length);
request.setRequestHeader(???Connection???, ???close???);
request.send(fieldValue);
request.onreadystatechange = function() {//Call a function when the state changes.
if(request.readyState == 4 && request.status == 200) {
callback(request.responseText);
}
}
}