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.
Related
========== EDIT: ==========
Based on the below question, and below answer to use JSON. I'm rephrasing the question.
How can I take data from boto dynamo and jsonify it?
Right now I have something like this:
adv = #my advertiser
ads = self.swfTable.scan(advertiser__eq = adv)
arr=[]
for a in ads:
arr.append(a)
str = []
for i in arr:
str += [json.dumps(fields) for fields in i]
if str is not []:
json.dumps([ str.to_json() for ad in str ])
How do I turn this into a nice JSON dump or otherwise send it to my php?
========== Original Question: ==========
Forgive me I'm new to PHP.
So I have a stringified array of objects.
Ex:
Array [{cat,bat},{mat,hat}] -> ["cat","bat","mat","hat"] (let's call this aList below)
If I know each object pair will have a length of two. Is the only way to reform this Array by parsing the string? Is there any clever PHP way to do this?
I'm trying to move data from python to PHP in this case and sending a printed array seemed like the best / most universal way for me to write the api connection.
Here is my solution in pseudocode:
aList = file_get_contents(myUrl)
splitList = aList.split(",") # is there anyway to exclude "," from being also noticed? ex "app,le","blueberry" should only split 1x?
objects=[]
newObject{}
for int i =0;i<splitList.len; i++
if i%2
newObject.append(splitList[i])
objects.append(newObject)
newObject = {}
else:
newObject.append{list[i]}
Is there are way to do this in fewer lines / more efficiently? Also as mentioned above: is there anyway to exclude "," from being also noticed? ex "app,le","blueberry" should only split 1x?
You really should consider cross-language serialization, like JSON or MessagePack. As an example, see docs for PHP's json_decode and Python's json.
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']);
So I am using FLOT to generate some bar graphs and it uses some javascript arrays to allow for the data. I have a query that spits out the correct labels and values as so:
while ($row = mysql_fetch_array($chart_stats)){
printf("Race is: %s Percentage: %s", $row['Race'],$row['Percentage'] ."<br/>");
}
My question is can I get the values of my array from php into the array of Javascript (if that makes sense)
var d1 =[0, 72]; //instead of static value maybe var d1 = [0,<?printf($row['Percentage'])?>];
var d2 =[1,3];
var d3 = [2,40];
Thanks in advance!
Yes, you can echo stuff from PHP wherever you like. When putting it into a block of JavaScript, though, you have to be careful that:
The resulting output is ALWAYS valid code
There is no way for user-generated input to be placed into code and run
The second one is simple: never put anything you got from $_POST into a <script> tag.
As for the first, json_encode is a big help. With it, you can output almost any kind of PHP variable as a valid JavaScript one.
I have a list in javascript that is to be changed by the content of a database when the user clicks a link or slides a bar. I currently use a xmlhttp request to fetch a php page which generates the list.
I have a static list working in this form:
var mark_list = [
{ "EntID" : 3, "x" : 100, "y" : 400},
];
I tried to have the php page generate the { "EntID" : 3, "x" : 100, "y" : 400} and set mark_list equal to responseText but I believe that's just a string. I'm struggling to find a way to get this new list into the variablie.
Does anyone have any suggestions or solutions? Your help would be greatly appreciated.
Kallum
Make sure the browser has a JSON object by including the json script from here: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
It will defer to the native browser JSON object if available, and if not, will add it so that this functionality is available in browsers that don't currently support it.
Then in your code, after you receive the output from the PHP script, run this:
var mark_list = JSON.parse(responseText);
Based on the output from the PHP script, you may need to do this:
var stuff = JSON.parse(responseText);
var mark_list = [stuff];
This will convert the JSON string the PHP returns into an actual javascript object.
In your PHP code you can do something like this:
$output = array(
array(
'EntId' => 3,
'x' => 100,
'y' => 400,
),
);
echo json_encode($output);
Then you can use the var mark_list = JSON.parse(responseText); option in your JavaScript.
responseText will indeed just be a text represented by a string, so the way you are outputting it right now won't just do the trick all on its own. There are basically two ways you can do this:
In your javascript, you parse the output the server is giving you. This can be done onn a pure string in whatever way you feel like doing it. For example, you could write javascript to parse the format you gave with curly braces and a colon based syntax. Alternatively, you could use another format (like XML) which will reduce the work a little, but will still leave the interpreting of the output for you to do in the javascript.
You can output to a format used to describe objects and lists. JSON would be the big example of such a format. If you output in JSON, you will get something that resembles the format you used above (JSON stands for Javascript Object Notation and is based on parts of the syntax of javascript) and all you will have to do to be able to use it is to get to the data you want to get to. You can use JSON.parse() for this on most browsers, but an alternative with more widespread support is jQuery's jQuery.parseJSON() (for which you would use jQuery, which you should also provide in that case)
Due to the limitations of the deign of a current system, I need to pass data to a select element as json, reset each option in the select object with the 'id' value from the json and populate a second select element with 'sid' data from the json to create a dynamic parent-child pair of select elements.
However I seem to be unable to successfully parse the option value and push it into an array for use in later code.
<select id="Sector">
<option value="{'id':'Fruit','sid':['Apple','Orange']}"></option>
<option value="{'id':'Veg','sid':['Tomato','Carrot']}"></option>
</select>
<script language="JavaScript" type="text/javascript">
var plist = document.getElementById('Sector');
var opts = plist.options;
var x =[];
for(i=0;i<opts.length;i++){
x.push(opts[i].value);
}
alert(x[0]['id']);
</script>
What am I doing wrong ??i
The option values are strings. If you want to treat them as JavaScript objects, you have to run them through a JSON parser.
You will then run into another problem as the option values are not JSON. Use JSON Lint to find your errors (I can't see any aside from you using a ' every place you should be using a "). If you are dealing with JSON, you should almost always be building a data structure in a programming language and then running it through a JSON serializer, handcrafting JSON is asking for trouble.
this line is an issue
x.push(opts[0]);
first off, I think you need to do opts[0].value, then I think you need to use eval or JSON.parse to turn it into an object.