How to make a simple jQuery Ajax request

jQuery is an amazing javascript framework. It‘s makes Ajax so easy. You don‘t have to know anything about Ajax to use it. I‘ve made a simple example on how to use jQuery to make an Ajax request. First, start with creating a database with the name jquery_ajax. I‘ve included the sql dump in the example. In the database there‘s 1 table, called comments. Then we‘ll need to include jQuery in our html file. Next, add a div with a class loading. In the css file the loading class is hidden so we‘ll use

display: none

to hide it. You can call the  jQuery.approve() function on whatever DOM element you like. Here we‘ll pass on 1 parameter (the id of the comment to be approved) to the function. 

these two line of code change the value of the button to approved and let it fade out slowly.

$('#'+commentid).attr("value","approved");
$('#'+commentid).fadeOut('slow');

The function Ajaxstart and Ajaxstop are standard jQuery function that execute instruction at the start and end of an ajaxrequest. These functions make it easy to display a loading notification while the request is being executed. this is the full code:

    $(document).ready(function() {
        //Loading notification
        $('.loading').ajaxStart(function() {
            $(this).show();
        }).ajaxStop(function() {
            $(this).hide();
        });
       
        //Ajax request
        jQuery.approve = function(commentid) {
                $.get('approved.php?id='+commentid, function(data) {});
                $('#'+commentid).attr("value","approved");
                $('#'+commentid).fadeOut('slow');
        }
    });

Download the example files:

download

Leave a comment