HTML Form submission technique via jQuery (gracefully degrades)
Published by on Jan 20, 2009
Since I started using jQuery (~10 months ago), I have been mostly using jQuery's $.ajax function for form submission as it provides an easy way to post form values and retreive JSON format easily. But, when using Javascript, there's always the question of 'graceful degradation'.
( **note: for sake of simplicity, I have placed the messageDiv on top of form **)
The messageDiv: The form:
In the above JS code, I am adding an extra Post variable 'return_type' with value 'json', whenever I am posting by $.ajax technique.
Now, the following is the PHP Code on submission Page:
The PHP code itself is self-explanatory. If there's a return_type in $_POST and has value 'json', then echo JSON values, otherwise redirect to return_url on $_POST passing the response values as $_GET.
Here's a technique I use often to provide an alternative method to HTML Form submission for JS Disabled Browsers.
Here's a Basic HTML Form with its corresponding jQuery script:( **note: for sake of simplicity, I have placed the messageDiv on top of form **)
The messageDiv: The form:
<form name="addCustomerForm" id="addCustomerForm" method="post" enctype="application/x-www-form-urlencoded" action="somefile.php"> <p>Name: <br /> <input type="text" name="customerName" /> </p> <p> Address: <br /> <input type="text" name="customerAddress" /> </p> <p> <input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /> <input type="hidden" name="return_url" value="URL_OF_CURRENT_PAGE" /> </p> </form> <script language="javascript" type="text/javascript"> <!-- $(function() { $('#addCustomerForm').submit(function() { // do form validation here $.ajax({ type : "POST", url : "somefile.php", dataType : "json", success: function(data){ if( data.error != '0' ) { $('#messageDiv').addClass('error').html(data.msg); } else { $('#messageDiv').addClass('success').html(data.msg); } } }); return false; }); }); // --> </script>
Now, the following is the PHP Code on submission Page:
Tags: