jQuery Tip: Submitting All Form Fields via AJAX to a REST Endpoint


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
Source: https://managewp.org/articles/14365/jquery-tip-submitting-all-form-fields-via-ajax-to-a-rest-endpoint




source https://williechiu40.wordpress.com/2017/02/10/jquery-tip-submitting-all-form-fields-via-ajax-to-a-rest-endpoint/