Dilshi
Dilshi

Reputation: 553

cannot read json pass from php file by jquery

  [{
      p_date: "26-07-2013",
      c_no: "1",
      time_slot: "shift1"
  }]

   $.each(data, function (i, elem) {


      alert(elem[p_date]);

  }); 

i get above json from my php file.all i want to do is read it from jquery file.I tried above method to read that json .but it didn't work.

      i get the following error Uncaught SyntaxError: Unexpected token p 

Upvotes: 0

Views: 159

Answers (2)

krishwader
krishwader

Reputation: 11371

Shouldn't elem[p_date] be elem["p_date"] in your each function? Or you could also try elem.p_date.

 var data = [{
     p_date: "26-07-2013",
     c_no: "1",
     time_slot: "shift1"
 }]

 $.each(data, function (i, elem) {
     alert(elem["p_date"]);
     //or elem.p_date would also work.
 });

Demo : http://jsfiddle.net/hungerpain/c46br/

Edit :

If you get the following error message,

Cannot use 'in' operator to search for '77' in [{p_date: "26-07-2013" , c_no: "1", time_slot: "shift1" } ]

It means your (so-called) JSON is a string. You'll have to do this :

var formatted = JSON.parse(data);

Then, you can use formatted variable in each :

$.each(formatted, function (i, elem) {

PHP formatting :

This is how you make an array in PHP:

$first = true;
$json = array();
while ($row = mysqli_fetch_array($distributor_List)) {
  array_push($json, $row);
}
echo json_encode($json) 

This will ensure that you neednt use JSON.parse in JS :)

Upvotes: 5

bipen
bipen

Reputation: 36531

try this

$.each(data, function (i, elem) {
     alert(elem['p_date']); //notice the `''`
}); 

Upvotes: 0

Related Questions