Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
Test HTTP Requests Tools Blog Learn Quizzes Smile API Log In / Sign Up
« Return to the tutorials list
We have updated the website and our policies to make sure your privacy rights and security are respected.
Click here to learn more about the way our website handles your data.

Remove this message.

A simple jQuery Ajax Request to PHP

Daniel Gheorghe Difficulty: 20 / 50 Tweet

This article is old. Be careful! It might contain outdated information.

simple-ajax-requests

This article was originally written in 2010. This is an updated version on how to do simple Ajax requests using jQuery

Ajax is a very nice tool for web developers. It helps you interact with the visitor without reloading the page. Searching the internet you will find various Ajax code samples that are simply too complicated and some are too specific. I added some comments that will better explain what the code does and how it can be tweaked. There's no PHP file here ... in it you just grab the data from the request (GET or POST) and do what you want with it.

    
        <script>
        jQuery(document).ready(function() {
            //you should replace submit with any selector that you use
            jQuery('#submit').click( function(e) {
                e.preventDefault(); //preventing the default functionality of the submit button aka... submitting the form and refreshing the page
                //then we build the data that will be submitted through the form
                var x = jQuery('input[name="the name of the input"]').val();
                var y = jQuery('input[name="the name of the other input"]').val();
                //let's concatenate the data:
                var data = 'x=' + x + '&y=' + y;
                jQuery.ajax({
                    //the path to the php file that handles the data
                    url: "dir/dir/file.php",
                    //I always use post, but get also works
                    type: "POST",
                    // the data that we built earlier
                    data: data,
                }).done( function (html) {
                        //Assuming that the PHP file will respond with '0' which means that something is wrong. I like to give codes to differentiate between error messages... For example: 0 would be wrong email, 1-another error, etc.
                            if (html!=='0')
                                alert('Thank you!');
                            else
                                alert('An error has occurred');
                    });
            });
        });
        </script>
    

I hope this is easy and straightforward enough for all you guys. Now all you have to do is create a PHP file that will handle the data sent by this jQuery script. This can be anything from form validation to database queries and so on. Thank you again for reading this!

Now let's get serious

AJAX was invented by Microsoft (really!) and the JavaScript object that stands behind it is "XMLHttpRequest". The above example, while easy to understand and implement is not necesarilly the best AJAX implementation. Below, I will write a much better function that sends a request to a server-side script and after receiving the result it alters the content of the web-page without the need to "refresh".

One of the reasons why the above is not the best implementation is because it uses jQuery which is an overhead if all you need is to create a simple AJAX request. Second reason is that using jQuery(document).ready (or window.onload if you're not using the framework), is only needed if you are placing the snippet of code above the '#submit' element. So placing the code just before you close your '</body>' tag is way nicer.

This being said let's try and translate the same functionality of the above code inside an immediately-invoked function expression with plain JavaScript (much nicer and a lot faster).

    
        <script>
            (function(win) {
                var simpleAjax = {
                    initialize: function (url, method, data, callback) {

                                    var xhr;

                                    /* See if the browser supports the XMLHttpRequest */
                                    if(typeof XMLHttpRequest !== 'undefined') 
                                        xhr = new XMLHttpRequest();
                                    else {
                                        alert('Please use a browser from this century');
                                        return;
                                    }

                                    /* See if the browser supports event listeners for XMLHttpRequest IE 10+*/
                                    if( typeof XMLHttpRequestProgressEvent === 'function' )
                                    {
                                        xhr.addEventListener("error", transferFailed, false);
                                        xhr.addEventListener("abort", transferFailed, false);
                                        xhr.addEventListener("load", transferComplete, false);
                                    }
                                    else
                                        xhr.onreadystatechange = seeIfWeAreGood; //older browsers

                                    xhr.open(method, url, true);

                                    //set the content type
                                    xhr.setRequestHeader("Content-Type", "application\/x-www-form-urlencoded");
                                    xhr.send(data);
                                     
                                    function seeIfWeAreGood() {
                                        //a ready state that is smaller than 4 means that the AJAX call is not yet done                                       
                                        // transfer has completed (make sure to check status codes 404, 500 etc... in the callback)
                                        if(xhr.readyState === 4)
                                            transferComplete();
                                        else
                                            return;
                                    }

                                    function transferFailed(){
                                        console.log('An error has occurred');
                                        /* do something on error */
                                    }

                                    function transferComplete(){
                                        /* do something when the request is complete  (make sure to check status codes 404, 500 etc... in the callback) */
                                        console.log('Everything is ok ... passing to the callback function');
                                        callback(xhr);
                                    }
                                }
                };
                simpleAjax.initialize('https://www.codepunker.com/atestfile.php', 'post', "a=1&b=2", function(xhr){ 
                     /* This is my nice callback function */ 
                    console.log(xhr.responseText);
                });
            }(window)); //pass the window object to the IIFE
        </script>
    

Breaking the above into pieces, here's what happened:

  • The initialize method first checks if "XMLHttpRequest" exists. Then it checks if the browser can use event listeners to handle the AJAX request and if not it falls back to the older "onreadystatechange" method to verify the status of the request.
  • Then the script initializes the request with xhr.open(method,url,async), it sets the encoding of the submitted data (in our case the default HTML form enctype) and then it sends the data to the server.
  • One other thing you should know is that xhr.readyState is 4 when a request has been completed, but that doesn't mean that no errors have occured - you still need to check status codes in your callback function.

If you have any other questions about AJAX, let me know using the comments area below. Thanks!

comments powered by Disqus