HTML Form submission technique via jQuery (gracefully degrades)

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'.

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:
  1. <div id="messageDiv"><?php if( isset($_GET['msg']) ) {
  2. echo $_GET['msg']; } ?></div>
The form:
  1. <form name="addCustomerForm" id="addCustomerForm" method="post" enctype="application/x-www-form-urlencoded" action="somefile.php">
  2. <p>Name: <br />
  3. <input type="text" name="customerName" />
  4. </p>
  5. <p> Address: <br />
  6. <input type="text" name="customerAddress" />
  7. </p>
  8. <p>
  9. <input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" />
  10. <input type="hidden" name="return_url" value="URL_OF_CURRENT_PAGE" />
  11. </p>
  12. </form>
  13.  
  14. <script language="javascript" type="text/javascript">
  15. <!--
  16. $(function() {
  17. $('#addCustomerForm').submit(function() {
  18. // do form validation here
  19. $.ajax({
  20. type : "POST",
  21. url : "somefile.php",
  22. data : $(this).serialize() + "&return_type=json",
  23. dataType : "json",
  24. success: function(data){
  25. if( data.error != '0' ) {
  26. $('#messageDiv').addClass('error').html(data.msg);
  27. } else {
  28. $('#messageDiv').addClass('success').html(data.msg);
  29. }
  30. }
  31. });
  32. return false;
  33. });
  34.  
  35. });
  36.  
  37. // -->
  38. </script>
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:
  1. <?php
  2. /** After Server side validation is done.. **/
  3. $responseArr = array();
  4.  
  5. /** Assuming the process was successful **/
  6. if($success) {
  7. $responseArr = array (
  8. 'error' => '0',
  9. 'msg' => 'New Customer Added');
  10. } else {
  11. $responseArr = array (
  12. 'error' => '1',
  13. 'msg' => 'Error Adding Customer');
  14. }
  15.  
  16. if( isset($_POST['return_type']) && $_POST['return_type'] == 'json' ) {
  17. header("Content-Type: text/plain");
  18. echo json_encode($responseArr);
  19. exit;
  20. } else {
  21. // so, jQuery submission was not made..
  22. header('Location: '.$_POST['return_url'].'?'.http_build_query($responseArr));
  23. }
  24.  
  25.  
  26. ?>
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.
Tags: