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.

Example

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

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


Leave a Reply

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