GC Blog

Feed Rss

Basic AJAX connection using the POST method to retrieve content

07.12.2010, AJAX, by .

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);
}
}
}

Get your social on!

One Response to Basic AJAX connection using the POST method to retrieve content

  1. 2010-07-23 at 21:57 Jennifer

    Hey! I like your site. I especially like the blog you set up – very nice!
    ;)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>