AJAX is a useful coding technique that allows for asynchronous requests to the server without the page needing to refresh. This is a useful method in creating modern websites where loading times must be cut as much as possible.
For this tutorial you will need to include jQuery within your HTML document, the jQuery package can be found
. This method we will be using is jQuery's $.ajax method.
A basic example
Javascript:
$.ajax({
type : 'GET',
url : "testScript.php",
success : function(response){
alert( response );
},
error : function(response){
alert( "Error: " + response );
}
});
PHP (testScript.php):
<?php
echo( "hello world" );
?>
In this example we are sending a request to the server for "testScript.php" which is specified in the "url" parameter of the function. We are also specifying the type of request in the "type" parameter to be "GET" (this can either be "POST" or "GET"). We also create to callback functions, one for if there is an error in the request and one for if the request is successful.
If the request is indeed successful the function will return a response from the request, in this case it would be the output of the PHP script being "hello world".
To add your own parameters to a GET request is quite simple, all you have to do is add them as a query string at the end of the request url like so:
url : "testScript.php?param1=hello¶m2=world"
This can then be accessed in PHP with:
$_GET["param1"]
For POST requests the easiest way would be to use a Form object, this can be created either by using an actual form element or by adding your own elements to the object, this can then be given as a value for the data parameter.
var formData = new FormData();
formData.append( "param1", "hello" );
formData.append( "param2", "world" );
//or var formData = new FormData( $( "#yourform" )[0] );
$.ajax({
type : 'POST',
url : "testScript.php",
data : formData,
success : function( response ){
alert( response );
},
error : function( response ){
alert( "Error: " + response );
}
});
If you plan on passing other types of data- such as images- you will need to set the value of processData to false, this will ensure that the data included in your form object are not processed into a query string which can sometimes have a limit based on the URL. For more info on asynchronous image uploading, have a look at
Another method for AJAX requests is xmlhttp which is the default method in Javascript without using jQuery, check out
for more information.