Back to blog

jQuery Ajax call tutorial


Somehow I got a lot of questions about jQuery and Ajax, which is quite easy to understand.
I’ll show you how to create an ajax call using jQuery and update the page without reloading.

I assume you have knowledge of HTML, CSS and basic HTTP techniques.

First we’re going to create our HTML document.

Our HTML5 document


<!doctype html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>My jQuery Ajax test</title>
		<style type="text/css">
			#mybox {
				width: 300px;
				height: 250px;
				border: 1px solid #999;
			}
		</style>
	</head>
	<body>
		The following div will be updated after the call:<br />
		<div id="mybox">
			
		</div>
		<input type="button" value="Update" />

	</body>
</html>

As you can see it’s a simple HTML5 document with a little style, a DIV element and a button.

jQuery

You may have noticed jQuery isn’t included yet. You can include it through a CDN (Content Delivery Network) or host it yourself.
See http://docs.jquery.com/Downloading_jQuery for more ways to include jQuery.

Add the following between the <head></head> tags of our HTML5 document:


<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>

At the time of this writing we use jQuery 1.11.0.

Your Ajax call

Create the following code between the <head> and </head> tags, for example below the jQuery source.


<script>
	
	function myCall() {
		var request = $.ajax({
			url: "ajax.php",
			type: "GET",			
			dataType: "html"
		});

		request.done(function(msg) {
			$("#mybox").html(msg);			
		});

		request.fail(function(jqXHR, textStatus) {
			alert( "Request failed: " + textStatus );
		});
	}
</script>

That’s it! Lets break it down a little:


function myCall() {
		var request = $.ajax({
			url: "ajax.php",
			type: "GET",			
			dataType: "html"
		});

Here you’re creating a function called “myCall” which will make the actual request to a file on your server called “ajax.php”.
We’re using GET HTTP-request to send our data to the server.
The expected type of the return code is HTML.


request.done(function(msg) {
	$("#mybox").html(msg);			
});

When the request is done fetching our data from ajax.php it will update the DIV “#msgbox” with the output of ajax.php
If the request fails it will show an alert message with the failure message.

To make the actual call add this to the input button element:


<input type="button" value="Update" onclick="myCall();" />

When you press the button it will execute your function “myCall()” we’ve created earlier.

Server-side script

In this tutorial we’ll create a PHP file that will act as the ajax callable file. You could use any server-side scripting language you prefer.


<?php
echo '<p>Hi I am some random ' . rand() .' output from the server.</p>';

Save the above code as “ajax.php” and make sure you upload it in the same spot as the HTML document.

You should now have 2 files in the same folder, one is the HTML document:


<!doctype html>
<html>
	<head>
		<meta charset="utf-8" />
		<title>My jQuery Ajax test</title>
		<style type="text/css">
			#mybox {
				width: 300px;
				height: 250px;
				border: 1px solid #999;
			}
		</style>
		<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
		<script>							
				function myCall() {
					var request = $.ajax({
						url: "ajax.php",
						type: "GET",			
						dataType: "html"
					});

					request.done(function(msg) {
						$("#mybox").html(msg);			
					});

					request.fail(function(jqXHR, textStatus) {
						alert( "Request failed: " + textStatus );
					});
				}
			
		</script>
	</head>
	<body>
		The following div will be updated after the call:<br />
		<div id="mybox">
			
		</div>
		<input type="button" value="Update" onclick="myCall()" />

	</body>
</html>

And the PHP file “ajax.php”:


<?php
echo '<p>Hi I am some random ' . rand() .' output from the server.</p>';

Refresh your browser and press the button a few times. You’ll see the div will update itself with the output of the ajax file.

Labels: ajax html javascript php

26 Responses

  1. Nice article :)
    J also write something about jQuery and AJAX :)
    http://www.matw.pl/blog/2012/12/jquery-ajax

  2. example is fine

  3. tawana on March 27, 2013

    just what i was looking for. Thanx

  4. Great example, thanks!

  5. Zeke on March 31, 2013

    WAY TO GO! You’re the only one to keep it genuinely simple and graspable. Everyone else seems to be showing off in some way or another and making it incomprehensible!

  6. philipp on April 23, 2013

    Thank you for this awesome tut!

  7. very very nice tuttorial. thenk u for ajax :)

  8. Irina on April 25, 2013

    The example not working for me in Chrome 26.0.1410.65 on a server behind a firewall.
    (works in other browsers, thanks a lot! )

  9. For whatever reason, I’ve been struggling with the implementation of AJAX calls (until now). This is the first post that I’ve seen that clearly lays out how to implement this. Thanks!

    • Peter Prins on May 22, 2013

      Hi Craig,

      Thanks for your kind reply. I will add another jquery ajax tutorial online in a few days.

  10. Thanks! This was a very good explanation and example.

  11. Selva on December 2, 2013

    Thanks! This was a very good explanation and example. :)

  12. Lots of people have knowledge. Its nice to run into someone who has the ability to explain things in a clear and logical manner. Thanks.

  13. Cornel on January 23, 2014

    If one wanted to show some text from a MySQL database instead of using <?php echo '[some text]';, would one replace "echo '[some text]'" with php code that makes a connection to the database?

  14. Naleen Yadav on February 1, 2014

    thanx :)

  15. Dhaval Motka on April 18, 2014

    thanx…..good example

  16. Fenwick Hall on April 28, 2014

    Please notice that it is a great talent, not common, to explain code in such understandable way
    Extremely useful in making a design decision, Appreciated.

  17. vipin on April 30, 2014

    nice article :)

  18. richr on May 4, 2014

    I’ve found this article very helpful. Just something odd I ran into on Windows 8.1 (IE11), the random number did not increment. So I changed to show the date time (seconds) and same issue occurred, the time stayed the same. The issue has something to do with cache refresh. I tried using ctrl+f5 and still doesn’t work. I found I had to use F12, ctrl+4 and made sure ‘always refresh from server’ is selected. Once set, then each time the button was pressed, the time (including second changed). Is there a PHP or some other function to make sure the refresh from server is on?

    If I show the page again and click update the time does not change. I have to redo the setting of ‘always refresh from server’.

    • Peter Prins on May 4, 2014

      I think there is a cache service running on the server (backend). You could try to call the url with random get parameters from the client (Javascript): e.g. /search.php?r=843132132 which could be a timestamp.

      But if I was you I’d check if there is some cache service running.

    • richr on May 4, 2014

      Peter, actually the solution is on the client side and IE 11. In Internet options, on the General tab click Setting (Browsing History). For the Website Data Setting/Temporary Internet Files click “Every time I visit the webpage” for “check for newer versions of stored pages:”, click ok and ok again.

      At this point, you can click the update button and (in my case), the current time will show and update each and every time clicked.

      Question: is there a way to make sure this option is set for IE and if not set, to make sure it is set (JS, php, …)?

    • Peter Prins on May 5, 2014

      No you can’t alter browser settings. You can however “force cache referesh” from php. You need to set a few headers before the output, for example:

      header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1
      header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past

      Even when this is not enough you should pass random get variables to the url like I said in my previous comment. Caching is very important but can be a real pain in the a :)

  19. abon on July 23, 2014

    very easy to understand, thank you.

  20. Johnk84 on August 9, 2014

    Its really a great and useful piece of information. Im glad that you shared this useful info with us. Please keep us informed like this. Thanks for sharing. eddkadeeedde

  21. Shubham Verma on August 16, 2014

    Thanks for this great tutorial, its such a nice tutorial for beginners.
    Can you please tell me, if I want to fetch the records form the database such like ajax.php?id=1 then how can I fetch records form the database and convert it into JSON in PHP(decode) and in jquery encode it again and through output in div?
    Sorry for my bad english.

Drop a note