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');
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 = "";
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With