I'm creating a simple d3 chart which is linked to data from a MySQL server (with PHP handling those queries). I've formatted the data in PHP to be JSON compliant, and finally used the PHP function json_encode to pass the data to javascript. Below, I've included the important lines of code:
1) The packer array is created in JSON format and is d3-friendly too.
$packer[] = array('key' => $subject, 'values' => $array);
//where $subject is a string and $array is (you guessed it) an array of data
2) In the d3 chart constructor, data is initialized as an array, in JSON format
var data = <?=json_encode($packer)?>;
//here, I echo the php array to javascript in JSON format
When I load the page, the chart appears, but no data is loaded. I therefore know this problem lies in the loading of the data. I'd appreciate any help!
EDIT: I found the answer! It was a problem with my JSON data using arrays but d3 required an object formatted slightly differently. Link for those curious:
https://stackoverflow.com/questions/19500742/plotting-json-data-using-nvd3
$temp['values'][$i]['x']= $i;
$temp['values'][$i]['y']= intval($row['temperature']);
Related
I have an array, myData=[[1,2,3],[4,5,6],....,[..,..,..]]
I want to post this to the server.
Usually, for a JS variable, I just put the variable into a textbox and then submit the form using JS. However, when I put the 2D array into a textbox, JS converts it to a string, such that it becomes a 1D array, which looks like:
[1,2,3,4,5,6....]
I want to be able to post the entire 2D array to the server and retrieve it on the next page using PHP. How do I do that?
Thanks!
You should use JSON to turn the array into a string with javascript and then parse the string back into an array in php.
for example:
var myData = var data = [['hooray',1],['test','meow'],[0,3,2]];
var myData_string = JSON.stringify(myData);
This will turn your object/array into a string which you can then POST and parse with php like so:
$myData = json_decode($input);
References:
JSON (javascript)
json_decode() (php)
Using http://objectmix.com/javascript/389546-reading-json-object-jquery.html as a starting point, I have been reading lots about JSON. Unfortunately I am a total beginner and can't get my head around the basics of creating JSON objects.
I have created a PHP page called getContact.php
<?php
"Contact": {
"ID" : "1",
"Name" : "Brett Samuel"
}
?>
And a javascript file with the following code:
$.getJSON('getContacts.php', function(data) {
var obj = (new Function("return " + data))();
alert(data.Contact.Name)
});
This page http://msdn.microsoft.com/en-us/library/bb299886.aspx suggests I have the basic approach correct. Can anyone tell me why this does not work? Absolutely nothing happens.
Thanks in advance.
Your PHP file contains JSON, which is not valid PHP, and will therefore error.
If you're working with PHP the easiest way to build JSON is to first prepare your data as an array (associative or indexed, as required) then simply convert it via json_encode(). (You can also decode JSON, with the corresponding json_decode().
[EDIT - in response to comment, just have a look at the PHP docs for json_encode() - it's very self explanatory. You take an array, pass it to json_encode(), and you get a JSON string.
$arr = array('one', 'two', 'three');
echo json_encode($arr); //JSON string
JSON is not a programming language, and it's certainly not executable as PHP. It's just a file format. If you want your web server to serve up a static JSON file, just drop it in the file system as filename.json, without any <?php tags. (Of course, as with HTML, you can also make it a .php file and just not have any PHP in it, other than something to set the Content-Type since the file suffix won't do it automatically. But that's wasteful.)
If you want to dynamically generate some JSON with PHP, then you have to write PHP code to print it out, e.g.:
<?= json_encode( array(
'Contact' => array('ID' => 1, 'Name' => 'Brett Samuel' )
) ); ?>
Also, note that a JSON document has to be a complete object; yours requires another set of curly braces around the whole thing (as output by the above snippet).
you need to use json_encode and json_decode
refer this json php manual
I have a problem with the json functionality in zend and js.
I try to encode a single array containing some number of models like this:
echo json_encode(Application_Model_Marker::getMarkers());
var mark = JSON.parse(jsonVal); //in js
where getMarkers is a static method that returns an array of marker models.
This works fine and when I parse it in the js script and try accessing the values of the json object it works fine.
If however I try to create and send an array of array like this:
$allData = array();
$allData['info'] = Application_Model_Marker::getMarkers();
$allData['openingHours'] = Application_Model_Openinghours::getOpeningHours();
$allData['happyHours'] = Application_Model_Happyhour::getHappyHours();
echo json_encode($allData);
It still sends all the correct information when I try to alert(jsonVal.responseText); in js.
It has three arrays each containg some arrays of objects.
However when I try to initialize a variable to the parsed json object like in the first example, I can't access the values and it seems some kind of error occurs as the program stops when I try it.
I don't quite get it as it has all the correct info when i just try to print the response text from the encoded json object.
Any ideas how to do this multidimensional json encoding?
Try this, Hopefully it'll work :
<sctript>
var mark;
eval("mark = "+jsonVal+";");
</sctrip>
Trying to figure out a way to get ActionScript to print out a php object. In PHP, I can just do print_r, and I'm able to successfully get the object into Flash, but now can't figure out how to print out the object using ActionScript 3?
Well, when the request first comes over, there is always URLLoader.data, which is data in its raw form. If you're looking to get the data from a JSON-style object, there is for( var i:String in obj ). If you're looking for things more obscure than that, there is the ability to use describeType. My favorite example of the last one is in the JSONEncoder class.
From PHP, you can encode most objects to JSON using json_encode() (PHP5+). Using the AS3 JSON decoder from as3corelib you can then convert that encoded string into an oject that AS3 con read. After that you can iterate over the object as key/value pairs and output it however you wish.
I think I know what you mean, I had the same need, so I made this
http://www.actionscript.org/forums/showthread.php3?t=266979
scroll to the bottom, there is a description and an .AS file called trace_r that I wrote
Looking for a way to setup a server-side datatable using PHP to parse XML json?
Okay, I'm getting the data from wufoo and so I am also able to pull json. How can I get started with the following data?
{"Entries":[{"EntryId":"33","Field71":"","Field41":"John","Field42":"Smith","Field55":"","Field34":"2004","Field375":"Arts, Design, Entertainment, Sports and Media","Field378":"Select One","Field4":"Kayak Outfitter","Field3":"Kayak Tours, Inc","Field7":"123 Main Street","Field8":"","Field9":"New York","Field10":"New York","Field11":"54209","Field12":"United States","Field19":"(555)555-5555","Field23":"contact#email.com","Field46":"http:\/\/www.website.com","Field21":"","Field49":"","Field6":"May>September","Field65":"","Field69":"","Field25":"","Field37":"Its all about Self-Motivation.","Field30":"Yes","Field31":"Yes","Field172":"","Field39":"","DateCreated":"2009-01-30 05:46:02","CreatedBy":"public","DateUpdated":"2010-08-08 22:23:30","UpdatedBy":"User"}]}
As Charles suggests DataTables will currently only accept a JSON input with a specific format. The reason for this is that supporting abstract formats would add a lot of overhead to both the internals and the initialisation (i.e. you'd need to tell it that you want it to use //articles/book#author or whatever).
So one option is to use fnServerData ( http://datatables.net/usage/callbacks#fnServerData ) to make your own Ajax call and get the XML - than transform it into the JSON format that DataTables needs with a simple loop.
Allan
Thanks for the sample data.
You're going to need to convert the data slightly.
DataTables can take a Javascript data structure (JSON), but it has to be an array of arrays.
Your sample data has a root element called Entries, which contains an array. That's great. Unfortunately each element in that array is currently a hash -- a key/value pair.
You need only the values from that pair, not the keys.
This Javascript will convert your Entries array-of-hashes into a plain old array-of-arrays. I'm using the Javascript 1.6 for each ... in syntax here because I had a brainfart and didn't remember that we're talking about a jQuery plugin here, and wrote it without that dependency.
var entries = /* JSON as provided in question */;
var new_array = new Array();
var el = entries['Entries'].length;
for(i = 0; i < el; i++) {
var inner_array = new Array();
for each (var value in entries['Entries'][i]) {
inner_array[ inner_array.length ] = value;
}
new_array[ new_array.length ] = inner_array;
}
You can then pass new_array into the initial options hash's aaData option, as documented in the link I provided above. You will need to work out how to present the column headings yourself, given that you seem to have fallen into the anti-pattern of useless key names.