Now I didn't read all your code, instead I though I'd give you some tips for when AJAX:ing forms or other things.
Instead of first building the JavaScript + AJAX version of the form, start with the pure version. The one that will work in browsers all over the planet on all types of devices.
Once that's finished you hijax that form. With jQuery and the jQuery Form plugin (http://www.malsup.com/jquery/form/) it couldn't be easier. Say you've already got your form set up:
<form method="post" action="some-action.php" id="my-form">
<p><label>Some field<br><input type="text" name="foo"></label></p>
<p><input type="hidden" name="bar" value="1"><input type="submit" value="Go"></p>
</form>
And you've made sure that some-action.php
handles the form submission properly (without AJAX) then simply:
$('#my-form').ajaxForm(function (data) {
alert(data); // data returned by some-action.php
});
Now if you want to do different things in some-action.php
depending on whether it's an AJAX call or not (you may want to redirect back to the previous page on non AJAX calls for example) you can simply check $_SERVER['HTTP_X_REQUESTED_WITH']
, I usually do (where you keep constants):
define('XHR', (
isset($_SERVER['HTTP_X_REQUESTED_WITH']) and
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
));
And then later in some-action.php
:
if (XHR) {
die(json_encode(array('success' => true)));
}
else {
header('Location: ' . $_SERVER['http_referer']);
}
The benefits of so called progressive enhancement (purest version first) over graceful degradation (fanciest version first) is the same as those of mobile first design. They're both better explained elsewhere like Brad Frost's blog: http://bradfrostweb.com/blog/web/mobile-first-responsive-web-design/