-1

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

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

                debugger;
                },
                error: function (error) {
                 debugger;
              }

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);
        $data='';
        if(mysql_num_rows($res)> 0) 
                    {
                    for($i=0;$i<mysql_num_rows($res);$i++) {
                    $row=mysql_fetch_assoc($res);


                    $output =  array('name'=>$row['rec_name'],
                 'mobile'=>$row['mobile_number']);

                    echo json_encode($output);
                    }

please advice

Haifaa aa
  • 21
  • 3

1 Answers1

4

The JSON is invalid

{"name":"ehab","mobile":"xxx"}{"name":"Hamza","mobile":"zzzz"}
Here -------------------------^

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

You could make it an array by wrapping it in [...] and separating the entries with ,:

[{"name":"ehab","mobile":"xxx"},{"name":"Hamza","mobile":"zzzz"}]

Then you'd access it like this:

console.log(data[0].name); // "ehab"
console.log(data[1].name); // "Hamza"

Or using a loop, forEach, etc.


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

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • could you please help me how to write the JSON array ? $sql ="select * from recipients where `groupid`='$searchText'"; $res = mysql_query($sql); $num = mysql_num_rows($res); $data=''; if(mysql_num_rows($res)> 0) { for($i=0;$i$row['rec_name'], 'mobile'=>$row['mobile_number']); echo json_encode($output); } – Haifaa aa Dec 10 '15 at 11:02
  • i add the php code in the question please your help to write the json array in correct way – Haifaa aa Dec 10 '15 at 11:04
  • Create an array. Add a new object each time you go around the loop. Convert *only* the *final result* to JSON. – Quentin Dec 10 '15 at 11:05
  • @Haifaaaa: That would be a **new** question. But it's [already been asked and answered](http://stackoverflow.com/questions/6739871/php-create-array-for-json), just search for "Create JSON PHP". – T.J. Crowder Dec 10 '15 at 11:07