DEV Community

Cover image for Ajax Loading in jQuery using PHP
Code And Deploy
Code And Deploy

Posted on • Updated on

Ajax Loading in jQuery using PHP

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/jquery/ajax-loading-in-jquery-using-php

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

In this post, I will show you how to add an ajax loader using jQuery when the ajax request is in progress to your PHP. It is important to show a loading on your ajax request so that your user will know that your request is still in progress and it is more important if you're fetching large content from your server-side.

Ajax Loader CSS Style

We are using CSS for our loader so that we don't need to load an image from our server. So, here is the code below. You can find this code at styles.css file inside assets/css folder if you download this complete code.

/*Ajax Loading*/
.ajax-loader,
.ajax-loader div {
  box-sizing: border-box;
}
.ajax-loader {
  display: inline-block;
  position: relative;
  width: 80px;
  height: 80px;
}
.ajax-loader div {
  position: absolute;
  top: 33.33333px;
  width: 13.33333px;
  height: 13.33333px;
  border-radius: 50%;
  background: currentColor;
  animation-timing-function: cubic-bezier(0, 1, 1, 0);
}
.ajax-loader div:nth-child(1) {
  left: 8px;
  animation: ajax-loader1 0.6s infinite;
}
.ajax-loader div:nth-child(2) {
  left: 8px;
  animation: ajax-loader2 0.6s infinite;
}
.ajax-loader div:nth-child(3) {
  left: 32px;
  animation: ajax-loader2 0.6s infinite;
}
.ajax-loader div:nth-child(4) {
  left: 56px;
  animation: ajax-loader3 0.6s infinite;
}
@keyframes ajax-loader1 {
  0% {
    transform: scale(0);
  }
  100% {
    transform: scale(1);
  }
}
@keyframes ajax-loader3 {
  0% {
    transform: scale(1);
  }
  100% {
    transform: scale(0);
  }
}
@keyframes ajax-loader2 {
  0% {
    transform: translate(0, 0);
  }
  100% {
    transform: translate(24px, 0);
  }
}
Enter fullscreen mode Exit fullscreen mode

Ajax Loader Javascript Function

In this function, we have two actions show and hide for this ajax loader. You can find this code inside assets/js/scripts.js.

/**
 * Ajax loader function
 *
 * @param {string} selector - The trigger element
 * @param {string} action - The action (show|hide) you want to apply of this function
 * @return {any}
 */
function ajaxLoader(selector, action) 
{
    var $class = "ajax-loader";

    $html = '<div class="'+$class+'"><div></div><div></div><div></div><div></div></div>';

    if(action == "show") {
        $($html).insertBefore(selector);
    } else if(action == "hide") {
        $("."+$class).hide();
    }

}
Enter fullscreen mode Exit fullscreen mode

Code Implementation

Since have already our ajax loader CSS and javascript function. Then next we will implement it in our ajax request. Here is the sample code below:

// Ajax config
$.ajax({
    type: "GET", //we are using GET method to get all record from the server
    url: 'all.php', // get the route value
    beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
        ajaxLoader("#employees-list", "show");
    },
    success: function (response) {//once the request successfully process to the server side it will return result here

    },
    complete: function() {
        ajaxLoader("#employees-list", "hide");
    }
});
Enter fullscreen mode Exit fullscreen mode

As you can see we have an ajax() function and we add our ajaxLoader() function inside beforeSend() function to show our loader when processing the ajax request and in complete() function we add also the ajaxLoader() function to hide the loader when the ajax request is complete.

About beforeSend() and complete() function in ajax

beforeSend() - will execute before AJAX request is processed

complete() - will execute after AJAX request is finished either sucess or failed

Complete Ajax Implementation

Now let's implement this in my previous tutorial code when getting the employees list or all records from the database. Here is the javascript code below.

function all() 
{
    // Ajax config
    $.ajax({
        type: "GET", //we are using GET method to get all record from the server
        url: 'all.php', // get the route value
        beforeSend: function () {//We add this before send to disable the button once we submit it so that we prevent the multiple click
            ajaxLoader("#employees-list", "show");
        },
        success: function (response) {//once the request successfully process to the server side it will return result here

            // Parse the json result
            response = JSON.parse(response);

            var html = "";
            // Check if there is available records
            if(response.length) {
                html += '<div class="list-group">';
                // Loop the parsed JSON
                $.each(response, function(key,value) {
                    // Our employee list template
                    html += '<a href="#" class="list-group-item list-group-item-action">';
                    html += "<p>" + value.first_name +' '+ value.last_name + " <span class='list-email'>(" + value.email + ")</span>" + "</p>";
                    html += "<p class='list-address'>" + value.address + "</p>";
                    html += "<button class='btn btn-sm btn-primary mt-2' data-toggle='modal' data-target='#edit-employee-modal' data-id='"+value.id+"'>Edit</button>";
                    html += "<button class='btn btn-sm btn-danger mt-2 ml-2 btn-delete-employee' data-id='"+value.id+"' typle='button'>Delete</button>";
                    html += '</a>';
                });
                html += '</div>';
            } else {
                html += '<div class="alert alert-warning">';
                  html += 'No records found!';
                html += '</div>';
            }

            // Insert the HTML Template and display all employee records
            $("#employees-list").html(html);
        },
        complete: function() {
            ajaxLoader("#employees-list", "hide");
        }
    });
}
Enter fullscreen mode Exit fullscreen mode

You will find the code above inside "assets/js/scripts.js" when you download this complete code.

So you have an idea of how to implement the AJAX loader using jQuery and PHP. I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/jquery/ajax-loading-in-jquery-using-php if you want to download this code.

Advanced Laravel SAAS Starter Kit with CRUD Generator

Advanced Laravel SAAS Starter Kit with CRUD Generator - GET YOUR COPY NOW!

Happy Coding :)

Top comments (0)