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.

Example

<!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

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

Example

<!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

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

Leave a Reply

Your email address will not be published. Required fields are marked *