[javascript] jQuery Ajax POST example with PHP

I am trying to send data from a form to a database. Here is the form I am using:

<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

The typical approach would be to submit the form, but this causes the browser to redirect. Using jQuery and Ajax, is it possible to capture all of the form's data and submit it to a PHP script (an example, form.php)?

This question is related to javascript jquery ajax post

The answer is


I am using this simple one line code for years without a problem (it requires jQuery):

<script src="http://malsup.github.com/jquery.form.js"></script> 
<script type="text/javascript">
    function ap(x,y) {$("#" + y).load(x);};
    function af(x,y) {$("#" + x ).ajaxSubmit({target: '#' + y});return false;};
</script>

Here ap() means an Ajax page and af() means an Ajax form. In a form, simply calling af() function will post the form to the URL and load the response on the desired HTML element.

<form id="form_id">
    ...
    <input type="button" onclick="af('form_id','load_response_id')"/>
</form>
<div id="load_response_id">this is where response will be loaded</div>

Handling Ajax errors and loader before submit and after submitting success shows an alert boot box with an example:

var formData = formData;

$.ajax({
    type: "POST",
    url: url,
    async: false,
    data: formData, // Only input
    processData: false,
    contentType: false,
    xhr: function ()
    {
        $("#load_consulting").show();
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = (evt.loaded / evt.total) * 100;
                $('#addLoad .progress-bar').css('width', percentComplete + '%');
            }
        }, false);

        // Download progress
        xhr.addEventListener("progress", function (evt) {
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
            }
        }, false);
        return xhr;
    },
    beforeSend: function (xhr) {
        qyuraLoader.startLoader();
    },
    success: function (response, textStatus, jqXHR) {
        qyuraLoader.stopLoader();
        try {
            $("#load_consulting").hide();

            var data = $.parseJSON(response);
            if (data.status == 0)
            {
                if (data.isAlive)
                {
                    $('#addLoad .progress-bar').css('width', '00%');
                    console.log(data.errors);
                    $.each(data.errors, function (index, value) {
                        if (typeof data.custom == 'undefined') {
                            $('#err_' + index).html(value);
                        }
                        else
                        {
                            $('#err_' + index).addClass('error');

                            if (index == 'TopError')
                            {
                                $('#er_' + index).html(value);
                            }
                            else {
                                $('#er_TopError').append('<p>' + value + '</p>');
                            }
                        }
                    });
                    if (data.errors.TopError) {
                        $('#er_TopError').show();
                        $('#er_TopError').html(data.errors.TopError);
                        setTimeout(function () {
                            $('#er_TopError').hide(5000);
                            $('#er_TopError').html('');
                        }, 5000);
                    }
                }
                else
                {
                    $('#headLogin').html(data.loginMod);
                }
            } else {
                //document.getElementById("setData").reset();
                $('#myModal').modal('hide');
                $('#successTop').show();
                $('#successTop').html(data.msg);
                if (data.msg != '' && data.msg != "undefined") {

                    bootbox.alert({closeButton: false, message: data.msg, callback: function () {
                            if (data.url) {
                                window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                            } else {
                                location.reload(true);
                            }
                        }});
                } else {
                    bootbox.alert({closeButton: false, message: "Success", callback: function () {
                        if (data.url) {
                            window.location.href = '<?php echo site_url() ?>' + '/' + data.url;
                        } else {
                            location.reload(true);
                        }
                    }});
                }

            }
        }
        catch (e) {
            if (e) {
                $('#er_TopError').show();
                $('#er_TopError').html(e);
                setTimeout(function () {
                    $('#er_TopError').hide(5000);
                    $('#er_TopError').html('');
                }, 5000);
            }
        }
    }
});

I would like to share a detailed way of how to post with PHP + Ajax along with errors thrown back on failure.

First of all, create two files, for example form.php and process.php.

We will first create a form which will be then submitted using the jQuery .ajax() method. The rest will be explained in the comments.


form.php

<form method="post" name="postForm">
    <ul>
        <li>
            <label>Name</label>
            <input type="text" name="name" id="name" placeholder="Bruce Wayne">
            <span class="throw_error"></span>
            <span id="success"></span>
       </li>
   </ul>
   <input type="submit" value="Send" />
</form>


Validate the form using jQuery client-side validation and pass the data to process.php.

$(document).ready(function() {
    $('form').submit(function(event) { //Trigger on form submit
        $('#name + .throw_error').empty(); //Clear the messages first
        $('#success').empty();

        //Validate fields if required using jQuery

        var postForm = { //Fetch form data
            'name'     : $('input[name=name]').val() //Store name fields value
        };

        $.ajax({ //Process the form using $.ajax()
            type      : 'POST', //Method type
            url       : 'process.php', //Your form processing file URL
            data      : postForm, //Forms name
            dataType  : 'json',
            success   : function(data) {
                            if (!data.success) { //If fails
                                if (data.errors.name) { //Returned if any error from process.php
                                    $('.throw_error').fadeIn(1000).html(data.errors.name); //Throw relevant error
                                }
                            }
                            else {
                                    $('#success').fadeIn(1000).append('<p>' + data.posted + '</p>'); //If successful, than throw a success message
                                }
                            }
        });
        event.preventDefault(); //Prevent the default submit
    });
});

Now we will take a look at process.php

$errors = array(); //To store errors
$form_data = array(); //Pass back the data to `form.php`

/* Validate the form on the server side */
if (empty($_POST['name'])) { //Name cannot be empty
    $errors['name'] = 'Name cannot be blank';
}

if (!empty($errors)) { //If errors in validation
    $form_data['success'] = false;
    $form_data['errors']  = $errors;
}
else { //If not, process the form, and return true on success
    $form_data['success'] = true;
    $form_data['posted'] = 'Data Was Posted Successfully';
}

//Return the data back to form.php
echo json_encode($form_data);

The project files can be downloaded from http://projects.decodingweb.com/simple_ajax_form.zip.


In your php file enter:

$content_raw = file_get_contents("php://input"); // THIS IS WHAT YOU NEED
$decoded_data = json_decode($content_raw, true); // THIS IS WHAT YOU NEED
$bar = $decoded_data['bar']; // THIS IS WHAT YOU NEED
$time = $decoded_data['time'];
$hash = $decoded_data['hash'];
echo "You have sent a POST request containing the bar variable with the value $bar";

and in your js file send an ajax with the data object

var data = { 
    bar : 'bar value',
    time: calculatedTimeStamp,
    hash: calculatedHash,
    uid: userID,
    sid: sessionID,
    iid: itemID
};

$.ajax({
    method: 'POST',
    crossDomain: true,
    dataType: 'json',
    crossOrigin: true,
    async: true,
    contentType: 'application/json',
    data: data,
    headers: {
        'Access-Control-Allow-Methods': '*',
        "Access-Control-Allow-Credentials": true,
        "Access-Control-Allow-Headers" : "Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization",
        "Access-Control-Allow-Origin": "*",
        "Control-Allow-Origin": "*",
        "cache-control": "no-cache",
        'Content-Type': 'application/json'
    },
    url: 'https://yoururl.com/somephpfile.php',
    success: function(response){
        console.log("Respond was: ", response);
    },
    error: function (request, status, error) {
        console.log("There was an error: ", request.responseText);
    }
  })

or keep it as is with the form-submit. You need this only, if you want to send a modified request with calculated additional content and not only some form-data, which is entered by the client. For example a hash, a timestamp, a userid, a sessionid and the like.


You can use serialize. Below is an example.

$("#submit_btn").click(function(){
    $('.error_status').html();
        if($("form#frm_message_board").valid())
        {
            $.ajax({
                type: "POST",
                url: "<?php echo site_url('message_board/add');?>",
                data: $('#frm_message_board').serialize(),
                success: function(msg) {
                    var msg = $.parseJSON(msg);
                    if(msg.success=='yes')
                    {
                        return true;
                    }
                    else
                    {
                        alert('Server error');
                        return false;
                    }
                }
            });
        }
        return false;
    });

To make an Ajax request using jQuery you can do this by the following code.

HTML:

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>

JavaScript:

Method 1

 /* Get from elements values */
 var values = $(this).serialize();

 $.ajax({
        url: "test.php",
        type: "post",
        data: values ,
        success: function (response) {

           // You will get response from your PHP page (what you echo or print)
        },
        error: function(jqXHR, textStatus, errorThrown) {
           console.log(textStatus, errorThrown);
        }
    });

Method 2

/* Attach a submit handler to the form */
$("#foo").submit(function(event) {
    var ajaxRequest;

    /* Stop form from submitting normally */
    event.preventDefault();

    /* Clear result div*/
    $("#result").html('');

    /* Get from elements values */
    var values = $(this).serialize();

    /* Send the data using post and put the results in a div. */
    /* I am not aborting the previous request, because it's an
       asynchronous request, meaning once it's sent it's out
       there. But in case you want to abort it you can do it
       by abort(). jQuery Ajax methods return an XMLHttpRequest
       object, so you can just use abort(). */
       ajaxRequest= $.ajax({
            url: "test.php",
            type: "post",
            data: values
        });

    /*  Request can be aborted by ajaxRequest.abort() */

    ajaxRequest.done(function (response, textStatus, jqXHR){

         // Show successfully for submit message
         $("#result").html('Submitted successfully');
    });

    /* On failure of request this function will be called  */
    ajaxRequest.fail(function (){

        // Show error
        $("#result").html('There is error while submit');
    });

The .success(), .error(), and .complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use .done(), .fail(), and .always() instead.

MDN: abort() . If the request has been sent already, this method will abort the request.

So we have successfully send an Ajax request, and now it's time to grab data to server.

PHP

As we make a POST request in an Ajax call (type: "post"), we can now grab data using either $_REQUEST or $_POST:

  $bar = $_POST['bar']

You can also see what you get in the POST request by simply either. BTW, make sure that $_POST is set. Otherwise you will get an error.

var_dump($_POST);
// Or
print_r($_POST);

And you are inserting a value into the database. Make sure you are sensitizing or escaping All requests (whether you made a GET or POST) properly before making the query. The best would be using prepared statements.

And if you want to return any data back to the page, you can do it by just echoing that data like below.

// 1. Without JSON
   echo "Hello, this is one"

// 2. By JSON. Then here is where I want to send a value back to the success of the Ajax below
echo json_encode(array('returned_val' => 'yoho'));

And then you can get it like:

 ajaxRequest.done(function (response){
    alert(response);
 });

There are a couple of shorthand methods. You can use the below code. It does the same work.

var ajaxRequest= $.post("test.php", values, function(data) {
  alert(data);
})
  .fail(function() {
    alert("error");
  })
  .always(function() {
    alert("finished");
});

Please check this. It is the complete Ajax request code.

$('#foo').submit(function(event) {
    // Get the form data
    // There are many ways to get this data using jQuery (you
    // can use the class or id also)
    var formData = $('#foo').serialize();
    var url = 'URL of the request';

    // Process the form.
    $.ajax({
        type        : 'POST',   // Define the type of HTTP verb we want to use
        url         : 'url/',   // The URL where we want to POST
        data        : formData, // Our data object
        dataType    : 'json',   // What type of data do we expect back.
        beforeSend : function() {

            // This will run before sending an Ajax request.
            // Do whatever activity you want, like show loaded.
        },
        success:function(response){
            var obj = eval(response);
            if(obj)
            {
                if(obj.error==0){
                    alert('success');
                }
                else{
                    alert('error');
                }
            }
        },
        complete : function() {
            // This will run after sending an Ajax complete
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert('error occured');
            // If any error occurs in request
        }
    });

    // Stop the form from submitting the normal way
    // and refreshing the page
    event.preventDefault();
});

I have one other idea.

Which the URL that of PHP files which provided the download file. Then you have to fire the same URL via ajax and I checked this second request only gives the response after your first request complete the download file. So you can get the event of it.

It is working via ajax with the same second request.}


<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
    <button id="desc" name="desc" value="desc" style="display:none;">desc</button>
    <button id="asc" name="asc"  value="asc">asc</button>
    <input type='hidden' id='check' value=''/>
</form>

<div id="demoajax"></div>

<script>
    numbers = '';
    $('#form_content button').click(function(){
        $('#form_content button').toggle();
        numbers = this.id;
        function_two(numbers);
    });

    function function_two(numbers){
        if (numbers === '')
        {
            $('#check').val("asc");
        }
        else
        {
            $('#check').val(numbers);
        }
        //alert(sort_var);

        $.ajax({
            url: 'test.php',
            type: 'POST',
            data: $('#form_content').serialize(),
            success: function(data){
                $('#demoajax').show();
                $('#demoajax').html(data);
                }
        });

        return false;
    }
    $(document).ready(function_two());
</script>

Pure JS

In pure JS it will be much simpler

foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}

_x000D_
_x000D_
foo.onsubmit = e=> {
  e.preventDefault();
  fetch(foo.action,{method:'post', body: new FormData(foo)});
}
_x000D_
<form name="foo" action="form.php" method="POST" id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" />
</form>
_x000D_
_x000D_
_x000D_


HTML:

    <form name="foo" action="form.php" method="POST" id="foo">
        <label for="bar">A bar</label>
        <input id="bar" class="inputs" name="bar" type="text" value="" />
        <input type="submit" value="Send" onclick="submitform(); return false;" />
    </form>

JavaScript:

   function submitform()
   {
       var inputs = document.getElementsByClassName("inputs");
       var formdata = new FormData();
       for(var i=0; i<inputs.length; i++)
       {
           formdata.append(inputs[i].name, inputs[i].value);
       }
       var xmlhttp;
       if(window.XMLHttpRequest)
       {
           xmlhttp = new XMLHttpRequest;
       }
       else
       {
           xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
       }
       xmlhttp.onreadystatechange = function()
       {
          if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
          {

          }
       }
       xmlhttp.open("POST", "insert.php");
       xmlhttp.send(formdata);
   }

If you want to send data using jQuery Ajax then there is no need of form tag and submit button

Example:

<script>
    $(document).ready(function () {
        $("#btnSend").click(function () {
            $.ajax({
                url: 'process.php',
                type: 'POST',
                data: {bar: $("#bar").val()},
                success: function (result) {
                    alert('success');
                }
            });
        });
    });
</script>

<label for="bar">A bar</label>
<input id="bar" name="bar" type="text" value="" />
<input id="btnSend" type="button" value="Send" />

This is a very good article that contains everything that you need to know about jQuery form submission.

Article summary:

Simple HTML Form Submit

HTML:

<form action="path/to/server/script" method="post" id="my_form">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Email</label>
    <input type="email" name="email" />
    <label>Website</label>
    <input type="url" name="website" />
    <input type="submit" name="submit" value="Submit Form" />
    <div id="server-results"><!-- For server results --></div>
</form>

JavaScript:

$("#my_form").submit(function(event){
    event.preventDefault(); // Prevent default action
    var post_url = $(this).attr("action"); // Get the form action URL
    var request_method = $(this).attr("method"); // Get form GET/POST method
    var form_data = $(this).serialize(); // Encode form elements for submission

    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});

HTML Multipart/form-data Form Submit

To upload files to the server, we can use FormData interface available to XMLHttpRequest2, which constructs a FormData object and can be sent to server easily using the jQuery Ajax.

HTML:

<form action="path/to/server/script" method="post" id="my_form">
    <label>Name</label>
    <input type="text" name="name" />
    <label>Email</label>
    <input type="email" name="email" />
    <label>Website</label>
    <input type="url" name="website" />
    <input type="file" name="my_file[]" /> <!-- File Field Added -->
    <input type="submit" name="submit" value="Submit Form" />
    <div id="server-results"><!-- For server results --></div>
</form>

JavaScript:

$("#my_form").submit(function(event){
    event.preventDefault(); // Prevent default action
    var post_url = $(this).attr("action"); // Get form action URL
    var request_method = $(this).attr("method"); // Get form GET/POST method
    var form_data = new FormData(this); // Creates new FormData object
    $.ajax({
        url : post_url,
        type: request_method,
        data : form_data,
        contentType: false,
        cache: false,
        processData: false
    }).done(function(response){ //
        $("#server-results").html(response);
    });
});

I hope this helps.


I use the way shown below. It submits everything like files.

$(document).on("submit", "form", function(event)
{
    event.preventDefault();

    var url  = $(this).attr("action");
    $.ajax({
        url: url,
        type: 'POST',
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {
            console.log("error");
        }
    });
});

Since the introduction of the Fetch API there really is no reason any more to do this with jQuery Ajax or XMLHttpRequests. To POST form data to a PHP-script in vanilla JavaScript you can do the following:

_x000D_
_x000D_
function postData() {_x000D_
    const form = document.getElementById('form');_x000D_
    const data = new FormData();_x000D_
    data.append('name', form.name.value);_x000D_
_x000D_
    fetch('../php/contact.php', {method: 'POST', body: data}).then(response => {_x000D_
        if (!response.ok){_x000D_
            throw new Error('Network response was not ok.');_x000D_
        }_x000D_
    }).catch(err => console.log(err));_x000D_
}
_x000D_
<form id="form" action="javascript:postData()">_x000D_
    <input id="name" name="name" placeholder="Name" type="text" required>_x000D_
    <input type="submit" value="Submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Here is a very basic example of a PHP-script that takes the data and sends an email:

<?php
    header('Content-type: text/html; charset=utf-8');

    if (isset($_POST['name'])) {
        $name = $_POST['name'];
    }

    $to = "[email protected]";
    $subject = "New name submitted";
    $body = "You received the following name: $name";

    mail($to, $subject, $body);

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to post

How to post query parameters with Axios? How can I add raw data body to an axios request? HTTP POST with Json on Body - Flutter/Dart How do I POST XML data to a webservice with Postman? How to set header and options in axios? Redirecting to a page after submitting form in HTML How to post raw body data with curl? How do I make a https post in Node Js without any third party module? How to convert an object to JSON correctly in Angular 2 with TypeScript Postman: How to make multiple requests at the same time