1

I am having trouble sending a data object for a put request in jQuery’s ajax method. I want my data to be formatted like the following example:

var data_obj = {user_id: 1, music_albums: [{title: "X", artist: "A"}, {title: "Y", artist: "B"}]};

My ajax request has the usual syntax:

$.ajax({
  url: "/someurl",
  type: "put",
  data: data_obj,
  success: function(json) { /* etc. */ }
});

I want the array of objects to be accessible on the server side to process in my API. I am using expressJS for the backend. Right now when I send over the data object, the array of objects is not preserved.

Based on previous answers to similar questions, I have also tried to call JSON.stringify() on the array property, so for example:

var data_obj = {user_id: 1, music_albums: JSON.stringify([{title: "X", artist: "A"}, {title: "Y", artist: “B”}])};

But that did not work either.

How should I format this data properly to access the music_albums property as an array on the server side?

Andrew Myers
  • 2,754
  • 5
  • 32
  • 40
PR Doe
  • 11
  • 2
  • What becomes of the array when it goes to the backend? Does it get turned into some string representation like `"[object Array]"`? – Andrew Myers Mar 03 '17 at 23:04
  • Try JSON.stringify(data_obj). And what do you get on the server? undefined? – disstruct Mar 03 '17 at 23:05
  • @AndrewMyers The array on the backend is split up in a weird way with separate properties for each element's individual object property. So the object on the backend became `{user_id: 1, 'music_albums[0][title]': 'X', 'music_albums[0][artist]': 'A'...` and so on. Not sure why this happens. – PR Doe Mar 04 '17 at 23:49
  • @disstruct Using JSON.stringify(data_obj) works, but I had to set it as the value of a property and wrap that in another object, and then parse it on the backend. My data object ended up being ` { user: JSON.stringify(data_obj) } ` , then on the server side I did `JSON.parse(req.body.user).music_albums` to access the array. Wish there was a more straightforward way to do it, but at least it works now! – PR Doe Mar 04 '17 at 23:58
  • Hmm... that's strange behavior. With $.ajax you should be able to pass objects to a request body without any use of JSON.stringify or JSON.parse. From your previous comment to @AndrewMyers I guess that something wrong with body-parser settings – disstruct Mar 05 '17 at 03:16
  • 1
    I'm a little curious about the backend code now. Could you provide a snippet showing how you're doing the Express stuff? (Don't need to go overboard on including _everything_, just what's necessary.) It just seems like `music_albums[0][title]` and `music_albums[0][artist]` should get parsed by Express differently. – Andrew Myers Mar 07 '17 at 00:46
  • 1
    @AndrewMyers the request is simply missing `contentType: 'application/json'` – Phil Mar 07 '17 at 02:52

0 Answers0