Part of the project I’m working on now uses jQuery AJAX methods to process certain requests. In particular, the first implementation of this was the simple submission of a form that saves some configuration options. These days who wants to see the ugly/old-style spinning loading icon when they click submit? I’d say that AJAX has more impact, seems more professional and is … well … cooler.
Everything worked fine until I came to managing the results when something *didn’t* work, i.e. when a PHP script returned an error. Here’s what I used that did work.
Firstly, I’ll just say that this page isn’t going to be about how to use jQuery, AJAX or anything like that; there are many thousands of pages on the web already that do a far better job of that than I could. As a starting point I’d highly recommend the jQuery documentation – it’s pretty good.
Here’s my jQuery function that gets triggered when the submit is clicked.
<script type="text/javascript"> // jQuery script $(function() { $('#return_message').hide(); $("#save_button").click(function() { var style = $("#style").val(); var dataString = 'action=set_style&style=' + style; $.ajax({ type: "POST", url: "include/ajax.php", data: dataString, success: function(response) { if(response.indexOf("error") > 0) { $('#options_form_div').html("<div id='message'><span class='return_message_bad'>Oops, something broke while saving the configuration! Please <a href='__admin.php'>refresh this page</a> and try again shortly.</span></div>").hide().fadeIn(1500, function(){ $('#message'); }) } else { $('#options_form_div').html("<div id='message'><span class='return_message_ok'>Great, everything worked and your new configuration has been saved successfully!<br />Please note that if you changed the style the new style will be visible the next time this page is loaded (or you can click <a href='__admin.php'>here</a>).</span></div>").hide().fadeIn(1500, function(){ $('#message'); }) } } }); return false; }); }); </script> |
And here is the part of ajax.php that matters:
$result = $database->DoQuery($query, $database->connection); if (!$result) { $return['error'] = true; $return['msg'] = 'Error updating style.'; } echo json_encode($return); |
The success(response) part of the jQuery script above is the key part – without it you’ll never know if your PHP file (ajax.php in this case) returns an error. If ajax.php exists and you don’t have the response set as a parameter, the jQuery function will be successful even if the PHP file throws an error.
I’m sure there are other, more elegant ways to do this, perhaps in the jQuery documentation. This way works for me though.