currently I have the following:
$.ajax({
type: \'POST\',
url: this.action,
data: $(this).serialize(),
});
This works fine, howe
While matt b's answer will work, you can also use .serializeArray()
to get an array from the form data, modify it, and use jQuery.param()
to convert it to a url-encoded form. This way, jQuery handles the serialisation of your extra data for you.
var data = $(this).serializeArray(); // convert form to array
data.push({name: "NonFormValue", value: NonFormValue});
$.ajax({
type: 'POST',
url: this.action,
data: $.param(data),
});
Don't forget you can always do:
<input type="hidden" name="NonFormName" value="NonFormValue" />
in your actual form, which may be better for your code depending on the case.
this better:
data: [$(this).serialize(),$.param({NonFormValue: NonFormValue})].join('&')
firstly shouldn't
data: $(this).serialize() + '&=NonFormValue' + NonFormValue,
be
data: $(this).serialize() + '&NonFormValue=' + NonFormValue,
and secondly you can use
url: this.action + '?NonFormValue=' + NonFormValue,
or if the action already contains any parameters
url: this.action + '&NonFormValue=' + NonFormValue,
You can write an extra function to process form data and you should add your nonform data as the data valu in the form.seethe example :
<form method="POST" id="add-form">
<div class="form-group required ">
<label for="key">Enter key</label>
<input type="text" name="key" id="key" data-nonformdata="hai"/>
</div>
<div class="form-group required ">
<label for="name">Ente Name</label>
<input type="text" name="name" id="name" data-nonformdata="hello"/>
</div>
<input type="submit" id="add-formdata-btn" value="submit">
</form>
Then add this jquery for form processing
<script>
$(document).onready(function(){
$('#add-form').submit(function(event){
event.preventDefault();
var formData = $("form").serializeArray();
formData = processFormData(formData);
// write further code here---->
});
});
processFormData(formData)
{
var data = formData;
data.forEach(function(object){
$('#add-form input').each(function(){
if(this.name == object.name){
var nonformData = $(this).data("nonformdata");
formData.push({name:this.name,value:nonformData});
}
});
});
return formData;
}
Instead of
data: $(this).serialize() + '&=NonFormValue' + NonFormValue,
you probably want
data: $(this).serialize() + '&NonFormValue=' + NonFormValue,
You should be careful to URL-encode the value of NonFormValue
if it might contain any special characters.