views:

76

answers:

2

I have a PHP API I'm working with that outputs everything as JSON.

I need to call one of the API methods and parse it out using an AJAX request. I am using jQuery (though it shouldn't matter).

When I make the request it errors out with a "parsererror" as the textStatus and a "Syntax Error: invalid label" when I make the request.

Simplified code:

$.ajax
({
    type: "POST",
    url: "http://mydomain.com/api/get/userlist/"+mid,
    dataType: "json",
    dataFilter: function(data, type)
    {
        /* Here we assume and pray */
        users = eval(data);
        alert(users[1].id);
    },
    success: function(data, textStatus, XMLHttpRequest)
    {
        alert(data.length); // Should be an array, yet is undefined.
    },
    error: function(XMLHttpRequest, textStatus, errorThrown)
    {
        alert(textStatus);
        alert(errorThrown);
    },
    complete: function(XMLHttpRequest, textStatus)
    {
        alert("Done");
    }
});

If I leave off the eval(data) then everything works fine. Well, except for data still being undefined in success. Note that I'm taking an array of objects in PHP and then passing them out through json_encode. Would that make any difference?

There has been no progress made on this. I'm willing to throw more code up if someone believes they can help.

Here is the PHP side of things

private function _get_user_colors($id)
{
    $u = new User();
    $u->get_where(array('id' => $id));

    $bar = array();

    $bar['user'] = $u->stored;

    foreach($user->colors as $color)
    {
        $bar['colors'][] = $color;
    }

    echo(json_encode($bar));
}

I have had zero issues using this with other PHP based scripts. I don't know why Javascript would take issue with it.

+1  A: 

Parsererror generally indicates that the response from the server is malformed. If you load it directly in a browser does it look good?

Rob Drimmie
Yes it looks fine. And all the output is from php's `json_encode` function.
Josh K
+1  A: 

Try outputting alert(request.responseText) (and rename the first argument to request) in your error handler. That should fix you up with the errorsome output of your script.

bouke
It shows me my response. And there is no errorsome output. It does however trigger `success` if I leave off the `eval(data)`. How else should I decode the `JSON`?
Josh K
Oh! jQuery's ajax() function handles decoding for you. If you're using Chrome or Firefox + Firebug, replace the eval(data) line with <code>console.log(data)</code> and inspect the object - it should have all your data as properties.
Rob Drimmie
@Rob: It doesn't seem to recognize `console.log` and if I simply `alert(data)` it says `undefined`.
Josh K