I am trying to pass an array in an array via ajax. If I do not pass in the additional array, it works just fine.
For example:
var settings = [];
// add stuff to the array
$.ajax({
type: 'POST',
url: "api/update-settings",
data: {
userId: 1,
userSettings: settings
},
done: function(response) {
//do something with the response
},
fail: function() {
// do error stuff
}
});
Sending this will not work. The API (in PHP) gets the code and is able to tell me what userId is, but userSettings is not defined.
Notice: Undefined index: userSettings in /api/update-settings.php on line 9
However, if I set the settings variable as a different data type (such as an int or string), the index is no longer undefined.
Within the PHP, when I dump request to see what's in it, userSettings is not found:
var_dump($_REQUEST);
Output: array(1) { ["userId"]=> string(1) "1" }
I'm adding items to my array using settings['template'] = template;
Before I submit the ajax request, I can console log it and I get this:
[p: "setting1", s: 1587, emp: "setting2", ems: 3245, template: "", …]
which contains all data that I need.
I tried to stringify the data with JSON.stringify(settings) but then ajax passes an empty array:
array(2) { ["userId"]=> string(1) "1" ["userSettings"]=> string(2) "[]" }
I feel like this is something simple, but I can't figure it out. And yes, I've done my searches - I've found similar things, but none of the responses seem to help.
Thank you, in advance.
settings) array"? Because if you're not, I'm pretty sure it won't send anything for an emptyuserSettingsarray in the request's body.var settings = [ 'yay something!' ];instead