Sahil
Sahil

Reputation: 1983

json object usage with ajax returned array

I have a problem with the returned array from ajax call.

the array is encrypted using json. it is as below

while ($found_course = mysql_fetch_assoc($sql)) {

    $info[] = array(
        'code' => $found_course['course_code'],
        'name' => $found_course['course_name']   );

}
echo json_encode($info); //this is returned to javascript

then the problem is that I am unable to use the above array returned in javascript. I tried using the $.each method but to no avail. the eval() also do not work as it give output as [object object]. Can someone please help me with this.

All I want is to be able to acces the code and the name of the course saperately

Thanks.

Upvotes: 0

Views: 365

Answers (3)

Rene Pot
Rene Pot

Reputation: 24815

Just loop through it with for()

for (var c in myAjaxArray){
    myAjaxArray[c].code; // contains the code
    myAjaxArray[c].name // contains the name
}

Make sure you set the dataType in the jQuery ajax call to "JSON" to make sure you have a json Object. Or use the $.getJSON() function.

Upvotes: 3

thenetimp
thenetimp

Reputation: 9820

This should get you the data you need. Not sure how you tried using $.each but it should be in your success function on your ajax call. Also make sure the datatype is set to json.

success: function(data){
  $(data).each(function(idx,val){
     alert(val.code + " " + val.name);
  })
}

Upvotes: 0

deadrunk
deadrunk

Reputation: 14155

<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
  var item = data[i];
  alert(item["code"] + " / " + item["name"]);
}
<script>

Upvotes: 0

Related Questions