user3189357
user3189357

Reputation: 153

how to send the form data to server in json format in ajax javascript

function ajax() {
  $('form').submit(function() {
    console.log($(this).serializeArray());
    $('#result').text(JSON.stringify($(this).serializeArray()));
    return false;
  });
}

This is the json data i'm getting:

[{"name":"firstName","value":"erere"},{"name":"lastName","value":"rere"},{"name":"emailAddress","value":"[email protected]"},{"name":"password","value":"dfdfd"},{"name":"phoneNumber","value":"989989898"}]

How can I send it to the server. What should I include in data in the ajax call?

Upvotes: 3

Views: 6501

Answers (2)

James
James

Reputation: 2201

Try this:

$('form').submit(function() {
    var form = $(this);
    var data = form.serialize();

    $.ajax({
        url: 'post url'
        method: 'POST',
        data: data,
        success: function(resp){
             //action on successful post
        },
        error: function() {
            //handle error
        }
    });
    return false;
});

Upvotes: 2

Pez Cuckow
Pez Cuckow

Reputation: 14422

A simple example:

$('form').submit(function() {

    $.post( "send.php", $(this).serializeArray())
      .done(function( reply ) {
        alert( "Complete, reply from server: " + reply );
      });

    return false;
});

See: http://api.jquery.com/jquery.post/ for information on handling callbacks.

Upvotes: 3

Related Questions