php - JSON not working in javascript ajax request


please your help, i have problem in my ajax request. i have return text data and i want to convert it to JSON using json_parse but it does't work

the data that return from the ajax request looks like this :

data = "{"name":"ehab","mobile":"xxx"}{"name":"Hamza","mobile":"zzzz"}"

i want to convert this data to json i use the following ajax request

                type: "POST",
                url: "getGroup.php",
                data: { "searchText" : number},
                 success: function(data)
                data = JSON.parse(data);

                error: function (error) {

if i use this way error message returns

Uncaught SyntaxError: Unexpected token {

my php array file

$sql ="select * from recipients where `groupid`='$searchText'";

        $res = mysql_query($sql);
        $num = mysql_num_rows($res);
        if(mysql_num_rows($res)> 0) 
                    for($i=0;$i<mysql_num_rows($res);$i++) {

                    $output =  array('name'=>$row['rec_name'],

                    echo json_encode($output);

please advice




The JSON is invalid


You cannot have two objects at the top level like that.

You could make it an array by wrapping it in{-code-2} and separating the entries with{-code-3}:


Then you'd access it like this:


Or using a loop{-code-3}{-code-6}{-code-3} etc.

Side note: If your server returns correctly-identified{-code-3} valid JSON{-code-3} jQuery will parse it for you before calling your{-code-7} function{-code-3} so no need for the{-code-8} in your code.



-----^|||[...]|||,|||[{"name":"ehab","mobile":"xxx"},{"name":"Hamza","mobile":"zzzz"}]|||console.log(data[0].name); // "ehab" console.log(data[1].name); // "Hamza"|||forEach|||success|||JSON.parse

People are also looking for solutions to the problem: The value of dropdown after posting from IE7/8, displays as array, but normal value in firefox using PHP,HTML,JAVA(DHTMLSUITE modal message)


Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.