I admit to cutting corners when it comes to graceful degradation, but one area where you certainly don't want to skimp is form submissions. Let's even take the hypothetical case where 100% of your users have JavaScript enabled. What if there's a small JavaScript error? How JS is parsed/executed is entirely up to the myriad of various web browsers out there. On the server side, it's just your scripting language, so you can be relatively sure it's gonna work.

So what's best way to go about this? As with most web interactions, where you want to maintain functionality without the presence of JavaScript, you want to build and test without any JS enhancements first. For many of us, that might mean disabling JavaScript in our browser.

Then, when you are ready to add the AJAX solution to your form submission, you might consider reusing the same processing script, but passing in a "flag" to indicate that this request is coming from JavaScript, so don't do any redirection when it's complete.

Example:

<form action="blah.php">
  <input type="text" name="field1" />
  <input type="submit" />
</form>

<script type="text/javascript">
  $(form).submit(function() {
    var url = 'blah.php?field1=' + $(this).children('input[name=field1]') + '&ajax=1';
    $.ajax({
        url: url,
        success: function() { document.write('Nice job - form submitted!'; }
    });
  });
</script>

PHP Script

<?php

// processing code

if(isset($_GET['ajax']))
  return true;
else
  header('Location: thankyou.php');


?>

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *