JQUERY BASIC
JQUERY EFFECTS
JQUERY MANIPULATION
JQUERY ADVANCED
JQUERY EXAMPLES
JQUERY REFERENCE
Advertisements

jQuery Ajax GET and POST Requests

In this tutorial you will learn how to send and receive data from a web server through Ajax via HTTP GET or POST methods using jQuery.

jQuery $.get() and $.post() Methods

The jQuery's $.get() and $.post() methods provide simple tools to send and retrieve data asynchronously from a web server. Both the methods are pretty much identical, apart from one major difference — the $.get() makes Ajax requests using the HTTP GET method, whereas the $.post() makes Ajax requests using the HTTP POST method.

The basic syntax of these methods can be given with:

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

The parameters in the above syntax have the following meaning:

  • The required URL parameter specifies the URL to which the request is sent.
  • The optional data parameter specifies a set of query string (i.e. key/value pairs) that is sent to the web server along with the request.
  • The optional success parameter is basically a callback function that is executed if the request succeeds. It is typically used to retrieve the returned data.

Note: The HTTP GET and POST methods are used to send request from a browser to a server. The main difference between these methods is the way in which the data is passed to the server. Check out the tutorial on GET and POST methods for the detailed explanation and comparison between these two methods.


Performing GET Request with AJAX using jQuery

The following example uses the jQuery $.get() method to make an Ajax request to the "date-time.php" file using HTTP GET method. It simply retrieves the date and time returned from the server and displays it in the browser without refreshing the page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery get() Demo</title>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        $.get("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>

Here's our "date-time.php" file that simply output the current date and time of the server.

Example

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

Tip: If you face any difficulty while running these examples locally on your PC, please check out the tutorial on jQuery Ajax load for the solution.

You can also send some data to the server with the request. In the following example the jQuery code makes an Ajax request to the "create-table.php" as well as sends some additional data to the server along with the request.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery get() Demo</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("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>

Here's the PHP script of our "create-table.php" file that simply output the multiplication table for the number entered by the user on button click.

Example

Download
<?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

POST requests are identical to GET requests in jQuery. So, generally which method you should use either $.get() or $.post() is basically depends on the requirements of your server-side code. If you have large amount of data to be transmitted (e.g. form data) you need to use POST, because GET has a stringent limit on the data transfer.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery post() Demo</title>
<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();
        
        /* 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("display-comment.php", formValues, function(data){
            // Display the returned data in browser
            $("#result").html(data);
        });
    });
});
</script>
</head>
<body>
    <form>
        <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>

Here's our "display-comment.php" file that simply output the data entered by the user.

Example

Download
<?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"; ?>

Now that you have learnt how to perform various Ajax operations such as loading data, submitting form, etc. asynchronously using jQuery. Before concluding this chapter check out one more classic example of Ajax that will show you how to populate the state or city dropdown based on the option selected in the country dropdown using jQuery.

Advertisements
Bootstrap UI Design Templates Property Marvels - A Leading Real Estate Portal for Premium Properties