While working with the WordPress REST API, I found I was writing jQuery AJAX calls with data objects that were getting longer and longer as I submitted more complex forms. I used to list out each form field that I wanted to submit, like this:
jQuery.ajax({
url : '/wp-json/my-namespace/v1/my-endpoint/',
async : true,
dataType: 'json',
type : 'POST',
data : {
first_name: jQuery("#first_name").val(),
last_name: jQuery("#last_name").val(),
email: jQuery("#email").val(),
language_preference: jQuery("#language").val(),
country_code: jQuery("#country_code").val(),
phone_number: jQuery("#phone").val(),
start_date: jQuery("#start_date").val()
}
}).done(function() {
// Handle Success
}).fail(function(xhr, status, error) {
// Handle Failure
});
Then I discovered jQuery’s serialize function. You can use it to take each element in a form and serialize their values into a string. The resulting code now looks like:
jQuery.ajax({
url : '/wp-json/my-namespace/v1/my-endpoint/',
async : true,
dataType: 'json',
type : 'POST'
data : jQuery("form").serialize(),
}).done(function() {
// Handle Success
}).fail(function(xhr, status, error) {
// Handle Failure
});
Now, if you add or remove fields from your form, you don’t need to modify the Javascript.
[…] Source: Submitting All Form Fields via AJAX to a REST Endpoint – Shawn Hooper – WordPress Developer … […]
Don’t forget FormData https://developer.mozilla.org/en-US/docs/Web/API/FormData/FormData