php - JSON not working in javascript ajax request

368

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

330

Answer

Solution:

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{-code-2} and separating the entries with{-code-3}:

[{"name":"ehab"{-code-3}"mobile":"xxx"}{-code-3}{"name":"Hamza"{-code-3}"mobile":"zzzz"}]

Then you'd access it like this:

{-code-5}

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.

854

Answer

-----^|||[...]|||,|||[{"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)

Source

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.