Decode json and display in table - php

I have a HotUKDeals API which when using the URL bellow gives me some JSON.
Im trying to use PHP to display it in a table but if i try and use a loop to go through the JSON i get errors.
If i try and decode i get "Object of class stdClass could not be converted to string"
So far I have this which i no gets the json and stores it in the variable .
I also have some JS which will go through JSON and put it in a table , but im having difficulties getting the JSON in the php variable into the JS.
Needed to remove code for work reasons !

To get the JSON into your jQuery code you'll have to use AJAX:
PHP file -
<?php
$tester = file_get_contents('http://api.hotukdeals.com/rest_api/v2/?key=d2c088ea340558b3b3517396963a341c&results_per_page=2&output=json');
echo $tester;
?>
jQuery AJAX -
$.get( "hotukdeals.php", function( data ) {
// now you can work with `data`
var JSON = jQuery.parseJSON( data ); // it will be an object
$.each(JSON.deals.items, function( index, value ) {
console.log( value.title + ' ' + value.description );
});
});
NOTE: The JSON that is returned has complex construction, so you will have to take care about how you extract during the loop and then place in the table.

Related

Get data array from PHP to JavaScript

I want to get data array from php to Javascript. (Actually I am doing plotting using javascript library and the data is in the database: I get the data using php script and want to use that data for plotting). I have tried to use a JSON for this. My code looks follows but it is not working. Please give me a help on this
<script type="text/javascript">
<?php
$php_arr=array('abc','def'); // I want to transport this array to javascript
echo "display_diagram(" . json_encode($php_arr) . ")";
?>
function display_diagram(data) {
obj = JSON.parse(data); // this is not working for me
Try use data variable in display_diagram function without JSON.parse.
You now give data attribute in json format and this not require additional json parsing.
Check this:
<script>
<?php
$php_arr=array('abc','def'); // I want to transport this array to javascript
echo "display_diagram(" . json_encode($php_arr) . ")";
?>
function display_diagram(data){
obj = data;
alert(obj);
}
</script>

Passing array through AJAX from php to javascript

I need to get an array generated from a script php. I have Latitude and Longitude for each user in a database.
I take the values from the db with this code (file.php):
$query = "SELECT Latitude, Longitude FROM USERS";
$result=mysql_query($query);
$array=array();
while ($data = mysql_fetch_array($result)) {
$array[]=$data['Latitude'];
$array[]=$data['Longitude'];
}
echo $array;
and I call with ajax with this code:
$.post('./file.php',
function( result ){
alert(result);
});
but even if in the script php the array is correct (if I echo array[25] I obtain the right value) in Javascript I obtain "Undefined".
How can I get the array in correct way??
thanks!
edit: after encoded with json_encode($array); in php and JSON.parse(result) in javascript seems not working.
In the console I have the array, but I can't access to its values. (Array[0] gave me "undefined").
use this
echo json_encode($array);
on server side
and
var arr=JSON.parse(result);
on client side
As Ruslan Polutsygan mentioned, you cen use
echo json_encode($array);
on the PHP Side.
On the Javascript-Side you can simply add the DataType to the $.post()-Function:
$.post(
'./file.php',
function( result ){
console.log(result);
},
'json'
);
and the result-Parameter is the parsed JSON-Data.
You can also set the correct Content-Type in your PHP Script. Then jQuery should automaticly parse the JSON Data returned from your PHP Script:
header('Content-type: application/json');
See
http://api.jquery.com/jQuery.post/
http://de3.php.net/json_encode
You need to convert the php array to json, try:
echo json_encode($array);
jQuery should be able to see it's json being returned and create a javascript object out of it automatically.
$.post('./file.php', function(result)
{
$.each(result, function()
{
console.log(this.Latitude + ":" + this.Longitude);
});
});

json_encode creating malformed JSON data?

I have a codeigniter application returns some data from my database to a view. I'm trying to send it back as json data.
The problem is that the data that is returned it malformed.
it looks like this:
({'2.5':"Admin1", '2.10':"Admin2"})
When I test this on jsonlint.com, it shows that this is not valid json.
the '2.5' should be in double quotes, not single quotes.
What I don't understand is that I'm calling json_encode on my data before I pass it to the view. My code in my controller looks like this:
public function getbuildings()
{
$buildings = array();
$branchID = $this->uri->segment(3);
$buildingforbranch = array();
$_locations = $this->racktables_model->get_locations();
//print_r($_locations);
foreach ($_locations as $location)
{
if ((isset($location['L2FullID'])) && (!array_key_exists($location['L2FullID'],$buildings))) {
$buildings[$location['L2FullID']] = $location['L2Location'];
}
}
foreach ($buildings as $key => $value)
{
$pattern = "/(".$branchID."\.\d)/i";
if (preg_match($pattern,$key))
{
$buildingforbranch[(string)$key] = $value;
}
}
header ('Content-Type: application/json; charset=UTF-8');
echo json_encode($buildingforbranch);
}
As you can see from the code, I've even tried casting $key explicitly to a string data type. But that doesn't seem to change anything. Any suggestions?
Thanks.
EDIT 1
When I do a var dump on $buildingforbranch right before the header / json_encode() calls, I get the following results:
array(3) {
["2.5"]=>
string(7) "Admin 2"
["2.10"]=>
string(7) "Admin 1"
["2.11"]=>
string(3) "SB4"
}
It looks good here ... but when I do a console.log() and pass in the data from the controller, the browser shows the incorrectly formed json data.
EDIT 2
Here's what i'm trying to accomplish. I need to dynamically create a combo box when a user clicks on a control on my page. If the ajax call results in an empty array, I don't want to display the combo. Otherwise, I try to populate the combo box with the results of the ajax call. Everything is working, except for the part where I'm attempting to check the length of the json data. My app always displays a combo box regardless of what is sent back.
Here's the code:
$.ajax({
url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
type:'GET',
dataType:'json',
success: function(returnDataFromController) {
console.log("getbuildings ajax call successfull");
var htmlstring;
htmlstring="<select name='L2Locations' id='L2Locations'>";
htmlstring = htmlstring + "<option value='all'>All</option>";
//console.log(returnDataFromController);
var JSONdata=[returnDataFromController];
console.log(JSONdata);
if (JSONdata.length != 0)
{
for(var i=0;i<JSONdata.length;i++){
var obj = JSONdata[i];
for(var key in obj){
var locationkey = key;
var locationname = obj[key];
htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
} //end inner for
$('#l2locations').html(htmlstring);
}//end outer for
}
else {
//alert('i think undefined');
$('#l2locations').html('');
}
}//success
});//end ajax
If I call the page that is returning the json data directly, i get [] as the result for an empty array.
[] is actually defines an array with a single element in your particular case. But as I see you are using jQuery ajax with dataType: "json", this means that the returned value is already an object, you don't need to parse it one more time, so just remove []:
var JSONdata=returnDataFromController; // instead of var JSONdata=[returnDataFromController];
As stated in your other question, you need to handle the JSON as JSON.
Basic overview is:
returnDataFromController will be a string, use JSON.parse() or jQuery's parseJson() to convert it to a JSON object
Rewrite your loop that generates the options to iterate over a JSON object, instead of an array. Note that jquery.each() can handle both arrays and objects will handle This appears to be the part that you're missing . . .
The real key here is keeping datatypes straight. You're getting a string back, that contains JSON data. There's no easy way to convert that to an array, so read it in as JSON. Since it's now a JSON object, you have to treat it as a JSON object, not an array.
Check the jQuery Utilities category for other JSON related items.
Use firebug on firefox to see what is shown in "response" tab on "net" tab
This code
<?php
echo json_encode(array(
"2.5" => "Admin 2",
"2.10" => "Admin 1",
"2.11" => "SB4"
));
produces this output {"2.5":"Admin 2","2.10":"Admin 1","2.11":"SB4"} on my server (php5.3) and on this fiddle example
http://www.phpfiddle.org/main/code/xqy-ize

Getting JSON data from Javascript

I am currently working on a php/javascript project which retrieves information from a database and json encodes the data. It is supposed to show the values from the database inside a combo box on the web page.
In the PHP script that encodes the mysql data I have the following code:
$query = "SELECT pla_platformName as `platform` FROM platforms";
$result = mysql_query($query);
if ($result)
{
while ($myrow = mysql_fetch_array($result))
{
$output[] = $myrow;
}
print json_encode($output);
die();
}
In the javascript code I have the following:
<script>
$(document).ready(function()
{
getPlatforms();
function getPlatforms()
{
$.post("phpHandler/get-platforms.php", function(json)
{
alert(json);
alert(json.platform);
}
);
}
});
</script>
I have alert(json); which shows the entire json data which looks like the following:
[{"0":"hello","platform":"hello"},{"0":"android","platform":"world"}]
The next alert(json.platform) I am expecting it to show either hello or world or both but on this line it keeps on saying undefined. Why isn't this working and how do I get a specific platform, i.e. either hello, or world.
Thanks for any help you can provide.
You need to first convert your JSON string into an object
var data = $.parseJSON(json);
In this case, the object returned is an array. Try
alert(data[0].platform);
You can skip the first step if you set the dataType option to json in your ajax call.
$.post("phpHandler/get-platforms.php", function(data) {
alert(data[0].platform);
},
'json'
);
See jQuery.post() documentation
Your platform member is defined on each item, you'll have to specify which array item you want the platform for. This should do the trick:
alert(json[0].platform);
I'm assuming that your json parameter actually holds a javascript object, and not simply a string. If it is a string, you should define contentType 'application/json' on your php page. (I'm not sure how you do that in php since I do .NET for server side myself.)
To test it quickly however, you can do a $.parseJSON(json) to get the object.

PHP to JSON on client side

I'm using Rob Monies 'Jquery Week Calendar' to build a calendar application.
I have a MSSQL DB a with table named 'dates' and the following fields:
id
start
end
title
I would like to query this DB in PHP and then pass the results to Javascript, Javascript will then render the events in the browser.
The Javascript needs to receive the event details in JSON format as per the following example:
{"id":1,"start": 2010-10-09T13:00:00,"end":2010-10-09T14:00:00,"title":"Lunch with Mike"},
{"id":2,"start": 2010-10-10T13:00:00,"end": 2010-10-10T14:00:00, "title":"Dev Meeting"}
So far, to keep things simple I've just returned one row from the DB at a time, however - I will need the application to be able to render multiple events, as stored in the database.
I've tried using json_encode() to put the values into a var and pass them to a Javascript var called DB_events - if I return the DB_events in an alert box on the client side I see the following;
{"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"}
which looks ok, but when I do this in my code:
events : [DB_events]
It doesn't work :(
If I take PHP out of the equation, and just do the following on the client side:
var DB_events = {"id":1, "start":2010-10-09T13:00:00, "end":2010-10-09T14:00:00,"title":"Lunch with Mike"};
and return DB_events in an alert box, I get:
[object] [Object]
But when I do this:
events : [DB_events]
it works!
Back to PHP …
If I put the SQL result into PHP vars as follows:
$id = id;
$start = start;
$end = end;
$title = title;
and pass those vars to the following JS vars:
JS_id
JS_start
JS_end
JS_title
and do this on the client side:
var DB_events = {"id":JS_id, "start":JS_start, "end":JS_end,"title":JS_title};
events : [DB_events]
that also works.
As you can probably tell - I'm new to this and probably missing something very basic.
Any help, advice or information would be very much appreciated :)
Many Thanks
Tim
when you get a string representation of your object it means that you've exported it as a string not as an object.
when you get [object] [Object] it means that it is now an object, which is right!
You can do this with JSONP if you get JSON from an URL:
// send the request via <script> tag
var src = "..."; // url of the JSON output
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.setAttribute("type", "text/javascript");
script.setAttribute("src", src);
head.appendChild(script);
Or parse it as a string with JSON parser:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
var DB_events = JSON.parse( ...JSON output as a string... );
Or by directly passing it from PHP with an inline <script> block in your page:
echo "<script>";
echo "var DB_events = " . json_encode( ... ) . ";";
echo "</script>";
​
Did you use jsocn decode
http://php.net/manual/en/function.json-decode.php
You can split the result and make it differenct variables like start ,end , events etc
http://php.net/manual/en/function.explode.php

Categories