POST requests in jQuery

Unlike GET requests, POST request data is not transmitted in the request line, but in its body. A common example of such requests is submitting form data to the server.

The method is used to send POST requests post. Its declaration and usage is generally similar to the get method. It accepts the following parameters:

  • url: required parameter containing the address of the resource that the request will access
  • data: optional parameter containing a simple javascript object or string to be sent to the server along with the request
  • success(data, textStatus, jqXHR): optional parameter – a callback function that will be executed when the request is successful. It can take three parameters: data- the data received from the server, textStatus- the status of the request, and jqXHR- a special jQuery object that represents an extended version of the XMLHttpRequest object .
  • dataType: optional parameter containing the data type as a string, such as “xml” or “json”

As output, the post method returns a jqXHR.

Usage example:

$.post('ajax.php', {'login':'1111', 'password' : '2222'},
        function(data) {
        $('#news').html(data);
        });

In this case, we pass the password and login as data. On the server, we can get the data and send a response to the user:


<?php
    $login=$_POST['login'];
    $pass=$_POST['password'];
    if($login=="1111" && $pass=="2222"){
        echo "Authorization was successful";
    }
    else{
        echo "Invalid username or password";
    }
?>

Since the most common use of a post request is when submitting form data, we use a form on the client side:

<html>
    <head>
        <metacharset='utf-8'>
        <script src="jquery-1.10.1.min.js"></script>
    </head>
    <body>
         <form action="ajax.php" id="loginForm">
            <input type="text" id="login" placeholder="Login" /><br><br>
            <input type="text" id="password" placeholder="Password" /><br><br>
            <input type="submit" value="Sign in" />
        </form>
        <div id="result"></div>
        <script type="text/javascript">
        $("#loginForm").submit(function(event) {
            // Prevent normal form submission
            event.preventDefault();
            $.post('ajax.php', {'login':$('#login').val(), 'password' : $('#password').val()},
                    function(data) {
                            $('#result').html(data);
                    });
            });
        </script>
    </body>
</html>

So, the server part to which the form will access – the ajax.php file – remains the same with us. Only in this case, now for the parameter data in the post method, we take the data from the fields on this form.

Please note that we are blocking the normal form submission ( event.preventDefault();), otherwise we would have had a redirect.

Form Serialization

Since forms are often not limited to two fields, it is easier to use form serialization. Serialization is done through a method serializeand as a result creates a javascript object, where the properties correspond to the form fields. And the values ​​store these properties are the same as the corresponding form fields.

So let’s apply the form serialization:

<form action="ajax.php" id="loginForm">
    <input type="text" name="login" placeholder="Login" /><br><br>
    <input type="text" name="password" placeholder="Password" /><br><br>
    <input type="submit" value="Sign in" />
</form>
<div id="result"></div>
<script type="text/javascript">
$("#loginForm").submit(function(event) {
    // Prevent normal form submission
    event.preventDefault();
    $.post('ajax.php', $("#loginForm").serialize(),
            function(data) {
                    $('#result').html(data);
            });
    });
</script>

Unlike the previous example, we have two differences here. First, notice that the input fields have the attribute name. When specifying a parameter, data we serialize the form data through the serialize: method $(“#loginForm”).serialize(). In this method, parameters are passed to the request body. Moreover, the names of the parameters are the values ​​of the name attributes of the input fields. And the values ​​of the parameters are respectively the entered values ​​in the text fields.

And so with PHP we can extract these values: $login=$_POST[‘login’].