4

i'm trying to make a simple call to data from database using php and ajax. I need multiple results. hence i'm using json method. But its not working.

$.ajax({
  type: "POST",
  data: "qid=162",
  url: "activity_ajax.php",
  dataType: json,
  success: function (data) {
    alert(data.first);
  }
});

My activity_ajax.php page returns the following

echo "first":"Steven","last":"Spielberg","address":"1234 Unlisted Drive";
0

2 Answers 2

11

you can send multiple data in an array and then use json_encode

$output =  array('first'=>'Steven',
                 'last'=>'Spielberg',
                 'address'=>'1234 Unlisted Drive');

echo json_encode($output,JSON_FORCE_OBJECT);

and on other side you can access the value by this way

 success : function(resp) {(
              alert(resp.first);
              alert(resp.last);
              alert(resp.address);
            });
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks diCho. it solved the issue. I was missing those "" at dataType: "json" parameter
1

Your not returning valid JSON ... change your PHP to this :

$temp = array('first' => 'Steven', 'last' => 'Spielberg', 'address' => '1234 Unlisted Drive');
echo json_encode($temp);

and it will return valid JSON.

The json_encode method returns valid JSON from a variety of sources (an associative array being one)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.