0

I am a little stuck on how to retrieve all the values from the json array in jquery. I know it needs to be looped but how ? The function - at the moment is:

$.ajax({                                      
    url: 'query.php',                     
    data: "",                       
    dataType: 'json',                   
    success: ajaxfunction
   }); 

function ajaxfunction(json_data){
// problem is below, i need to output all the data from the array         
    console.log (json_data)
    while(json_data){
    $('#maindisplay').html("<b>Product: </b>"+json_data.prod_name+"<b> colour: </b>"+json_data.colour); // problem is here, i need to output all the data from the array
    }
  } 

The php:

$result = mysql_query("SELECT * FROM fproduct WHERE fproduct.category='Shirts'");
$elements = array ();
do{
   $row=mysql_fetch_array($result); 
    if ($row)    //if there is anything
              $elements[] = ($row); 

} while($row);
echo json_encode($elements);

1 Answer 1

2

You have to iterate over the elements of the array.

function ajaxfunction(json_data){
    for (var i = 0; i < json_data.length; i++){
        $('#maindisplay').append($("<b>Product: </b>"+json_data[i].prod_name+"<b> colour: </b>"+json_data[i].colour+"<br>"));
    }
} 
5
  • Changed it to use append instead of html. A table would probably be a better way to present it, though. Commented Apr 4, 2013 at 1:21
  • Should be for(var i = 0.... Commented Apr 4, 2013 at 1:22
  • I think you should parse your JSON data before the loop: var data = jQuery.parseJSON(json_data); Commented Apr 4, 2013 at 1:27
  • @juanchopx2 That's done automatically by jQuery when you specify dataType: 'json' in the $.ajax() call. Commented Apr 4, 2013 at 1:28
  • thanks, just wanted to see if it outputs, i was going to style it with tables. Commented Apr 4, 2013 at 1:34

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.