jQuery and Ajax – Ready to use code snippets for every day

The term AJAX was coined twelve years ago to describe a method of retrieving data from a server without requiring a page refresh. Amongst many other amazing features, jQuery is known for making the whole AJAX process way simpler. In this article, I have compiled ready-to-use code snippets for everyday needs: sending data with the GET and POST method, retrieving text or Json from remote pages, and more.


Note: this article doesn’t use the $ shortcut for the jQuery object.

Send data using the GET method

jQuery.get() is a shorthand AJAX function, which loads data from the server using a HTTP GET request. The following snippet shows how to send two values to a page named mypage.php.

jQuery( document ).ready(function() {
	jQuery.get( "mypage.php", { name: "John", time: "2pm" } )
		.done(function( data ) {
		alert( "Data Loaded: " + data );
	});
});

Send data using the POST method

Similar to jQuery.get(), jQuery.post() loads data from the server using a HTTP POST request. The code below demonstrates how to send a POST request to page.php when button is clicked.

jQuery("button").click(function(){
    jQuery.post("page.php", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

Retrieving text from a webpage

The jQuery.load() method makes it extremely easy to retrieve text from a specific webpage. The method allows to only fetch a specific part of the document, so you don’t have to get the whole page and parse it afterwards.

<ol id="new-projects"></ol>
 
<script>
jQuery( document ).ready(function() {
	jQuery( "#new-projects" ).load( "/resources/load.html #projects li" );
});
</script>

Get all values from form and send it to a page

Here’s a super handy snippet that I use very often. It works very simply: once the user clicks on #submit, the data from #form is serialized and sent to a remote page using the POST method.

jQuery( document ).ready(function() {
	jQuery( "#submit" ).click(function() {
		 jQuery.post( "https://yoursite.com/yourpage.php", jQuery('#form').serialize())
			.done(function( data ) {
			alert(data);
		}); 
		return false;
	});
});

Retrieve JSON data

Back in the early days of AJAX, data sent by a server was mostly formatted as XML. Nowadays, most modern applications use JSON as the format for data from the server.

The getJSON() method loads JSON-encoded data from the server using a GET HTTP request. The example below shows how to use jQuery to retrieve JSON-encoded data.

jQuery.getJSON( "http://yoursite.com/test.json", function( data ) {
        alert(data);
});

Once you get your JSON from the server, use the JSON.parse() method to turn the data into a JavaScript object:

jQuery.getJSON( "http://yoursite.com/test.json", function( data ) {
        var obj = JSON.parse(data);
        jQuery( "#container" ).html(obj.name + ", " + obj.age);
});