thegumba
thegumba

Reputation: 61

Understanding JSON Response with PHP json_encode

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.

Upvotes: 1

Views: 4790

Answers (2)

Dr.Molle
Dr.Molle

Reputation: 117354

for(var error in data)

this is a method to walk through objects, 'error' in that case is not a label, you may see 'error' here as a variable containing the label(the current key, or better called as member-name). You may use here whatever you want to as "variable"-name.

for(var foo in data) {
        $("#frmPrntRgstr").prepend(data[foo]);
        }

...will do the same.

This is nearly similar to this PHP-code:

foreach($data as $error => $message )
{
    echo $data[$error]
}

Where $data is an array and $error the current key while walking through the array.

Upvotes: 0

Marc B
Marc B

Reputation: 360782

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...

$msgs = array();
if (...) {
    $msgs['message'] = 'blah blah blah';
}

if (...) {
    $msgs['errors'][] = 'error message here';
}

echo json_encode($msgs);

Then you can have your JS check for any errors with if (data.errors.length > 0) or similar.

Upvotes: 1

Related Questions