jQuery Ajax

By Forrest Smith - Drempd.com

Making calls to the website’s database without page refreshes is pretty easy with jQuery. There are several functions that can be used, including load, get, and post:

Load

load() provides the ability to load an html file into an element:

$('#divContent').load('content_file.html');

With load(), you can even specify specific areas of a file to display. The following code will only insert the content of a div with the id of ‘news’:

$('#divContent').load('content_file.html #news');

Two functions work with sending and retrieving data from the server, get(), and post(), which is to be used if you will be changing data on the server.

Get

Use get() to retrive data from a server-side file.

$.get(url,data,callback function);     //data and callback are optional

Post

Use post() to send data to a server-side file.

$.post(url,data,calback function);   //data and callback are optional

data – the data to submit, formatted as: ‘{rating:5}’ //this is like saying rating=5

var data = {
     productID: 10,
     productName: 'Toilet Brush'
}
$.post('SubmitProduct.php',data);

The callback function will process once the the server-side processes have finished.

Serialize

This will take all of the form names and values and create a query string, which can then be sent to the server-side (php) file.

Given a form with the id of ‘login’:

var formData - $('#login').serialize();
$.get('login.php',formData);

This will submit a string of data to the ‘login.php’ file, like: ‘username=john&password=ceaser’. If using $.post, the values can be retrieved with php with a post statement: $username = $_POST[‘username’];

Error

Add this to the end of a post or get function to handle errors with the server or connection:

$.post('login.php',formData,successFunction).error(errorFunction);

Example: Getting a value from a php script and updating the values of a form

The following code will pass the variable ‘object_id’ to the php script ‘Post_act_GetData.php’, and then update the two form fields with the data given from the php script:

The jQuery:

var data = {
     object_id: 24
}
$.post('Post_act_GetData.php',data,function(return_data){
     $('#fld_Title').attr('value',return_data.post_title);
     $('#fld_Tags').attr('value',return_data.post_tags);
},'json');

The php script:
Echo the json_encode function to make the variables available to the jQuery script. The ‘object_id’ variable passed from jQuery, can simply be utilized from the $_POST[‘object_id’] variable.

echo json_encode(array("post_title"=>'my test title',"post_tags"=>'my test tags'));

Troubleshooting

It may be helpful to run the php script without interfacing with jQuery — any errors are easier to spot without complicating it with the jQuery aspect. Once everything is dialed in and working correctly, begin calling it from jQuery.