jQuery Get/Post

In the jQuery's $.get() and $.post() methods, simple tools to send and retrieve data asynchronously from a web server are provided. Both methods are kind of identical, but possess one major difference which is that the $.get() uses the HTTP GET method to make Ajax requests, while the $.post() uses the HTTP POST method to make Ajax requests.

The basic syntax of these methods can be given with:

$.get(URL, data, success);   —Or—   $.post(URL, data, success);

Below is the meaning of the parameters in the above syntax:

  • The required URL parameter specifies the exact URL to which the request is sent.
  • The optional data parameter specifies a set of query strings such as the key/value pairs that are sent to the web server alongside the request.
  • The optional success parameter is mainly a callback function that is executed if the request succeeds. This is basically used to retrieve the returned data.

 

Performing GET Request with AJAX using jQuery

The following instance uses the jQuery $.get() method to make an Ajax request to the ‘date-time.php’ file using the HTTP GET method. It typically retrieves the date and time returned from the server and displays it in the browser without the page being refreshed.

In the example below, there is the ‘date-time.php’ file that typically outputs the current date and time of the server.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of Making GET Request using Ajax in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("/examples/php/date-time.php", function(data){
            // Display the returned data in browser
            $("#result").html(data);
        });
    });
});
</script>
</head>
<body>
    <div id="result">
        <h2>Content of the result DIV box will be replaced by the server date and time</h2>
    </div>
    <button type="button">Load Date and Time</button>
</body>
</html>

date-time.php

<?php
// Return current date and time from the server
echo date("F d, Y h:i:s A");
?>

 

Some data can be sent to the server with the request. The jQuery code makes an Ajax request to the "create-table.php" and sends some additional data to the server alongside the request in the example below.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of Sending Data with Ajax GET Request in jQuery</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        // Get value from input element on the page
        var numValue = $("#num").val();
        
        // Send the input data to the server using get
        $.get("/examples/php/create-table.php", {number: numValue} , function(data){
            // Display the returned data in browser
            $("#result").html(data);
        });
    });
});
</script>
</head>
<body>
    <label>Enter a Number: <input type="text" id="num"></label>
    <button type="button">Show Multiplication Table</button>
    <div id="result"></div>
</body>
</html>

 

In the example below, we have the PHP script of "create-table.php" file that mainly outputs the multiplication table for the number entered by the user on button click.

<?php
$number = htmlspecialchars($_GET["number"]);
if(is_numeric($number) && $number > 0){
    echo "<table>";
    for($i=0; $i<11; $i++){
        echo "<tr>";
            echo "<td>$number x $i</td>";
            echo "<td>=</td>";
            echo "<td>" . $number * $i . "</td>";
        echo "</tr>";
    }
    echo "</table>";
}
?>

 

Performing POST Request with AJAX using jQuery

In jQuery, POST requests are identical to GET requests so the method to use either $.get() or $.post() generally depends on the requirements of the server-side code. POST needs to be used if there is a large amount of data to be transmitted such as form data because GET has a stringent limit on the data transfer.

In the example below, there is the "display-comment.php" file that typically outputs the data entered by the user.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example of Making POST Request using Ajax in jQuery</title>
<style>
    label{
        display: block;
        margin-bottom: 10px;
    }
</style>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("form").submit(function(event){
        // Stop form from submitting normally
        event.preventDefault();
        
        // Get action URL
		var actionFile = $(this).attr("action");

        /* Serialize the submitted form control values to be sent to the web server with the request */
        var formValues = $(this).serialize();
        
        // Send the form data using post
        $.post(actionFile, formValues, function(data){
            // Display the returned data in browser
            $("#result").html(data);
        });
    });
});
</script>
</head>
<body>
    <form action="/examples/php/display-comment.php">
        <label>Name: <input type="text" name="name"></label>
        <label>Comment: <textarea cols="50" name="comment"></textarea></label>
        <input type="submit" value="Send">
    </form>
    <div id="result"></div>
</body>
</html>

 

display-comment.php

<?php
$name = htmlspecialchars($_POST["name"]);
$comment = htmlspecialchars($_POST["comment"]);
echo "Hi, $name. Your comment has been received successfully." . "";
echo "Here's the comment what you've entered: $comment";
?>

 

This tutorial has shown how to perform various Ajax operations such as loading data, and submitting forms asynchronously using jQuery. But before concluding this chapter check one more classic example of Ajax that shows how to populate the state or city dropdown on the basis of the option selected in the country dropdown using jQuery.