0
  [{
      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 
0

2 Answers 2

5

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 :)

Sign up to request clarification or add additional context in comments.

11 Comments

this should actually work, unless data doesn't get filled as expected.. make sure of its content first
@Dilshi if it doesn't work then you haven't shown us the relevant code
@Dilshi pls make a fiddle for your problem. Then we'll know whats really wrong :)
function pop_search_prescription(param) { $.ajax({ type: "POST", url: "Patient_Handler.php", data: { search_pres: param }, success: function(data) { $.each(data, function(i, elem) { alert(elem["p_date"]); }); } });
above i get get the json to data variable.it works fine.but i cannot display it.
|
0

try this

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

1 Comment

it works when i hardcode that string.but when i try to prin the same string taken from php .it gives folowing error.annot use 'in' operator to search for '77' in [{p_date: "26-07-2013" , c_no: "1", time_slot: "shift1" } ]

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.