Handling Ajax Script Errors with jQuery

While I've read a lot of manuals on the subject, I've never been instructed in web development. This has a few disadvantages, but one major advantage - I have no pre-conceived notions about how things should be done. That means that a good deal of my methods will be "outside the box", and that's how I like it. My personal growth is much greater when I'm coding outside of an established framework.

There are many acceptable (and probably accepted) ways you can handle Ajax script errors, but I've come up with an error-handling method that is very simple and works exactly the way that I need it to. It involves checking the output from the Ajax script for an error message. In other words, if I have an error in my Ajax script, the script simply dies with the output "Error: (whatever the error is)". This is easily picked up on the Javascript side with a substr() statement. The error is then sent to the user with an alert() statement and execution stops.

On the Javascript side, this amounts to three extra lines of code (which could actually be combined into one):

$.post(url, $('#form2').serialize(), function (data) { // Post form2 to an Ajax script if (data.substr(0, 5) == "Error") // Detect the error alert(data); // Alert the user else // Otherwise, continue processing $('#mod_table').append(data); // No error - do something legit with the data });

I wrote this particular Ajax script to creates a new forum moderator and then appends a row containing the moderator info to a table with the id "mod_table". This data could be handled even more efficiently (albeit less simply) if I used JSON. This will require some additional lines of code:

$.post(url, $('#form2').serialize(), function (data) { // Post form2 to an Ajax script
if (data.errmsg.substr(0, 5) == "Error") // Detect an error
alert(data.errmsg); // Alert the user
else { // Otherwise, continue processing
$("#mod_table > tbody:last").append($('<tr>') // Add a table row
.append($('<td>') // Add cell 1
.append(data.mod_name) // Add moderator name to cell 1
) // close cell1 append
.append($('<td>') // Add cell 2
.append(data.forum_name) // Add forum name to cell 2
) // close cell2 append
); // close row append
} // close else
}, "json"); // close post->function statements