0

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.

3
  • Can you also post your javascript? Commented Mar 26, 2012 at 13:05
  • what is the structure of your JSON? how it gets to javascript is not really relevant. Commented Mar 26, 2012 at 13:05
  • 1
    nit-picky: it's json-encoded, not encrypted. Commented Mar 26, 2012 at 13:07

3 Answers 3

3

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.

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

1 Comment

i would suggest using var c instead of c to avoid creating a global.
0
<script>
var data = <?= json_encode($info); ?>;
for (var i = 0; i < data.length; i++) {
  var item = data[i];
  alert(item["code"] + " / " + item["name"]);
}
<script>

1 Comment

This is the structure of the javascript
0

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);
  })
}

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.