ashTon
ashTon

Reputation: 1141

How can I access this result

I have this result from my server and I want to access the value of mem and pid

{"mem":"7","pid":"5"}{"mem":"9","pid":"7"}{"mem":"10","pid":"7"}{"mem":"8","pid":"5"}

I tried echo the value from my console.but it did not show.

 $.ajax({
                type:'post',
                dataType:'json',
                data:'mydata'
                url:'tomyurl',
                success:function(data){
                 console.log(data[0].mem);//did not show the value


                   });

EDIT

here is my server side script

  public function display_children($parent,$level){
 try {
          $cmd = $this->connection->prepare('SELECT mem,pid from mytree where pid = ?');

          $cmd->execute(array($parent));


          $results = array(
              'mem' => array(),
              'pid' => array()

          );

          while ( $row =  $cmd->fetch(PDO::FETCH_ASSOC)) {


              $results['mem']=$row['mem'];
              $results['pid']=$row['pid'];

              echo json_encode(results);
              $this->display_children($row['mem'], $level + 1);

          }


      }
      catch(PDOException $ex){
          return $ex->getMessage();
      }

  }

I followed here on how to query hierarchical-data-database

and I'm having problem in accessing the value of my mem and pid.

Thank you in advance.

Upvotes: 0

Views: 54

Answers (1)

aroth
aroth

Reputation: 54856

That's not valid JSON as written. You probably want to ensure that your server is returning a valid array, like:

[{"mem":"7","pid":"5"},{"mem":"9","pid":"7"},{"mem":"10","pid":"7"},{"mem":"8","pid":"5"}]

If it is, the code you've supplied should work. To get all the mem and pid values in the array, you can do something like:

for (var index = 0; index < data.length; index++) {
    var item = data[index];
    console.log("index=" + index + ", pid=" + item.pid + ", mem=" + item.mem);
}

http://jsfiddle.net/cn7mzxws/1/

Since you're using jQuery, you can also use $.each to accomplish the same thing.

Though if you only care about the mem value for the first item, then data[0].mem is correct, once your data is correctly packed into a JSON-array.

Upvotes: 1

Related Questions