Cross Cross - 2 months ago 6
PHP Question

What is the proper way in getting data from a json file?

What is the proper way in getting a data from my json file? the result is always undefined

Item name: undefined
Item key: undefined

.json file

[{"item_id":"1","item_name":"Book","item_key":"290Q12"}]


my script, jquery

var item_name;
var item_key;
var item_id = '<?php echo $row->item_id; ?>';
var get_loc = '<?php echo base_url();?>index.php/main/get_one_item_info/';

item();
function item() {
$(document).ready(function () {
$.ajax({
type: 'GET',
url: get_loc + item_id,
data: { get_param: 'value' },
success: function (data) {
for (var i=0;i<data.length;++i)
{
item_name = data[0].item_name;
item_key = data[0].item_key;
document.getElementById("items").innerHTML = "Item name: " + item_name + "<br>Item key: " + item_key + " ";
}
}
});
});
setTimeout(item, 2500);
};


index.php

<div id='items'></div>

Answer

You can also try this

    $url = 'your url';
    $obj = json_decode(file_get_contents($url), true);
    $item_name = $obj['item_name'];
    $item_key = $obj['item_key'];
   // print_r($obj);
Comments