I can process my form values by targeting the form class <form class="my_form_class">
:
jQuery.ajax({
type:"GET",
url: "/wp-admin/admin-ajax.php",
data: my_form_class,
context: this,
success:function(data){
// do stuff
}
});
This works great.
But I want to add more data, so I tried:
data: { my_form_class, security : 'foo' },
It did not work. What am I doing wrong here? I tried:
data: { my_form_class : my_form_class, security : 'foo' },
And it obviously didn't work either.
Data of the form can be serialized, and data can be sent as a string :) I didn't test this, but it should work :)
jQuery.ajax({
type:"GET",
url: "/wp-admin/admin-ajax.php",
data: $('.my_form_class').serialize() + "&security=foo",
context: this,
success:function(data){
// do stuff
}
});
According to the definition of jQuery ajax
data
Type: PlainObject or String or Array Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You may use jquery param and jQuery serialize:
$('.my_form_class').serialize() + '&' + $.param({security : 'foo'});
My snippet:
$(function () {
$('#btn').on('click', function(e) {
console.log($('.my_form_class').serialize() + '&' + $.param({security : 'foo'}));
$.ajax({
type:"GET",
url: "/wp-admin/admin-ajax.php",
data: $('.my_form_class').serialize() + '&' + $.param({security : 'foo'}),
context: this,
success:function(data){
// do stuff
}
}).fail(function(jqXHR, textStatus, errorThrown) {
console.log('ajax error: ' + textStatus)
});
});
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<form class="my_form_class">
First name:<br>
<input type="text" name="firstname" value="name"><br>
Last name:<br>
<input type="text" name="lastname" value="surname">
</form>
<button id="btn">Submit Form with Ajax</button>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With