1

I am posting to a rails controller an array of json objects via a jQuery ajax request. Do I need to use JSON.stringify or should jQuery handle it for me?

  var vals = [{"name":"item name #1"},{"name":"item name #2"}];
  $.ajax({
    url: '/arc/api/v1/calculate_items',
    type: 'POST',
    data: {line_items: vals},
    dataType: 'json'
  }).done(function(r){

vs

  var vals = [{"name":"item name #1"},{"name":"item name #2"}];
  $.ajax({
    url: '/arc/api/v1/calculate_items',
    type: 'POST',
    data: {line_items: JSON.stringify(vals)},
    dataType: 'json'
  }).done(function(r){
2
  • Did you check both ways? which one worked for you? Commented May 31, 2017 at 3:58
  • using JSON.stringify seemed to work but would like to hear something more definitive. Commented May 31, 2017 at 4:01

1 Answer 1

1

Do I need to use JSON.stringify?

You need to use JSON.stringify to first serialize your object(or an array of objects) to JSON, and then specify the content-type so your server understands it's JSON.

jQuery handle it for me?

No, it is not.

There are two jQuery method which does it automaticly, getJSON, post

$.getJSON("/some/url", function(data) { 
   // the data is already a plain JSON object
})


var data = /* Your data in JSON format - see below */;
$.post("/some/url", data, function(returnedData) {
  // the returnedData is already a plain JSON object    
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.