Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

returning multiple values using php to jquery.ajax with json

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";
like image 498
Swadesh Avatar asked Dec 16 '22 21:12

Swadesh


2 Answers

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);
            });
like image 67
diEcho Avatar answered Jan 05 '23 00:01

diEcho


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)

like image 39
Manse Avatar answered Jan 05 '23 01:01

Manse