Totti
Totti

Reputation: 675

Ajax JSON exception Unexpected token [

hi i have a page contains a link , when user click the link i want to go to database and retrieve two arrays , but when i alert those two arrays i got this exception

Unexpected token [

this is my js code

function acNewConcpet(element){
    var parent = element.parentNode;
    parent.removeChild(element);
    var concpetSelect = document.createElement('select');
    var relationSelect = document.createElement('select');
    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){
        if(xmlhttp.readyState==4 &&  xmlhttp.status==200){
            var data = JSON.parse(xmlhttp.responseText);
            alert(data);
        }

    }
    xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+"concept"+"/TRUE",true);
    xmlhttp.send();
}

and this is my php code

public function getRelatedConceptsAndRelations($concpetName, $Ajax) {
        if ($Ajax) {
            $concepts = array('c1', 'c2');
            $relations = array('r1','r2');
            echo json_encode($concepts);
            echo json_encode($relations);
        }
        return;
}

why is this exception ? and how can i solve it ? and how can i receive those two arrays in my js ? this is full code code

Upvotes: 0

Views: 636

Answers (3)

Joseph
Joseph

Reputation: 119887

You are returning malformed JSON. From what I understand from your code, it prints out this JSON:

['c1','c2']['r1,r2']

You cant have 2 arrays like this. You must print it like:

[['c1','c2'],['r1','r2']]

Sorry for my rusty PHP, but you must have something like:

$json = array(
    array('c1','c2'),
    array('r1','r2')
);

echo json_encode($json);

Since you are using jQuery, why not use $.getJSON()?

$.getJSON(url,function(returnData){
    //returnData is the parsed JSON
});

Upvotes: 3

Johannes Klauß
Johannes Klauß

Reputation: 11052

When you response a JSON, it needs to be one JSON, but you are sending two seperate arrays.

Merge those two JSONs into one.

Update:

Do it like this:

public function getRelatedConceptsAndRelations($concpetName, $Ajax) {
    if ($Ajax) {
        $concepts = array('c1', 'c2');
        $relations = array('r1','r2');
        echo json_encode(array($concepts, $relations));
    }
    return;
}

Upvotes: 1

SLaks
SLaks

Reputation: 888223

JSON.parse can only parse a single JSON literal.

You should combine the two arrays into a single object with two properties.

Upvotes: 3

Related Questions