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 (in example, form.php)?

3 upvote
  flag
See related meta discussion for reasoning behind undeletion. – TRiG
upvote
  flag
best answer here: //allinonescript.com/questions/19029703/… checked and tested working – rohitcopyright

11 Answers 11

up vote 803 down vote accepted

Basic usage of .ajax would look something like this:

HTML:

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

    <input type="submit" value="Send" />
</form>

JQuery:

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

    // Prevent default posting of form - put here to work in case of errors
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

});

Note: Since jQuery 1.8, .success(), .error() and .complete() are deprecated in favor of .done(), .fail() and .always().

Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready() handler (or use the $() shorthand).

Tip: You can chain the callback handlers like this: $.ajax().done().fail().always();

PHP (that is, form.php):

// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;

Note: Always sanitize posted data, to prevent injections and other malicious code.

You could also use the shorthand .post in place of .ajax in the above JavaScript code:

$.post('/form.php', serializedData, function(response) {
    // Log the response to the console
    console.log("Response: "+response);
});

Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.

upvote
  flag
I can do something with that ;) But how should the form / php code look like? – Thew
81 upvote
  flag
+1 for the extra jQuery API deprecation details, sanitization tips and PHP server side snippet. – Jeach
3 upvote
  flag
Edited your answer to fix a bug: request was declared as a local var making if (request) request.abort(); never work. – lolmaus - Andrey Mikhaylov
upvote
  flag
Shouldn't serializedData be $inputs.serialize(), or is there a reason you serialize and submit the whole form? – Taj Morton
upvote
  flag
@TajMorton Doesn't really matter. In this case they would do the exact same thing. The reason I serialize the form is for ease of use and readability. As stated in the docs: It is typically easier, however, to select the <form> itself for serialization – Marcus Ekwall
14 upvote
  flag
A VERY IMPORTANT note, because I spent/wasted/invested a lot of time trying to use this example. You need to either bind the event inside a $(document).ready block OR have the FORM loaded before the bind is executed. Otherwise, you spend a lot of time trying to figure out WHY in hell the binding isn't called. – Philibert Perusse
1 upvote
  flag
@PhilibertPerusse Like with any event binding you obviously need the element to exist in the DOM before trying to bind to it, or if you use a delegated bind. – Marcus Ekwall
7 upvote
  flag
Yes, I understand that now. But I found many examples that always put a $(document).ready block around so that the example is self-contained. I wrote the comment for a future user who may, like me, stumble on this and end-up reading the comment thread and this beginner 'tip' – Philibert Perusse
upvote
  flag
Best answer to this question I could find and have been searching stack for hours now. Thanks so much! – Andrew Allen West
2 upvote
  flag
If you are applying this to your own code, note that the 'name' attributes are critical to the inputs otherwise serialize() will skip them. – Ben Flynn
upvote
  flag
Could someone kindly explain the purpose of the request.abort(); part. Running the code as is keeps throwing an abort error. When I disable that part my AJAX post works without error. Just want to understand fully what that part is doing and why I should or shouldn't need it? Thanks in advance anyone? The comment says Abort any pending request so i'm thinking possibly to prevent multiple posts at once? – JasonDavis
upvote
  flag
how to link the html with your js? – user4393693
upvote
  flag
Is it necessary to serialize the data? Can I just get the form values and send them instead of serailizing? – Robert Rocha

To make ajax request using jQuery you can do this by 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 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 cab be abort 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 ajax request now its time to grab data to server.

PHP

As we make a POST request in 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 POST request by simply either, Btw make sure that $_POST is set other wise you will get error.

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

And you are inserting value to database make sure you are sensitizing or escaping All request ( weather you made GET or POST) properly before making query, Best would be using prepared statements.

and if you want to return any data back to 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 than you can get it like

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

There are Couple of Shorthand Methods you can use below code it do the same work.

var ajaxRequest= $.post( "test.php",values, function(data) {
  alert( data );
})
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
});
1 upvote
  flag
Pointer : what is bar in $id = $_POST['bar']; and how it works ??? – Clarence
upvote
  flag
@Clarence bar is input type text name and since i am suing post method so $_POST['bar'] is used to get value of it – NullPoiиteя
3 upvote
  flag
For anyone wanting to use json - while using JSON the call should contain the parameter dataType: 'json' – K. Kilian Lindberg
3 upvote
  flag
@CarlLindberg - What if you want jQuery to guess based on the MIME type of the response (which is what it should do when you don't set the dataType), so that you can potentially accept JSON or some other format? – nnnnnn
upvote
  flag
@nnnnnn you are right - that's way better - indeed is default: Intelligent Guess – K. Kilian Lindberg
upvote
  flag
To access the JSON response object (data.returned_val), don't forget to include dataType: "json" in your original ajax call – chrishasbrouck
upvote
  flag
@NullPoiиteя can you tell me the steps of method1 if i want to send the form data to google spreadsheet ? – user1788736
upvote
  flag
Finding form elements and and later serialize it and afterword post it by ajax is a life saver. – kta

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;
    });
upvote
  flag
$.parseJSON() is a total lifesaver, thanks. I was having trouble interpreting my output based on the other answers. – foochow

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>
       </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.

<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>
upvote
  flag
what id difference between yours and other answer ? – NullPoiиteя
7 upvote
  flag
it is posted by me others are by others,. – john

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);
   }
2 upvote
  flag
I dont want to be mean but I don's see any jQuery here ... – Tom
3 upvote
  flag
I believe that was deliberate. – David

I use this way.It submit 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");

        }
    });        

});

I am using this simple one line code for years without problem. (It requires jquery)

<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 ajax page and af() means ajax form. In a form just simply calling af() function will post form to the url and load response on desired html element.

<form>
...
<input type="button" onclick="af('http://example.com','load_response')"/>
</form>
<div id="load_response">this is where response will be loaded</div>
    handling ajax error and loader before submit and after submit success show alert bootbox with 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);
                }
            }
        }
    });

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" />

Hi please check this 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 what ever 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();
});

Not the answer you're looking for? Browse other questions tagged or ask your own question.