bart2puck bart2puck - 1 year ago 66
PHP Question

ajax calls return php array, json doesnt seem correct

I have an ajax call that fires a php script that returns an array.

the php:

$errors[1] = "you didn't enter name";
$errors[2] = "your email is incorrect";
$errors[3] = "You didnt enter password";
echo json_encode($errors);

the javascript:

success: function(result)

I would expect to see:

{"1":"you didn't enter name","2":"your email is incorrect","3":"You didnt enter password"}

instead i see:
["you didn't enter name","your email is incorrect","You didnt enter password]

it seems like the json_encode did something funky. what am i missing

Answer Source

Try this:

echo json_encode($errors, JSON_FORCE_OBJECT);

Also, yout PHP script should contain:

header("Content-Type: application/json");

before any echo statements.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download