I have build a simple but working AJAX form using jQuery. The form is validated with jQuery before submit and then after successful submit again with PHP.
The only problem is the error handling. When the PHP-check returned that all fields are ok, I display a success message. If there was an error, I simply display "there was an error".
How can I send back data from PHP to jQuery so invalid fields can be marked as invalid?
Or is such form of error handling unnecessary as the dynamic highlighting needs JavaScript turned on and if JavaScript is turned on, the form can't be submitted wrong?
Basically, my valid checks look like this (simplified of course):
function checkSomething( $something ) {
$valid = true;
if ( strlen( $something ) === 0 ) {
$valid = false;
}
return $valid;
}
At the end of the script, I do it like this:
if ( checkSomething( $something ) && checkThis( $this ) && checkThat( $that ) ) {
echo "success";
} else {
echo "error";
}
And in my JavaScript/jQuery code it looks like this:
$.ajax({
url: "form.php",
type: "POST",
data: string,
success: function ( result ) {
if ( result == "success" ) {
alert( "success" );
} else {
alert( "error" );
}
}
});