jQuery Get() and Post() Methods

The jQuery get() and post() methods allows you to easily send a HTTP request to a page and get the result back. They are both static methods, which means that instead of instantiating a jQuery object and then working with that, we call get() or post() directly on the jQuery class, either by writing jQuery.get() or by using the shortcut character like this: $.get().

Other useful jQuery articles:

Both functions expect several parameters:

$.get( url, [data], [callback], [type] )

$.post( url, [data], [callback], [type] )

url: required – Specifies the url to send the request to.

data: optional – Specifies data to send to the server along with the request.

callback: optional – Specifies the function to run if the request succeeds.

type: optional – The type of data expected from the server. Possible types are xml, html, text, script, json.

Shorthand Ajax function with dataType GET:

$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});

This example fetches the requested HTML snippet and inserts it on the page.

Success handler:

$.get('test.html', function(data) {
$('.result').html(data);
alert('Loading...');
});

Shorthand Ajax function with dataType POST:

$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});

The success callback function is passed the returned data, which will be an XML root element.

Success handler:

$.post('test.html', function(data) {
$('.result').html(data);
})

Pages fetched with POST are never cached. This example fetches the requested HTML snippet and inserts it on the page.

Using $.ajax() function:

It is the most powerful among all these function because it is a raw function. Raw function means that it is the base function for all other like get, post, load etc. Behind the scene all functions rely on ajax function.

Content of ajaxLoad.html is:

<div id="firstDiv">This is first div.</div>
<div id="secondDiv">This is second div.</div>

Example:

<div id="targetPoint">Target Point</div>

<script type="text/javascript">
$.ajax({
url: 'ajaxLoad.html',
dataType:'json',
type:'POST',
data: name,
success: function(mydata){
alert("Success");
$('#targetPoint').html(mydata);
},
error: function(){
alert("Error");
}
});
</script>

The targeted element in example is div element with id=targetPoint. Thank you for letting me share these examples with you. I’d love to hear your thoughts in the comments.