DJack
DJack

Reputation: 639

Ajax read PHP generated json

So I want to send a json to an ajax call but I don't know how to read the json when is sent. And also my json looks strange because of the backslashes...

This is my ajax:

    function find(){
        var type = $('#object_type').val();
            $.ajax({
                type : 'POST',
                url : 'get_user.php',
                data : {
                    'type' : type
                },
                dataType : 'json',
                error : function(response){
                    alert('SOMETHING WENT WRONG');
                },
                success : function(response){

This is what I get as a response:
"[{\"name\":\"Test\",\"link\":\"test.php\"},{\"name\":\"Test2\",\"link\":\"test2
.php\"}]"
                }
            });     
    }

This is my PHP function:

    $type = $_POST['type'];
    $user_array;
    $user = mysqli_query($conn, "SELECT name,link FROM user WHERE `type` LIKE '%".$type."%'") or die();

            while ($row = mysqli_fetch_array($user, MYSQLI_ASSOC)) {

                $row_array['name'] = $row['name'];
                $row_array['link'] = $row['link'];
                array_push($user_array, $row_array);
            }
        mysqli_close($conn);
        $result = json_encode($user_array, 128);
        echo json_encode($result);

Upvotes: 0

Views: 107

Answers (2)

Mouser
Mouser

Reputation: 13304

As provided in techierishi's answer. Do not encode your response twice. Just do

 echo $result;

The JSON should be valid and parsed, why?

  • json_encode is used on a valid PHP array returned from a MySQLi query.
  • dataType is used, explicitly forcing jQuery to JSON.parse the response and no errors where raised during that process.

The JSON that is returned has the following structure

ROOT
   ARRAY
       ARRAY OBJECT
             OBJECT PROPERTY 

To address something like that:

root[array index].property

Will give you the array's value, which is an object. That object has multiple properties.

[] means array
{} means object

So [{name:"value 1"},{name:"value 2"}] is actually

ARRAY
   [0].name = value 1
   [1].name = value 2

So retrieving information like name from your JSON will be:

response[0].name; // = test

Upvotes: 4

techierishi
techierishi

Reputation: 390

First change that you should make : You don't need to encode two times

$result = json_encode($user_array, 128);
echo json_encode($result);

should be

 $result = json_encode($user_array, 128);
 echo $result;

Now the response should look like

[{"name":"Test","link":"test.php"},{"name":"Test2","link":"test2
.php"}]

which is a valid Javascript Array and can be accessed using following code :

var len = response.length;
for(i=0;i<len;i++){

  console.log(response[i].name);
  console.log(response[i].link);

}

Upvotes: 4

Related Questions