Simple jQuery AJAX Post and Response
Posted by matthew | Posted in Code Snippets | Posted on 24-11-2009
Tags: AJAX, Javascript, jQuery
0
jQuery is an extremely powerful library, one of the things it does really well is Ajax, this post shows how to send a request and post the response on to the page.
To use this function ensure you have the jQuery library included before you use this function.
function ajaxPost(returnDiv,myData) {
document.getElementById(returnDiv).innerHTML = "";
$.ajax({
type: "POST",
url: "/call.php",
data: "var=" + myData,
success: function(response){
document.getElementById(returnDiv).innerHTML = response;
}
});
}
To use the function simple use something like this:
onclick="ajaxPost(this.id, 'cats');"
This function will send an AJAX request on an ‘on click’ event, the response will be posted back to element ID the ‘on click’ is attached to (this can easily be replaced with any ID e.g. ‘myid’).
The data parsed is ‘cats’, again this could be ‘this.value’ if the element is a text box or even ‘this.innerHTML’ if you want to parse everything inside this element or any other string.
The function will always post the query to the page ‘call.php’ this can be changed to whatever you like.
The last thing to remember is to sanitise the POST values within the PHP page, just to ensure no injection happens.



