How to send HTTP post requests and HTTP get requests using jQuery

This was a proof of concept to try out jQuery's ajax features. Asynchronus Javascript And XML is a way for avoiding unnecessary refresh of the entire web page. When used properly, it can enhance user experience for your website, especially when you have lots of images on your page which does not change often across different pages.

This proof of concept was based on jQuery version 1.7.1.

A sample scenario

Let's create a scenario to demonstrate the use of jQuery AJAX facilities. Suppose we have two php scripts. One process variables sent by the client via HTTP post while the other process variables sent by the client via HTTP get.

Let's name the first script as postDataHandler.php; the second as getDataHandler.php.

The server script - postDataHandler.php:

Results from postDataHandler.php:
<br/>
<?php
$number = isset($_POST['number']) ? $_POST['number'] : '';
if (is_numeric($number)) {
    if ($number % 2 == 0) {
        echo 'The number is even.';
    }
    else {
        echo 'The number is odd.';
    } // end if
}
else {
    echo 'You did not enter a number. Please enter a number.';
} // end if
?>

In postDataHandler.php, we output a string that indicates the identity of the processing script. We then look for a post variable - number in the predefined variable, $_POST, that stores post data.

We then check whether a number is provided. If provided, we check whether the number is odd or even and prints the result.

If a number is not provided, we ask for a number.

The server script - getDataHandler.php:

Results from getDataHandler.php:
<br/>
<?php
$number = isset($_GET['number']) ? $_GET['number'] : '';
if (is_numeric($number)) {
    if ($number < 0) {
        echo 'The number is negative.';
    }
    else if ($number > 0){
        echo 'The number is positive.';
    }
    else {
        echo 'The number is neither positive nor negative. It is zero.';
    } // end if
}
else {
    echo 'You did not enter a number. Please enter a number.';
} // end if
?>

In getDataHandler.php, we output a string that indicates the identity of the processing script. We then look for a query string variable - number in the predefined variable, $_GET, that stores query string data.

We first check whether a number is provided. If a number is provided, we check whether it is negative, positive or is zero and outputs the result.

If a number is not provided, we ask for a number.

The HTML code for the sample scenario

<div id="contentLink">
    <a id="checkWhetherNumberIsOdd" href="#">
        Check if number is odd or even.
    </a>
    <br/>
    <a id="checkWhetherNumberIsNegative" href="#">
        Check if number is positive or negative.
    </a>
</div>
<label for="numberTextField">Number: </label>
<input id = "numberTextField" type="text"/>
<hr/>
<div id="contentBlock">
</div>

The HTML code renders four main elements on screen that will be involved in the demonstration:

  1. A link that will initiate a HTTP post.
  2. A link that will initiate a HTTP get.
  3. A text field for user input.
  4. A section that will display the result from the server scripts.

All four are given a unique id each to facilitate DOM selection by the jQuery counterpart.

The jQuery code to perform HTTP get and HTTP post

$(document).ready(
    
    function () {
    $('#checkWhetherNumberIsOdd').click(
        function(event) {
            event.preventDefault();
            $.post('postDataHandler.php'
                 , {number: $('#numberTextField').val()}
                 , dataReady);
        }
    );
    
    $('#checkWhetherNumberIsNegative').click(
        function(event) {
            event.preventDefault();
            $.get('getDataHandler.php'
                   , {number: $('#numberTextField').val()}
                   , dataReady); 
        } // end function(event)
    ); // end $(document).ready
    
    function dataReady(data) {
        $('#contentBlock').html(data);
    } // end function dataReady(data)
    
});

When the document is ready, a click handler is added to each of the two links.

Inside the click handler for checkWhetherNumberIsOdd

A call to event.preventDefault prevents clicks on the "Check whether number is odd or even" link from initiating a full refresh of the web page.

We then call $.post to send a HTTP post request to postDataHandler.php. There are three arguments supplied to the $.post function:

  1. The url to the server endpoint which will handle the HTTP post request, which in this case is postDataHandler.php.
  2. A javascript object which contains a number property with the user input from numberTextField as its value.
  3. The dataReady function which will look for contentBlock and set its content to the content of the HTTP response from the postDataHandler.php.

Inside the click handler for checkWhetherNumberIsNegative

The logic in the click handler for checkWhetherNumberIsNegative is similar to the logic checkWhetherNumberIsOdd.

We call event.preventDefault to prevent clicks on "Check if number is positive or negative." from initiating a full refresh of the web page.

However, we call $.get instead of $.post to send a HTTP get request to getDataHandler.php.

The three arguments supplied to the $.get function is similar to $.post:

  1. The url to the server endpoint which will handle the HTTP post request, which in this case is getDataHandler.php.
  2. A javascript object which contains a number property with the user input from numberTextField as its value.
  3. The dataReady function which will look for contentBlock and set its content to the content of the HTTP response from the getDataHandler.php.

Wait! How about cases when the server scripts are not contactable?

There may probably be situations when the scripts does not execute correctly, or in HTTP taxomony, does not send back a HTTP response with status of success 2xx. In such situations, nothing will be populated by the jQuery codes in contentBlock.

But what if we want to notify our users of such situations from our scripts? Yes we can do that. Since this proof of concept is based on jQuery 1.7.1, we can attach an event handler to output a notification to our users when failures occurred. The event handler can be attached to the $.post or $.get functions by chaining .error at the back:

$.post('postDataHandler.php'
     , {number: $('#numberTextField').val()}
     , dataReady).error(function () {
        alert('An error had occurred while checking if number is odd or even.');
     });

Related posts

About Clivant

Clivant a.k.a Chai Heng enjoys composing software and building systems to serve people. He owns techcoil.com and hopes that whatever he had written and built so far had benefited people. All views expressed belongs to him and are not representative of the company that he works/worked for.