Wednesday, 22 July 2020

Make Ajax requests from jQuery

jQuery  JavaScript  PHP  HTML 

Ajax is a set of web development techniques on the client side to exchange data with a server asynchronously. It allows updating parts of a web page dynamically without the need of reloading the whole page.

The jQuery JavaScript library allows developers to use Ajax easily. The jQuery ajax() method is used on the client side to make an Ajax request asynchronously. To use the jQuery library, we need reference it with the HTML <script> tag inside the <head> section.

<head>
    <!-- other codes ... -->
    <script src="https://code.jquery.com/jquery-3.5.1.min.js" 
    integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" 
    crossorigin="anonymous"></script>
    <!-- other codes ... -->
</head>

By including the jQuery library file from a CDN (Content Delivery Network) as shown above, we don't need to download and host the library file. The integrity and crossorigin attributes are used to verify the resource by using the Subresource Integrity (SRI) checking.

We can add a button on the web page for calling the backend PHP.

<button id="demo">Call PHP</button>

The following JavaScript code block is for the button click event. When the button is clicked, the jQuery ajax() method will perform an Ajax request to the backend PHP.


<script>
    $(document).ready(function() {
        $("#demo").click(function(){
            var student = {"name":"Tom", "sex":"M", "age":"11", "class":"6Y"};
            $.ajax({
                type: 'post',
                url: 'my-backend.php',
                data: JSON.stringify(student),
                success: function(data, textStatus, xhr) {
                    alert(data);
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert('Error Msg: ' + errorThrown);
                }
            });        
        });
    });
</script>

The JavaScript variable student defines an object that stores a student's personal data. In the ajax() method, we set the request type to POST. In url, we set the PHP file that will receive the request. The JavaScript function JSON.stringify() is used to convert the object student to a JSON string before it is sent to the server. The functions in success and error will be called respectively when the request succeeds or fails. Here, an alert box with the data returned from the server will display if the request succeeds. If it fails, an alert box will display the textual portion of the HTTP status errorThrown.

In the backend PHP file my-backend.php, we can do like this:

<?php
    $json = file_get_contents('php://input');
    $data = json_decode($json);
    echo $data->name;
?>

The function file_get_contents() in line 2 is used to get the data sent to the server. In line 3, the funcion json_decode() is called to convert the JSON encoded string $json into a PHP variable $data. Finally, the student's name $data->name is returned to the client side.



Search