Submitting a form using XHR and jQuery

jQuery’s serialize() method offers a convenient way to turn an HTML form’s data into a text string in standard URL-encoded notation. Consider the following code


$('form').on('submit', function(e) {
    $.ajax({
        type: 'POST',
        url:  '/my/endpoint',
        data: $('form').serialize(),
        dataType: 'json',
        success: function(data){
            // Success Code
        },
        error: function(jqXHR, strStatus, strErrorThrown){
            // Error Code
        }
    });
});

This serializes the form data in $(‘form’) and sends it to /my/endpoint.

Note that the JSON will contain keys for all the input elements regardless of whether or not they contain data except for inputs of type “radio” or “checkbox”. They must be clicked, then their key and value will be present in the JSON.

The following PHP code will take the serialized form data and convert it into a standard PHP array.


$qry = file_get_contents("php://input");
parse_str($qry, $qry_array);

$qry_array will contain the form’s data.

Leave a Reply

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