0

From my database i fetched some data as json string.But unfortunately i can't access the data which is returned as response. Following is my php page to fetch data:

  require_once '../core/init.php';
   $answer=$_POST['answer_body'];
   $post_id=$_POST['userpost_post_id'];
   $answerer=$_POST['users_user_id'];
   if(isset($answer,$post_id,$answerer)){
     if(!empty($answer) && !empty($post_id) && !empty($answerer)){
           $db=DB::getInstance();
           if($result=$db->post_and_fetch("CALL login.post_and_fetch_ans(?,?,?)",array($answer,$post_id,$answerer))->result()){
                echo json_encode($result);
           }else{
              echo 'there was a problem';
           }
       }
   }

It returned as following:

Enter image description here and in the receiving part is following:(it currently prints undefined)

$.ajax('../includes/verifyanswer.php',{
        data:data,
        type:"POST",
        datatype:'json',
        success:function(response){


           alert(response['answer_body']); // prints undefined

        },
        error:function(response){
              alert(response);
           }
    })
Ashish Detroja
  • 1,084
  • 3
  • 10
  • 32
AL-zami
  • 8,902
  • 15
  • 71
  • 130
  • try.. alert(response[0]['answer_body']); – amit_183 Jan 06 '16 at 10:48
  • solved it..had to parse the json string using var obj=$.parseJSON(response); alert(obj[0]['answer_body']); – AL-zami Jan 06 '16 at 10:53
  • 1
    do var data = JSON.parse(json); and data.sth – DpEN Jan 06 '16 at 10:53
  • @DpĚN yah ..that will solve it too... thanks :) – AL-zami Jan 06 '16 at 10:54
  • alternatively, if you add a response header to tell the browser it's json it will be interpreted by jquery as a json object and not a string. I'm not sure how this is done in php but the key is 'Content-Type' and it's value needs to be 'application/json' – DarthDerrr Jan 06 '16 at 10:55
  • here is how it's done in php according to many upvotes: http://stackoverflow.com/questions/4064444/returning-json-from-a-php-script – DarthDerrr Jan 06 '16 at 10:57

1 Answers1

0

Your response is a string, not an array. You should use getJSON() to make sure the response is parsed into an object :

$.getJSON(
    '../includes/verifyanswer.php',
    data,
    function(response) {
        alert(response.answer_body);
    }
);
Brewal
  • 8,067
  • 2
  • 24
  • 37