简体   繁体   中英

jQuery parse/display json data from php json_encode

Initial .ajax call in jquery:

$.ajax({                                      
 type: 'post',
 url: 'items_data.php',                  
 data: "id="+id,                                       
 dataType: 'json',                     
 success: function(data){     
  if(data){
   make_item_rows(data);
  }else{
   alert("oops nothing happened :(");
  }        
 } 
});     

Sends a simple string to a php file which looks like:

header('Content-type: application/json');
require_once('db.php');

if( isset($_POST['id'])){
 $id = $_POST['id'];
}else{
 echo "Danger Will Robinson Danger!";
}

$items_data = $pdo_db->query ("SELECT blah blah blah with $id...");
$result_array = $items_data->fetchAll();
echo json_encode($result_array);

I am catching the $result_array just fine and passing it on to another function. I double checked that there is indeed proper values being returned as I can just echo result to my page and it displays something like the following:

[{"item_id":"230","0":"230","other_id":"700"},{"item_id":"231","0":"231","other_id":"701"},{"item_id":"232","0":"232","other_id":"702"}]

I am having trouble figuring out how to iterate through the results so I can inject values into a table I have in my HTML. Here is what I have for my function:

function make_item_rows(result_array){  
 var string_buffer = "";
 $.each(jQuery.parseJSON(result_array), function(index, value){
  string_buffer += value.item_id; //adding many more eventually
  $(string_buffer).appendTo('#items_container');
  string_buffer = ""; //reset buffer after writing          
 });                    
}

I also tried putting an alert in the $.each function to make sure it was firing 3 times, which it was. However no data comes out of my code. Have tried some other methods as well with no luck.

UPDATE: I changed my code to include the parseJSON, no dice. Got an unexpected token error in my jquery file (right when it attempts to use native json parser). Tried adding the json header to no avail, same error. jquery version 1.9.1. Code as it is now should be reflected above.

Set the dataType:"JSON" and callback in your ajax call.

For example:

$.ajax({
    url: "yourphp.php?id="+yourid,
    dataType: "JSON",
    success: function(json){
        //here inside json variable you've the json returned by your PHP
        for(var i=0;i<json.length;i++){
            $('#items_container').append(json[i].item_id)
        }
    }
})

Please also consider in your PHP set the JSON content-type. header('Content-type: application/json');

You need to parse it with jQuery.parseJSON

function make_item_rows(result_array){  
 var string_buffer = "";
 $.each(jQuery.parseJSON(result_array), function(index, value){
  string_buffer = value.item_id;
  $(string_buffer).appendTo('#items_container');
 });                    
}
function make_item_rows(result_array){  
    var string_buffer = "";
    var parsed_array=JSON.parse(result_array);
    $.each(parsed_array, function(){
       string_buffer += parsed_array.item_id;
       $(string_buffer).appendTo('#items_container');
       string_buffer = "";           
    });                    
}

Try this.

function make_item_rows(result_array){  
 var string_buffer = "";
 $.each(result_array, function(index, value){
  value = jQuery.parseJSON(value);
  string_buffer += value.item_id;
  $(string_buffer).appendTo('#items_container');
  string_buffer = "";           
 });                    
}

Assuming you already parsed the json response and you have the array. I think the problem is you need to pass a callback to $.each that takes and index and an element param

function make_item_rows(result_array){  
    $.each(result_array, function(index, element){
        document.getElementById("a").innerHTML+=element.item_id;
    });                    
}

(Slightly modified) DEMO

for starters within the $.each you need to access the properties of the instance of object contained within result_array , not result_array itself.

var string_buffer = "";
 $.each(result_array, function(index, object){
     /* instance is "object"*/
     alert( object.item_id);
});

Not entirely sure what you are expecting from this line: $(string_buffer).appendTo('#items_container');

$(string_buffer) does not create a valid jQuery selector since nothing within string_buffer has a prefix for class, tagname or ID, and values from json don't either

If just want the string value of the item_id appended :

$('#items_container').append(  object.item_id+'<br/>');

If you are receiving this using jQuery AJAX methods you don't need to use $.parseJSON as other answers suggest, it will already be done for you internally provided you are setting correct dataType for AJAX

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM