What is AJAX?
AJAX stands for Asynchronous Javascript And Xml. AJAX is not a language. Instead, it is a set of functionality built into JavaScript that allows the JavaScript to call out to other pages without leaving the current page. Most often, the JavaScript calls out to a server side page (like a php page), that returns information to the JavaScript. The JavaScript then processes the result and dynamically makes changes to the current page.
AJAX can be written in pure JavaScript, but JQuery provides a much easier interface. To use AJAX in JQuery, use the following function:
$.ajax()
The .ajax() method has a number of properties that can be set. The most important/common properties are:
- url: the name/path to the server side page being queried
- type: the method to pass the information, POST is the norm
- data: a comma separated list of name:value pairs. The names become the post keys. The values can be hard coded or pulled from the calling page using standard JQuery methods.
- success: instructions on what to do with a successful connection to the server. The success property can be set to a callback function that receives the information being returned to the page. This information can then be displayed or used to make decisions about other actions that should happen in the page.
Here is an example of these properties in action:
$.ajax({
url: "script.php",
type: "POST",
data:{
key1: "value1",
key2: "value2",
key3: "value3"
},
success:function(data){
//do stuff based on data
}
});
AJAX results can be used to add information, delete information or alter information on a page using JQuery. Often, we see items change color or items be modified based on the data returned from the server.
The code that exists on the server page can do anything that server code can do. That includes reading text files, processing POST input, accessing a database, etc. To return information to a calling page from a server page, simply echo the information. Be aware, all information echoed will be returned. So, if you want to echo things based on options, use else if chains. Another option is to return several pieces of information separated by a delimiter that can then be picked apart by the JavaScript. Here is a simple server side page that could be a response to an AJAX query:
echo "hello";