Reputation: 111030
I'm binding to the beforeSend's ajax form submission:
My function looks like:
submitStuff : function(e, xhr, settings) {
settings.data = {
invitation : {
emails : me.returnsArrayX(),
bucket2 : me.returnsArrayY(),
bucket3 : me.returnsArrayZ()
}
}
}
This was working when I was manually submitting to the server like so:
$.ajax({
type: 'POST',
url: '/myurl',
dataType: 'json',
data: {
invitation : {
emails : me.returnsArrayX(),
bucket2 : me.returnsArrayY(),
bucket3 : me.returnsArrayZ()
}
}
});
But since I'm using Rails UJS, I would like to use the built in form submitter (data-remote). why would settings.data not work in the above? Do I need to convert the object to an array or something else?
Thanks
Upvotes: 4
Views: 6830
Reputation: 140228
Set processData
to false
, then you can simply work with an object in the beforeSend
:
$.ajax("/", {
beforeSend: function(xhr, settings) {
settings.data.key2 = "value2";
settings.data.key3 = {
more: "values",
like: "this"
};
//Encode at end
settings.data = jQuery.param(settings.data, false);
},
data: {
key: "value"
},
processData: false,
type: "POST"
});
Upvotes: 3
Reputation: 2279
For serializing the data I would use jQuery.param(obj). So from pdpMathi's example it would look something like this.
submitStuff : function(e, xhr, settings) {
data = {
invitation : {
emails : me.returnsArrayX(),
bucket2 : me.returnsArrayY(),
bucket3 : me.returnsArrayZ()
}
}
settings.data += "&serialized=" + jQuery.param(data)
}
You can see what the above does with some simple example data here jsFiddle. This allows you to work with your data easily and only serialize it when done.
Upvotes: 1
Reputation: 775
Try this
submitStuff : function(e, xhr, settings) {
settings.data += "&serialized=data";
}
similar post: How do I append data to a jquery-ujs post request in Rails?
Upvotes: 1