I have the following php code that runs after validation:
try {
if (isset($filtered) && !isset($errors)){
$p['email']=$filtered['email'];
# check if email exists
if ($user->userExists($p)){
$msg['error'] = false;
$msg['msg'] = 'This email address is already in our database';
} else {
# insert user data into database
$user->saveUser($filtered);
$msg['error'] = false;
$msg['msg'] = 'Successful! Go back to our homepage.';
}
} else {
# echo errors back
foreach ($errors as $value) {
$msg['error'] = true;
$msg['msg'] = $value;
}
}
I prepare the json data as follows:
# header encode
header('Content-type: application/json');
# return json encoded data
echo $encoded = json_encode($msg);
A direct array like this one below works fine.
header('Content-type: application/json');
$msg['error'] = true;
$msg['msg'] = 'Please enter an email address.';
echo $encoded = json_encode($msg);
I can’t seem to figure out what the problem with my php logic could be. Kindly help.
The only difference I can see there is that in the version that works, you call
header()before anything else.Try moving
above the try/catch. I have a suspicion that the reason you are getting this problem is because you are implicitly accessing the array
$msgbefore you have created it, which throws anE_NOTICE(or it might beE_STRICT, I can’t remember) and causes something to be written to the output buffer, so the headers are sent, and you can no longer manipulate them – although if this were the case I would expect it to break your JSON as well…Regardless, try the above and report back.