I am using jQuery plugin for my validation on one ajax calls.
Currently I have this:
$("#invoiceForm").validate({
rules: {
plateNumber: {
required: true,
},
plateIssueState: {
required: true,
}
},
submitHandler: function(form) {
var invoice= 1 + Math.floor(Math.random() * 999999999);
$.ajax({
type: "POST",
url: "invoice",
data: $(form).serialize(),
success: function() {
},
error: function() {
}
});
return false;
}
});
The submitHandler was able to serialize all the data from the HTML form, but this is not enough for me. I need to also send the variable invoice
to the back-end however invoice
variable is not in the form
. I have tried to do something like this but failed, it will not in the correct JSON data format:
data: JSON.stringify({invoiceData:invoice, formData:form}),
How can I change this?
Since your invoice value ist just a single variable, you could append it to the data
string:
$("#invoiceForm").validate({
rules: {
plateNumber: {
required: true,
},
plateIssueState: {
required: true,
}
},
submitHandler: function(form) {
var invoice= 1 + Math.floor(Math.random() * 999999999);
var formData = $(form).serializeArray().map(function(obj) {
var o = {};
o[obj.name] = obj.value;
return o;
});
var data = {
formData: formData,
invoiceData: invoice
};
$.ajax({
type: "POST",
url: "invoice",
data: JSON.stringify(data), // Send the concatenated values
success: function() {
},
error: function() {
}
});
return false;
}
});
If you want to send the invoice variable along with your form, you simply need to include an invoice input field. This can be a hidden field that gets populated just before your serialize your form data.
Assuming your have something like:
HTML:
<input type="hidden" name="invoice" id="InvoiceData" />
You would then just add that data directly:
javascript:
var invoice = 1 + Math.floor(Math.random() * 999999999);
$('#InvoiceData').val(invoice);
Try this:
...
data: $(form).serialize() + '&invoiceData=' + JSON.stringify(invoice),
dataType:'json',
...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.