bart2puck bart2puck - 3 months ago 6x
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


Try this:

echo json_encode($errors, JSON_FORCE_OBJECT);

Also, yout PHP script should contain:

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

before any echo statements.