HTML Form submission technique via jQuery (gracefully degrades)

Tags:
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.

Very nice

Hi. This site rocks :-) Very nice. Greetings from China.

Why not use a hidden field as return_type??

I am sorry, but you can easily use a hidden field for return_type with value 'json'.. why go to adding an post variable on $.ajax ??

Hidden field will not work..

As far as I can see, a hidden field directly coded on form will not serve my purpose. Adding return_type on $.ajax method will ensure when JS is disabled/Blocked and the form is submitted, there will be no 'return_type' on the post field, so from Server-side script, I can process the request and then redirect to that page again, to show appropiate message.

With JS Enabled, I will add the return_type on $.ajax, and thus from Server-side I can understand that the post was made via Javascript technique, so I can return a JSON Formatted data from Server-side.

Thanks,

nice post

Nice way to provide an alternate for JS disabled browsers...

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
9 + 11 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.