How to Use the jQuery post() Method

  • google plus

In Brief...

jQuery's post() method is a convenience function that can be used for making a simple POST request. The following six steps show how to get started using this method.

Instructions

  1. Download the jQuery library from jquery.com or find a link to the latest version of jQuery by going to code.jquery.com.
  2. Create an HTML document that includes the jQuery library.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
    </head>
    <body>
    
    </body>
    </html>
            
  3. Inside a script element in your HTML document, write jQuery's ready() function, which will wait until the selected object (the HTML document in this case) is ready before executing the code passed into it.
    <script>
        $(document).ready(function() {
    
        });
    </script>
                
  4. Write the post() method inside the body of the function passed into the ready() method. The only required argument is the first one, which is the URL to make the request to.
    <script>
        $(document).ready(function() {
            $.post('users');
        });
    </script>
                
  5. After the URL, pass any of the following arguments to post():
    • data - The data to be sent to the server. This can either be an object, like {foo:'bar',baz:'bim' }, or a query string, such as foo=bar&baz=bim.
    • success - A callback function to run if the request succeeds. The function receives the response data (converted to a JavaScript object if the data type was JSON), as well as the text status of the request and the raw request object.
    • dataType - The type of data you expect back from the server.
  6. Write a success callback function, which will receive the result of the request.
    $.post('users','userID=8', function(user) {
        $('<h1/>').text('Welcome ' + user.firstName).appendTo('body');
    },'json');
            
    Result of Running the post() Demo Script

Related Training

Categories

Courses

Author: Chris Minnick

Chris is a prolific author and trainer, and the CEO of WatzThis?. His published books include Writing Computer Code, JavaScript for Kids, Coding with JavaScript For Dummies, Beginning HTML5 and CSS3 For Dummies, Webkit For Dummies, CIW eCommerce Certification Bible, and New Riders' XHTML.

Discuss