Site Builder Studio

SITEBUILDERSTUDIO

Setting Form Action in jQuery AJAX

In a jQuery AJAX call, we set the the url to which the AJAX will pass the data.

Here are three options.

1 > HTML action

Use the action url coded into the HTML form we’re processing:

url: $(this).attr('action');

2 > Relative URL in the jQuery

If the code is always going to live in the same folder, for instance if you’re building a site that will never be replicated in another layer folder on this or any other site, you can code in the relative url right there in the ajax call.

url: "form-handlers/process-my-form.php"

3 > Use Absolute Path by referencing PHP global variables

If we want to use an absolute path (useful for if our code will end up living in many places) we’re in luck.

Here’s a trick to set the url in the jQuery by using the value of PHP global variables, or any url variable we set up in PHP (such as $site_url).

First, store the PHP variable inside a div which is not displayed to visitors. For example:

<div id="root-url" style="display:none">
<?php echo "http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']; ?>
</div>

Then use jQuery to get the contents of the div with id root-url to build the form action as an absolute path in the jQuery AJAX call like so;

var root-url = $("#root-url").text();

Use the new root-url jQuery variable to build the absolute path of the form processing script –

url: root-url+"form-handlers/process-my-form.php"

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
	}
    });
});

Clear form inputs with jQuery

jQuery doesn’t have function for clearing forms, but there is a way.

With this method you can clear form inputs with jQuery by re-loading the form.


<div id="container">
    <div id="content">
        <?php include("myform.php"); ?>
    </div>
</div>

$("#container").load("#content");

When the jQuery loads the content div into the container div, the file myform.php will essentially be refreshed and the form inputs will be cleared. This has been a neat trick to clear form inputs with jQuery.