JavaScript POST request example

[adinserter block=”34″]

RELATED TUTORIAL: PHP, MySQL and AJAX CRUD Tutorial – Step by Step Guide!

This post will show you JavaScript POST request examples. This is useful if you want to submit a form using HTML and JavaScript.

A PHP file will receive the posted data and print the response.

I think this is one of the most useful code when you’re coding with jQuery, especially if you’re building a web app with modules that deals with so many forms or post request on one page.

Why use jQuery for AJAX requests?

I think it is to make things easier, have shorter more readable code. You can see some code examples of doing an AJAX request without jQuery here and here.

As you can see on those links, some tasks include creating a catch for different browser XMLHttpRequest, opening the URL, checking if the request is in a ready state, and setting the request header.

jQuery solves this by having a short, more readable syntax.

Let’s code!

Alright, now we’ll get straight to the code examples. We’re gonna have three examples below, continue to read!

jQuery post form data using .ajax() method

This is a great way to show someone that you are now an AJAX programmer. Because of this .ajax() piece of code in your HTML page, you may now face the world with confidence and with a beautiful smile on your face.

Just kidding. But seriously, this piece of code is useful.

<html>
    <head>
        <title>jQuery post form data using .ajax() method by codeofaninja.com</title>

    </head>
<body>

<h1>jQuery post form data using .ajax() method</h1>
<div>Fill out and submit the form below to get response.</div>

<!-- our form -->
<form id='userForm'>
    <div><input type='text' name='firstname' placeholder='Firstname' /></div>
    <div><input type='text' name='lastname' placeholder='Lastname' /></div>
    <div><input type='text' name='email' placeholder='Email' /></div>
    <div><input type='submit' value='Submit' /></div>
</form>

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){

        // show that something is loading
        $('#response').html("<b>Loading response...</b>");

        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.ajax({
            type: 'POST',
            url: 'post_receiver.php',
            data: $(this).serialize()
        })
        .done(function(data){

            // show the response
            $('#response').html(data);

        })
        .fail(function() {

            // just in case posting your form failed
            alert( "Posting failed." );

        });

        // to prevent refreshing the whole page page
        return false;

    });
});
</script>

</body>
</html>

jQuery post form data using .post() method

.post() method has a more descriptive syntax, it is a shorthand of .ajax() method above. See how it was commonly used with the code below:

<html>
    <head>
        <title>jQuery post form data using .post() method by codeofaninja.com</title>

    </head>
<body>

<h1>jQuery post form data using .post() method</h1>
<div>Fill out and submit the form below to get response.</div>

<!-- our form -->
<form id='userForm'>
    <div><input type='text' name='firstname' placeholder='Firstname' /></div>
    <div><input type='text' name='lastname' placeholder='Lastname' /></div>
    <div><input type='text' name='email' placeholder='Email' /></div>
    <div><input type='submit' value='Submit' /></div>
</form>

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){

        // show that something is loading
        $('#response').html("<b>Loading response...</b>");

        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.post('post_receiver.php', $(this).serialize(), function(data){

            // show the response
            $('#response').html(data);

        }).fail(function() {

            // just in case posting your form failed
            alert( "Posting failed." );

        });

        // to prevent refreshing the whole page page
        return false;

    });
});
</script>

</body>
</html>

jQuery post JSON data using .post() method

Sometimes you don’t want to post data from an HTML form. You can do it by creating a JSON string, and here’s how you’ll be able to post it.

<html>
    <head>
        <title>jQuery post JSON data using .post() method by codeofaninja.com</title>

    </head>
<body>

<h1>jQuery post JSON data using .post() method</h1>
<div>Click the button below to get response.</div>

<!-- our form -->
<input type='button' value='Post JSON' id='postJson' />

<!-- where the response will be displayed -->
<div id='response'></div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){

    $('#postJson').click(function(){

        // show that something is loading
        $('#response').html("<b>Loading response...</b>");

        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.post('post_receiver.php', { user_id: "143", username: "ninjazhai", website: "https://codeofaninja.com/" }, function(data){

            // show the response
            $('#response').html(data);

        }).fail(function() {

            // just in case posting your form failed
            alert( "Posting failed." );

        });

        // to prevent refreshing the whole page page
        return false;

    });
});
</script>

</body>
</html>

Posting a JSON string using the .ajax() method is also possible, you can just replace the serialize() part with your JSON string.

Posted Data

Where did the posted data go? To the file where you want the posted data to be processed! But in our example, we just print the posted data. post_receiver.php has the following code

<?php
echo "<pre>";
    print_r($_POST);
echo "</pre>";
?>

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id=”12253″ text=”Download Now” style=”button” color=”green”]

If you want to learn how to create, read, update and delete data with AJAX, go ahead and learn from our AJAX CRUD Tutorial Using jQuery, JSON and PHP – Step by Step Guide!.

Related Tutorials

[adinserter block=”1″]

Thank you for learning our post about jQuery AJAX Post Example with PHP and JSON!

RELATED TUTORIAL: PHP, MySQL and AJAX CRUD Tutorial – Step by Step Guide!


Comments

13 responses to “JavaScript POST request example”

  1. Lennon Santos Avatar
    Lennon Santos

    Sou do Brasil e agradeço pelo post me ajudou muito, Obrigado.

    1. You’re welcome @lennon_santos, I’m glad to help you! Greetings from the Philippines!

  2. thanks … helps me to understand thie basics !

    1. Glad to help you about the basics @iknowv!

  3. I tried to check POSTed data below but nothing is printed ???
    <?php
    echo "”;
    print_r($_POST);
    echo “”;
    ?>

    1. Would you show us your code on post_receiver.php must be:

      [pre][code]
      &lt;?php
      echo &quot;&lt;pre&gt;&quot;;
      print_r($_POST);
      echo &quot;&lt;/pre&gt;&quot;;
      ?&gt;
      [/code][/pre]

      Please look at your jQuery code carefully as well.

  4. ok, you are the man 🙂

    1. You’re the man too @JuN!

  5. Mohamed Hafez Avatar
    Mohamed Hafez

    Nice article, useful for me

    1. Thanks for the kind words, glad to help you @mohamed_hafez_abdallah!

  6. Hi, I try your code and it saved my day. But could you show me how to let page automatically go to head of page after form submited? Thanks

    1. Hi @r94ever , glad our code helped you! To answer your question, you can use JavaScript scrollTo() method for that. See more solutions here http://stackoverflow.com/questions/1144805/scroll-to-the-top-of-the-page-using-javascript-jquery

  7. Hi @disqus_bE1w4MzxGO, I think you can make use of a “hidden” input field. Put the data both in your table and in a hidden input field. See https://stackoverflow.com/questions/17296313/what-is-input-type-hidden-used-for-in-html

Leave a Reply

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