Make a JSON object and send via ajax POST using jQuery

Make a JSON object and send via ajax POST using jQuery

Use jQuery to send a JSON object via POST. Everything EXCEPT the ajax call is done with simple javascript and jQuery is not needed. This is nice since JSON.stringify() will take care of special characters and other special cases you would have to check for manually. A little protection from posting plain input fields.

// declare the object
var data = {};

// throw some data into the object
data.address = '123 Main Street';
data.city = 'Orlando';
data.state = 'FL';

// convert the object into a json string
var data_json = JSON.stringify(data);

// simple ajax call to post your json data
$.ajax({
  type: 'post',
  url: 'where-to/post-data',
  data: 'data=' + data,
  success: function(result) {
    // check result object for what you returned
  },
  error: function(error) {
    // check error object or return error
  }
});

If you’re using PHP, you could retrieve the data using something like this:

$data = json_decode($_POST['data']);
// you $data object would look like
// $data->address = '123 Main Street';

Comments are closed.