Mar 4, 2010

////

AJAX made Simple with jQuery

There are lot of ways to do AJAX in jQuery but I was used of the $.post() and the $.get() functions. I find them the most simple.
Note: $.get() and .get() are two different functions. Don't get confused.

$.post( url, [ data ], callback )
$.post() - Load data from the server using a HTTP POST request. This is a shorthand of the $.ajax() function with type set to POST.

$.get( url, [ data ], callback )
$.get() - Load data from the server using a HTTP GET request. This is a shorthand of the $.ajax() function with type set to GET.

url A string containing the URL to which the request is sent.
data A map or string that is sent to the server with the request.
callback A callback function that is executed if the request succeeds.

Example: Fetches the contents of test.php and inserts it on the element with the class result.
$.post('test.php', function(data) {
$('.result').html(data);
});
or
$.get('test.php', function(data) {
$('.result').html(data);
});

Example: Request the test.php page, but ignore the return results.
$.post('test.php');
or
$.get('test.php');
Example: Request the test.php page and send some additional data along (while still ignoring the return results).
$.post('test.php', { name: 'John', time: '2pm' } );
or
$.get('test.php', { name: 'John', time: '2pm' } );
Example: pass arrays of data to the server (while still ignoring the return results).
$.post('test.php', { 'choices[]': ['Jon', 'Susan'] });
or
$.get('test.php', { 'choices[]': ['Jon', 'Susan'] });
Example: send form data using ajax requests
$.post('test.php', $('#testform').serialize());

Jquery made it simple. Stupid me making ajax functions from scratch before. I even noted the very basic of Ajax for reference. lol

0 Reactions to this post

Add Comment