I have an HTML form that submits to a PHP file for MySQL insertion using the Jquery Form Plugin’s .ajaxSubmit method. I was having trouble getting error responses from the server if there were errors, and a success response if there were no errors. I’ve got the code working, but I don’t understand why!
Pertinent snippet of the PHP submission file:
$reqs = array('userName', 'Pwd', 'firstName', 'lastName', 'email', 'cellPhone', 'homePhone', 'role');
foreach($reqs as $req) {
if((!isset($_POST[$req])) || (empty($_POST[$req]))) {
$newerr = "The field " . $req . " is required.";
$errors[] = $newerr;
}
}
if(!empty($errors)) {
echo json_encode($errors, JSON_FORCE_OBJECT);
} else {
then create the MySQL record and
$success = array('response'=>"Request successfully submitted. Your account must be configured before you can access the user panel. Please watch for an email confirming your registration and configuration.");
echo json_encode($success);
The success function in the .js is:
function processJson(data) {
if(data.response) {
$("#frmPrntRgstr").slideUp("normal", function() {
$("#frmPrntRgstrRspns").append(data.response).slideDown("normal");
})
} else {
for(var error in data) {
$("#frmPrntRgstr").prepend(data[error]);
}
}
}
This does what I want it to, and I understand the first part. There is only a 'response' key in the JSON object if it’s gotten past error checking. Firebug shows this as the server Response:
{"response":"Request successfully submitted. Your account must be configured before you can access the user panel. Please watch for an email confirming your registration and configuration."}
I don’t understand why the syntax 'data[error]' or simply 'data' works for reading back the errors. The response shown in Firebug is:
{"0":"The field cellPhone is required.","1":"The field homePhone is required."}
The JSON shown in Firebug is:
0 "The field cellPhone is required."
1 "The field homePhone is required."
It doesn’t say error in the key, and it doesn’t define a new “Errors” object. So why does that Javascript allow the definition `’data[error]’` if there’s neither an object nor a key defined as error in the response? I guess `’data’` works because it’s just reading back each value in the returned object.
JSON encodes the contents of a variable, but does not include the variable’s own name. Nothing says that you have to pass back only a single string via JSON. You can encode an entire message system in a single variable. So encode any messages you want, a sub-variable to say “error occured”, any error message(s) associated with that error condition, etc…
Then you can have your JS check for any errors with
if (data.errors.length > 0)or similar.