LearnBeginner’s Guide to Ajax Development with PHP

   
Avatar

Jake Rocheleau
writes on November 12, 2013

The common use of Ajax in web development has created a dynamic yet fluid Internet. Designers often build mockups which incorporate Ajax-based elements such as lazy loaders, tabbed widgets, and other similar page elements.

In this tutorial I want to delve into a basic example of handling Ajax development with PHP on the backend. Normally you would connect this into a database using an engine like MySQL, but for this tutorial I want to focus on handling the response from PHP, and how you can use this response to append new content onto the page. Take a peek at my live sample demo to get an idea of what we are creating.

Also read: 6 Must-Have Tools in a PHP Developer’s Toolkit

ajax php web development with jquery tutorial howto screenshot

Live DemoDownload Source Code

Starting with jQuery Ajax

When coding in standard JavaScript we are stuck using a method called XMLHttpRequest. The jQuery Ajax method is a more simplified way of handling this HTTP request, and you have a large index of documentation explaining each of the various options. I’ll be demonstrating two different styles of handling Ajax requests using different return values from PHP.

First I’ve created a new page, index.html, along with a related stylesheet. I won’t go over these codes so if you’re interested just download the project source. I also downloaded a local copy of jQuery along with a blank JavaScript file named ajax.js.

  <div class="heading"> 
    <h2>Someuser's Profile</h2>
    <h3>Joined Nov 1st, 2013 - <span id="followercnt">18</span> Followers</h3>
    <div id="followbtncontainer" class="btncontainer"><a href="#" id="followbtn" class="bigblue">Follow</a></div>
  </div><!-- @end .heading -->

....

    <div id="loadmorefollowers">
      <a href="#pg1" id="morefllwrs" class="bigblue thinblue">Load more followers</a>
    </div><!-- @end #loadmorefollowers -->

Above I have combined two bits of code from my HTML which are located at different sections in the page. The anchor link using an ID of #followbtn will trigger an event callback when clicked. The same goes for the other anchor link, #morefllwrs. However these events will run different callback functions, and they both expect a different type of request using Ajax.

We can start by looking at the follow button example and how this behavior works.

Simple Ajax Actions

Many social networks like Twitter and Pinterest use Ajax to auto-update the page once you follow a new profile. This would obviously require connecting into a database for any live application, but for this example we can write the PHP as if we already connected into the database. First let’s take a peek at the JS codes.

$(function(){
  $('#followbtn').on('click', function(e){
    e.preventDefault();
    $('#followbtn').fadeOut(300);

    $.ajax({
      url: 'php/ajax-follow.php',
      type: 'post',
      data: {'action': 'follow', 'userid': '11239528343'},
      success: function(data, status) {
        if(data == "ok") {
          $('#followbtncontainer').html('<p><em>Following!</em></p>');
          var numfollowers = parseInt($('#followercnt').html()) + 1;
          $('#followercnt').html(numfollowers);
        }
      },
      error: function(xhr, desc, err) {
        console.log(xhr);
        console.log("Details: " + desc + "\nError:" + err);
      }
    }); // end ajax call
  });

Once the button is clicked we need to call e.preventDefault to stop the href value from loading a hash symbol into the address bar. Then I’m using .fadeOut() on the button to remove it from the page so that a user doesn’t try clicking twice. You will notice the Ajax request has a lot of different options – certainly not the whole catalog but enough to get us going. I’ll break them down individually so you can understand how the Ajax call works.

  • url – the external URL to which we are sending the request. In this case I’ve organized all my Ajax PHP scripts into a folder and this one calls ajax-follow.php.
  • type – the request method, POST or GET.
  • data – what content are we passing to the PHP file? It should be organized like a JSON string with key:value pairs. So in PHP we can get the ‘action’ value by using $_POST[‘action’].
  • success – if the Ajax request runs successfully then we either call a separate function or write the callback inline. I usually write the function right within Ajax because it’s often much easier.
  • error – if the Ajax request fails, or somehow gets an error in the response, this alternative function is triggered. Usually helpful when debugging issues between JS and PHP.

I’ve structured this call so it could work for any simple common action we need to take. The ‘action’ found in our data string could be anything including unfollow, block, send a friend request, etc. The ‘userid’ is just made-up for my example but you’ll need this to be accurate when updating info in a database.

if($_POST['action'] == "follow") {
  /**
   * we can pass any action like block, follow, unfollow, send PM....
   * if we get a 'follow' action then we could take the user ID and create a SQL command
   * but with no database, we can simply assume the follow action has been completed and return 'ok'
  **/

  echo "ok";
}

So now inside ajax-follow.php we can see a very simple block of logic which checks for the action parameter. If we have it set to ‘follow’ then we could run some code that connects into the database and creates a new following relationship from the logged-in user and the current profile. At the end if it all works then we can return any value – I’ve chosen a string ‘ok’.

If you look back in the Ajax code you’ll see we run a logic check for if(data == “ok”). We only want to update the page with a success message if PHP has created the follow relationship. You might also notice we can update the number of followers on the page using a JavaScript method parseInt().

JSON Return Data in PHP

For the second bit of Ajax we want to dynamically load a full list of followers on this user’s profile. We can see this person has 18 followers and only 10 are displaying by default. Each click will load 5 more followers until we have loaded them all. Since we know how Ajax connects into PHP let’s first start with the backend file ajax-followers.php.

header("content-type:application/json");

$pg1 = array(
       array
       (
            'username' => 'facingdown',
            'profile_pic' => 'img/default-avatar.png'
       ),
       array
       (
            'username' => 'doggy_bag',
            'profile_pic' => 'img/default-avatar.png'
       ),
       array
       (
            'username' => 'goingoutside',
            'profile_pic' => 'img/default-avatar.png'
       ),
       array
       (
            'username' => 'redditdigg',
            'profile_pic' => 'img/default-avatar.png'
       ),
       array
       (
            'username' => 'lots_of_pudding',
            'profile_pic' => 'img/default-avatar.png'
       ),
       'nextpage' => '#pg2'
);

PHP uses a special function called header() for setting properties of the page during rendering. In this case we don’t want the data returned as plaintext, but instead using application/json as JSON data. This is formatted in a way that jQuery can easily loop through each follower and then append them into the list.

Notice all I’ve created are simple PHP arrays that contain a profile username and their avatar. There is a $pg1 and $pg2 variable which indicates each of the pages we can load. All of this info could be pulled out of MySQL and would appear in similar syntax using something like mysqli_fetch_assoc().

if($_POST['page'] == '#pg1')
  echo json_encode($pg1);

if($_POST['page'] == '#pg2')
  echo json_encode($pg2);

exit();

After both arrays have been defined you’ll see this block of code at the bottom. We check which page is needed by calling upon a variable passed in through jQuery $_POST[‘page’]. Whether it’s page 1 or 2 we just need to json_encode() the array and simply echo it out onto the page(since our document type is application/json). PHP’s exit() is a friendly way of terminating the script when its sole purpose is meant for Ajax calls.

Loading Followers with Ajax

This last bit of code inside ajax.js is much more convoluted than the earlier block. But this is the reason why I wanted to introduce two distinct methods of PHP/Ajax because there is so much to learn about this topic.

  $('body').on('click', '#morefllwrs', function(e){
    e.preventDefault();
    var container = $('#loadmorefollowers');

    $(container).html('<img src="img/loader.gif">');
    var newhtml = '';

Before even getting to the Ajax request let’s delve deeper into the actual event handler. Notice that my selector is targeting the page body and we pass the #morefllwrs button as a parameter to the .on() method. The purpose is to handle clicks on the same link which gets dynamically appended into the page. So right when the DOM loads jQuery will target the first link, and a user will click to load more followers, but in order to get another button to appear we need to add HTML onto the page using jQuery.

Free trial on Treehouse: Do you want to learn more about Ajax and PHP development? Click here to try a free trial on Treehouse.

This means whenever the user clicks the button a second time, it normally wouldn’t register because it wasn’t part of the original DOM so jQuery doesn’t notice it. By using the whole body as our selector it will keep listening for the click event including new elements which are added to the page after loading. The other code inside just creates variables, and then we replace the button HTML with a loading gif so the user doesn’t click twice.

$.ajax({
  url: 'php/ajax-followers.php',
  type: 'post',
  data: {'page': $(this).attr('href')},
  cache: false,
  success: function(json) {
	$.each(json, function(i, item) {
	  if(typeof item == 'object') {
	  newhtml += '<div class="user"> <a href="#" class="clearfix"> <img src="'+item.profile_pic+'" class="avi"> <h4>'+item.username+'</h4></a></div>';
	  } 
	  else {
		return false;
	  }
	}) // end $.each() loop

	if(json.nextpage != 'end') {
	  // if the nextpage is any other value other than end, we add the next page link
	  $(container).html('<a href="'+json.nextpage+'" id="morefllwrs" class="bigblue thinblue">Load more followers</a>');
	} else {
	  $(container).html('<p></p>');
	}

	$('#followers').append(newhtml);
  },
  error: function(xhr, desc, err) {
	console.log(xhr + "\n" + err);
  }
}); // end ajax call

Much of this syntax will look familiar because we are using the same jQuery function. In this case we need to call a different PHP file and we are passing a page value based on the button’s HREF attribute. It’s just one little trick we can use for dynamically-loaded page results. In fact, the biggest difference will be found inside the success function callback since we are using a type of jQuery .each() loop.

The response from PHP is held in a JS variable called json. We turn each array object inside the JSON string into a new variable called item. Since this is a very basic example the objects only have two keys – item.profile_pic and item.username. Any real-world example might include many more values.

One possibly confusing aspect of this loop is the very first logic check if(typeof item == ‘object’) used on each item. I’m doing this because each JSON response is comprised of profile objects, along with a string at the end called nextpage. When we get to this value we need to handle it differently because it won’t be added into the list, but instead it is used to build the new “Load more followers” button.

If this nextpage value is not ‘end’ then we know it contains some page value like #pg2. We can use this as the new button’s HREF attribute, which gets passed back into PHP to load the next set of followers. Once we hit the last JSON entry then we know there are no more pages. So we don’t append any new button and the loading gif is replaced instead by a single empty paragraph.

ajax php web development with jquery tutorial howto screenshot

Live DemoDownload Source Code

Closing

There are hundreds if not thousands of different purposes for creating an Ajax script. You might even connect into 3rd party APIs where you don’t need to host any backend files at all! Web development has advanced so quickly with the rise of open source projects like jQuery. Feel free to download a copy of my demo files and see if you can build any similar interfaces on your own web projects.

Want to learn more about coding, design and more? Try the Treehouse 7-day free trial today!

GET STARTED NOW

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Get Started

25 Responses to “Beginner’s Guide to Ajax Development with PHP”

  1. Thanks for the good writeup. It if truth be told was a enjoyment account it.
    Glance advanced to more added agreeable from you! By the
    way, how could we communicate?

  2. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Yes, Google (Google Maps), Yahoo (Flickr), Amazon (A9 Search),Gmail, Youtube, and Facebook tabs have been using it

  3. AJAX provides improved the consumer knowledge with desktop in addition to with mobile phones. Additionally, it has an essential function in abundant world wide web software and a lot of web 2. 0 software including Search engines, askjeeve, Microsoft company, Amazon and others.

  4. mritunjay pathak on August 8, 2017 at 11:34 am said:

    i am creating a project in which user can see his profile on login…but i want dashbord to load all other profile pages via ajax i.e. view profile,edit profile etc.

    so far what i done is
    made a home.php page sends ajax request to a load-page.php according to user request, load data checks the requested page and rends result back to home.php

    home.php

    $(document).ready(function(){
    loadPage(‘#dashbord’);
    })

    function loadPage(url) //the function that loads pages via AJAX
    {
    url=url.replace(‘#page’,”);

    $(‘#loading’).css(‘visibility’,’visible’); //show the rotating gif animation
    $.ajax({ //create an ajax request to load_page.php
    type: “POST”,
    url: “load-page.php”,
    data: {page:url}, //with the page number as a parameter
    dataType: “html”, //expect html to be returned
    success: function(msg){

    if(parseInt(msg)!=0) //if no errors
    {
    $(‘#pageContent’).html(msg); //load the returned html into pageContet
    $(‘#loading’).css(‘visibility’,’hidden’);//and hide the rotating gif
    }
    });

    load-page.php

    i want to use variables defined in home.php to use in pages coming from ajax, but the throw undefined index error.

  5. Being new to Ajax & a JQuery / JS n00b this was very useful !

    Wish I learnt javascript / jquery before I learnt PHP because you think of things that are so similar but totally different way of coding in different languages

  6. Thank you. Very Helpful Topic about AJAX for Beginners.

  7. Love the way you write and share the post with a proper guideline and PHP code to help us all. I always love PHP because my websites are dependent on them.

  8. Great tutorial, very simple and less code to write. The question or issue I am running into is how to send dynamic php script”$category.php” something like this in url and how to send the parameter to the dynamic php script in the ajax in data “Uniid=$uniid&Uid=$from” any inputs or help would be greatly appreciated.

  9. Nice tutorial for beginners. Thumbs up!

  10. The purpose of jQuery is to make it much easier to use JavaScript on your website.

    jQuery takes a lot of common tasks that require many lines of JavaScript code to accomplish, and wraps them into methods that you can call with a single line of code.

    jQuery also simplifies a lot of the complicated things from JavaScript, like AJAX calls and DOM manipulation.

    The jQuery library contains the following features:

    HTML/DOM manipulation
    CSS manipulation
    HTML event methods
    Effects and animations
    AJAX
    Utilities

  11. Ajax requests are triggered by JavaScript code; your code sends a request to a URL, and when it receives a response, a callback function can be triggered to handle the response. Because the request is asynchronous, the rest of your code continues to execute while the request is being processed, so it’s imperative that a callback be used to handle the response.

  12. Traditionally webpages required reloading to update their content. For web-based email this meant that users had to manually reload their inbox to check and see if they had new mail. This had huge drawbacks: it was slow and it required user input. When the user reloaded their inbox, the server had to reconstruct the entire web page and resend all of the HTML, CSS, JavaScript, as well as the user’s email. This was hugely inefficient. Ideally, the server should only have to send the user’s new messages, not the entire page. By 2003, all the major browsers solved this issue by adopting the XMLHttpRequest (XHR) object, allowing browsers to communicate with the server without requiring a page reload.

  13. Ajax is damn cool. It enables websites to load content into various elements without refreshing the page. ajax may not seem like a huge feature list but it allows us to do so much.

  14. Thank you for this article

  15. Madeindreams on January 13, 2016 at 9:47 pm said:

    Hi.

    Thank you for this article its finally introduced me to Json.

    I was wondering why you example wasnt working for me.

    When my php file returned ok the ajax function would return a error and i could see that the response was there “ok” but it was followed by to arows (enter like symbols) so i have tryed to json_encode my ok response and it worked. I dont know yet why.
    I did have the header set for json/app but ???.

    Well now i got it working so im going to play arround with it.

    Thank you

  16. Hi I tried your code and I get following error on my machine

    POST http://localhost:8000/php/ajax-follow.php 405 (Method Not Allowed)

  17. saeed mansour on October 16, 2015 at 2:06 pm said:

    Hi,
    This was a really helpful tutorial.
    I had just one question: Why didn’t you use the $.post() function ?? it’s much easier isn’t it?

  18. Thanks !!
    I spent almost 4 hrs and 18 tutorials but none was working. Yours had that small hint i wanted and I am done. Now I can easily upgrade my website with new features like email list. Keep it up.

  19. Great post and more interested article. very good explanation and make you feel the real interest in php development

  20. If it is something I do not understand is why in the success function of the second example(loading followers) the parameter passed instead of data is json.
    It is the first time I see such parameter being passed there.

    • Dimitris, that parameter is just the variable name for the data that is passed back to the success function. You can name it whatever you want. Because json is being passed back from the second PHP script example it’s useful to name the variable ‘json’, rather than just ‘data’.

  21. Excellent tutorial. php always looks messy to me but you’ve structured it in a very readable way there. Good job.

Leave a Reply

You must be logged in to post a comment.

man working on his laptop

Are you ready to start learning?

Learning with Treehouse for only 30 minutes a day can teach you the skills needed to land the job that you've been dreaming about.

Start a Free Trial
woman working on her laptop