bart2puck bart2puck - 4 months ago 8
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:

.....
datatype:'json',
success: function(result)
{
alert(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

Try this:

echo json_encode($errors, JSON_FORCE_OBJECT);

http://www.php.net/manual/en/json.constants.php

Also, yout PHP script should contain:

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

before any echo statements.