Site Builder Studio

SITEBUILDERSTUDIO

Form submission with AJAX

To submit a form by AJAX, ie using javascript with php to process a html form, use something like the code below.

Note that we’re using the ‘on’ click event, so that even if the div that contains the trigger gets refreshed the function will still be bound.

In this example, the form-handler file is called with the form data as a POST variable array. To change it to use GET instead, simply change the ajax type value to GET. Here’s the basics-

$('body').on('submit', '#form-submit-btn', function (e) {
    e.preventDefault();
    var form = $(this);
    var post_url = "form-handler.php";
    var post_data = form.serialize();
    $.ajax({
	type: 'POST',
        url: post_url,
	data: post_data,
        success: function () {
                // do something
	}
    });
});