Reputation: 37
I have the following ajax call to submit a Yii2 form:
var form = $("#purchase-order-form");
$.ajax({
url: form.attr('action'),
data: form.serialize(),
type: 'post',
success: function(data) {
$('#modal').modal('hide');
callNotify(data);
}
});
This works fine, however I have additional data that I need to pass along with the form's data. It is a string with json encoding, that I created calling JSON.stringify
in an array created by me.
I tried to use .serializeArray()
instead of .serialize()
and push the additional content to the form, like this:
var form = $("#purchase-order-form");
var table-data = tableToJson('.products-table');
var data = form.serializeArray();
data.push({table: table});
$.ajax({
url: form.attr('action'),
data: data,
type: 'post',
success: function(data) {
$('#modal').modal('hide');
callNotify(data);
}
});
When I see the console, the content is at the end of the array, but in my Controller it is passed as undefined.
I think yii processes data that is not from the model before letting me load it.
How can I pass data along with the form while still being able to load the model using $model->load()
?
Upvotes: 1
Views: 1474
Reputation: 23738
You have to add the extra data with name
and value
indexes, where name
holds the name of the variable to be posted and value
is the value of the variable you want to append
{name: 'data', value: data}
But before i suggest the actual code you have a few things to look after, you cannot name a variable containing -
like you have declared var table-data = tableToJson('.products-table');
Hyphens can be mistaken as subtraction attempts. Hyphens are not allowed in JavaScript names.
Then you are assigning data.push({table: table});
whereas there is no variable with the name table
.
So your complete code should be like
var form = $("#purchase-order-form");
var tableData = tableToJson('.products-table');
var data = form.serializeArray();
data.push({name: 'table', value:tableData});
$.ajax({
url: form.attr('action'),
data: data,
type: 'post',
success: function(data) {
$('#modal').modal('hide');
callNotify(data);
}
});
Upvotes: 1