Dual form processing

Recently, a client of mine wanted a single web form, residing on the localhost to submit the form contents to a database in the localhost, and as well as to a web server simultaneously. Although this sounds like an unnecessary duplication of data, my client wanted some of the form data to be stored on the localhost for the intranet applications to use. Achieving this functionality would have been a piece of cake, if we were not handicapped by the unavailability of cross-domain AJAX. For those of us familiar with AJAX, we know that we cannot send an AJAX request to a remote server due to security reasons – atleast not in a reliable, hack-less way.

So, instead of looking for a pure AJAX solution, I decided to implement this functionality by using a combination of AJAX (for the localhost) and a traditional PHP POST request (for the web server). The trick here is to execute the AJAX call before the form is submitted – by catching the form submission event using JavaScript. Once the AJAX call is successful, we allow the default form submission to take place. In case there is an error with our AJAX call, we should stop the propogation of the traditional form submission too.

Ok, so let’s start off with a simple example – a no-frills form with a few fields.


<form method="post" id="webform" action="http://www.example.com/path/to/PHPscript.php">

<label for="firstname">first name:</label>
<input type="text" name="firstname" id="firstname" value="" />

<label for="lastname">last name:</label>
<input type="text" name="lastname" id="lastname" value="" />

<label for="email" id="l_email">email address:</label>
<input type="text" name="email" id="email" value="" />

<input type="submit" name="Submit" id="submit_butt" value="Submit" />
<input type="reset" />

</form>

When the above form is submitted as it is, the form contents will be sent to the PHP script in the webserver. As I mentioned earlier, what we need to do now is “catch” this form submission event and insert our AJAX call before that. Let’s see how we can do that now. We will be using jQuery for our JavaScript needs.


$(document).ready(function(){
$("#webform").submit( function()
{
var success = -1;

$.post("localScript.php",
{
firstname: $("#firstname").val(),
lastname: $("#lastname").val(),
email: $("#email").val()
},

function(response){

if(response.status == "0")
success = false;
else
success = true;

}, "json");

var d = new Date();
var t = d.getSeconds();

while(success==-1)
{
var d = new Date();
if(d.getSeconds() - t > 4)
{
success = false;
break;
}
}

return success;
});
});

We set-up an event handler using jQuery, which fires whenever the form is submitted. We then make an AJAX call to the localhost to submit the form contents. We have a callback function which checks the status of the AJAX call. In case, any error occurs on the localhost, an error code can be returned (in our case, the status value will be 0) and we have to stop the form submission by returning “false” from the event handler function. This will stop the default action of the submit button, i.e. it will prevent the HTTP form submission.

This is achieved using a hack. Since the script will not wait for the callback function to return, the next statement, i.e. the “return” statement will be executed immediately after the $.post() call is made to the server. However, we cannot return from the function without knowing whether the operation on the backend succeeded or not. Since, JavaScript does not natively have any sleep()-like function, we have to force our script to get into a blocked state using a while() loop. We then manually terminate the while loop if we did not hear back from the server within a “few” seconds. In our example we have defined the timeout to be 4 seconds. In case we don’t hear from the server within this time, we will terminate the form submission by returning a “false”. This elaborate hack is required to ensure that we do not proceed to the next stage without knowing what happened to the data we submitted to the localhost.

If everything goes well in the localhost, the contents of the form will be processed and stored in the localhost database by the PHP script we have called using AJAX. The submit event handler will then return “true”. This would in turn cause the form to be submitted to the PHP script on the remote server, as defined in the action attribute of the <form> tag. Once the form is submitted, the browser requests, and loads this PHP script. The PHP scripts recieves the form contents as POST variables and saves them (by perhaps, storing them in a database).

We are not done yet, though. We still have to send the user back to a page on the localhost once the PHP script has finished processing and storing the form contents. We do that by:


$redirect_url = "http://localhost/path/to/some/page";
header( 'Location: ' . $redirect_url );
exit;

It is important that the header() is called before any actual output is sent to the browser. For example, you should not have any echo statement, or raw HTML output before calling the header().

That’s about it! Now we are really done! In most cases, you will notice that this entire process is so slick that your user would hardly notice the redirection from the page on the webserver to the page on the localhost! I have put together a barebones HTML page containing the code fragments above, which you can download for your reference and use from here.

No user responded to this post

You must be logged in to post a comment.

full indir download