Query datatable from rest api without pre-defining the table in html - javascript

I would like to query a JSON via post request from a rest API:
http://localhost/post1
param1='1'
that returns the following:
{
"json_table": [
{
"date": 123,
"test": "hello2"
},
{
"date": 19,
"test": "hello"
},
}
and it should then be automatcially populated into a jquery datatable, a little bit how it is described here:
$('#myTable').DataTable( {
ajax: '/api/myData'
} );
What I don't understand is:
How can I tell it to make a post request with a parameter
How can I create the table without having to predefine it in HTML, so that it's completely agnostic what is returned from the JSON and just displays the table accordingly, whatever is within the 'json_table' record (which is generated from a pandas data frame df.to_json(orient='records')?
How can I make it refresh (query again) every 15 seconds and update the table?
Any suggestions are appreciated.

To make the post request with parameters , U can do is:
$.ajax({
type: 'POST',
dataType: "json", #define the response type as Json
url: url,
data: data, # make a post request with a parameter you want
success: success
});
U can create table with json data like this :
<script type="text/javascript">
var myContacts = [{ "name": "Parvez Ansari", "email": "ansariparvez#gmai.com", "mobile":"9998979695" },
{ "name": "Tayyeb Shaikh", "email": "tshaikh1981#gmai.com", "mobile":"9091929394" },
{ "name": "Ashfaque Shaikh", "email": "ashly786#gmai.com",
"mobile":"8081828384" }
];
function generateDynamicTable(){
var noOfContacts = myContacts.length;
if(noOfContacts>0){
// CREATE DYNAMIC TABLE.
var table = document.createElement("table");
table.style.width = '50%';
table.setAttribute('border', '1');
table.setAttribute('cellspacing', '0');
table.setAttribute('cellpadding', '5');
// retrieve column header ('Name', 'Email', and 'Mobile')
var col = []; // define an empty array
for (var i = 0; i < noOfContacts; i++) {
for (var key in myContacts[i]) {
if (col.indexOf(key) === -1) {
col.push(key);
}
}
}
// CREATE TABLE HEAD .
var tHead = document.createElement("thead");
// CREATE ROW FOR TABLE HEAD .
var hRow = document.createElement("tr");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < col.length; i++) {
var th = document.createElement("th");
th.innerHTML = col[i];
hRow.appendChild(th);
}
tHead.appendChild(hRow);
table.appendChild(tHead);
// CREATE TABLE BODY .
var tBody = document.createElement("tbody");
// ADD COLUMN HEADER TO ROW OF TABLE HEAD.
for (var i = 0; i < noOfContacts; i++) {
var bRow = document.createElement("tr"); // CREATE ROW FOR EACH RECORD .
for (var j = 0; j < col.length; j++) {
var td = document.createElement("td");
td.innerHTML = myContacts[i][col[j]];
bRow.appendChild(td);
}
tBody.appendChild(bRow)
}
table.appendChild(tBody);
// FINALLY ADD THE NEWLY CREATED TABLE WITH JSON DATA TO A CONTAINER.
var divContainer = document.getElementById("myContacts");
divContainer.innerHTML = "";
divContainer.appendChild(table);
}
}
</script>
U can refer this code for refreshing in every 15 mins :
Check this Ans

Creating a dynamic DataTable from arbitrary JSON is certainly possible - but it can get complicated depending on how many of the features of DataTables you are trying to use.
Also, if you have control over the JSON being sent from the server, you can make things easier for yourself. I will assume you do have such control for what follows.
Static Example
Assume we start with this simple static example:
The server sends this JSON data:
{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architext",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421",
"toggle": "off"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "1278",
"toggle": "on"
}
]
}
And we have a simple DataTables definition like this:
<body>
<div style="margin: 20px;">
<table id="example" class="display" style="width:100%"></table>
</div>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": {
"url": "http://localhost:7000/employees",
"dataSrc": "data",
"type": "GET",
},
"columns": [
{ "data": "name",
"title": "Name" },
{ "data": "position",
"title": "Position" },
{ "data": "office",
"title": "Office" },
{ "data": "extn",
"title": "Extn." },
{ "data": "start_date",
"title": "Start Date" },
{ "data": "salary",
"title": "Salary" },
]
} );
} );
</script>
</body>
Enhancing the JSON
To make things easier for ourselves, we can enhance the JSON being sent from the server, to contain metadata about the columns in the data records:
{
"response": [
{
"columns": [
{
"data": "name",
"title": "Name"
},
{
"data": "position",
"title": "Position"
},
{
"data": "office",
"title": "Office"
},
{
"data": "extn",
"title": "Extn."
},
{
"data": "start_date",
"title": "Start Date"
},
{
"data": "salary",
"title": "Salary"
}
]
},
{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architext",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421",
"toggle": "off"
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "1278",
"toggle": "on"
}
]
}
]
}
This new columns section in the JSON is basically the same information as was hard-coded into the first DataTables definition.
We can read that into a variable, when we receive the JSON from the server, and then use this variable in our DataTables configuration.
And we can do the same thing for the data records also:
var tableData = [];
var tableColumns = [];
...
$('#example').DataTable( {
"data": tableData,
"columns": tableColumns
} );
For more flexibility, the ajax request can be separated out from DataTables:
<script type="text/javascript">
var tableData = [];
var tableColumns = [];
function ajax1() {
return $.ajax({
url: "http://localhost:7000/employees",
success : handleData,
type: "POST",
data: { "foo": "bar" }
});
}
function handleData(data) {
tableData = data.response[1].data;
//console.log(JSON.stringify(tableData));
tableColumns = data.response[0].columns;
}
$(document).ready(function() {
$.when(ajax1()).done(function(a1){
$('#example').DataTable( {
"data": tableData,
"columns": tableColumns
} );
});
} );
</script>
The easiest way to assemble what you need is (I think) to write the hard-coded version of your data table - and then to start replacing pieces with dynamically created variables.
POST with parameters
The above ajax example includes these lines:
type: "POST", // request type (watch out for CORS!)
data: { "foo": "bar" } // request body (form parameters)
This means the ajax request will be a POST and will contain a request body in this case containing foo=bar. You can, of course put whatever you need in there. It's standard form data. The server would read this data in whatever standard way it uses (e.g. request context form parameters).
Auto-Refresh
I haven't done this myself, but there are solutions documented using setInterval - something like this:
setInterval( function () {
console.log("reloading");
}, 2000 ); // milliseconds
Final note - just to reiterate - this is not going to be able to handle whatever JSON you throw at it. And if you have no control over the JSON structures, then there may well be too many differences from one payload to the next.
But if you control the JSON and if you want to define more features (e.g. default sorting, hidden columns) then you can start adding those to the JSON as additional metadata items.
Hope that helps or at least gives you some pointers.
By the way, there should generally be no need to use code which manipulates the DOM (e.g. building strings of HTML, or manipulating tags). That is counter to how DataTables is designed to work. You should instead be working with the DataTables object itself, wherever possible.

Related

Iterate through the AJAX url in the render from Datatables

The thing is that i am trying to fill a datatable like this
$('#example tbody').on('click', 'tr', function () {
var data = table.row( this ).data();
alert( 'You clicked on '+data.name+'\'s row' );
$.ajax({
url: data.url,
dataType: 'json',
success: function(json){
console.log(json)
tableDos.rows.add([json]).draw();
}
});
} );
What this does is that when someone selects a row from another datatable that its already filled, it is going to extract the URL of the selected JSON from the row (The JSON comes from SWAPI.CO API) and passed it through to fill another datatable like this.
var tableDos = $('#exampleDos').DataTable({
"columns": [{
"title": "Films",
"data": "films",
render: function (data, type, row, meta) {
var currentCell = $("#exampleDos").DataTable().cells({"row":meta.row, "column":meta.col}).nodes(0);
// $.each(data, function (i, item){
$.ajax({
url: data[0],
success: function(json){
console.log(json)
$(currentCell).text(json.title);
}
});
// })
return null;
}
},
{
"title": "Vehicles",
"data": "vehicles"
},
{
"title": "Starships",
"data": "starships"
}
]
});
The tricky part comes here, what this table is receiving is coming from this JSON
{
"name": "Luke Skywalker",
"height": "172",
"mass": "77",
"hair_color": "blond",
"skin_color": "fair",
"eye_color": "blue",
"birth_year": "19BBY",
"gender": "male",
"homeworld": "https://swapi.co/api/planets/1/",
"films": [
"https://swapi.co/api/films/2/",
"https://swapi.co/api/films/6/",
"https://swapi.co/api/films/3/",
"https://swapi.co/api/films/1/",
"https://swapi.co/api/films/7/"
],
"species": [
"https://swapi.co/api/species/1/"
],
"vehicles": [
"https://swapi.co/api/vehicles/14/",
"https://swapi.co/api/vehicles/30/"
],
"starships": [
"https://swapi.co/api/starships/12/",
"https://swapi.co/api/starships/22/"
],
"created": "2014-12-09T13:50:51.644000Z",
"edited": "2014-12-20T21:17:56.891000Z",
"url": "https://swapi.co/api/people/1/"
}
So my table as you can see is receiving films, vehicles and starships in the form of an array and URL so i have to do another AJAX call as you can see in the table from for example "films" so i in the AJAX url i have to iterate through the films ARRAY but it automatically iterates without using loops or each and i cant make it work. It seems confusing but check it out for yourselves.
https://jsfiddle.net/um8tmgq2/2/

Attach object to Highcharts click event

Moving from D3 to Highcharts and this is eluding me. I have a fairly complex object that contains a clickthrough object which needs to be accessed in a function on a point click in the series. I'm creating the series array with the data and name just fine with a small conversion, but I need to attach this object to the data points as well. No idea how.
Quick example. original data:
[
{
"key": "Super Cool Thing",
"format": ".2f",
"values": [
{
"label": "01",
"value": 9.5,
"format": ".2f",
"order": 0,
"tooltip": "numerator = 133, denominator = 14",
"clickthrough": {
"output_format": "json",
"metrics": "",
"options": {
"columns": [
{
"order": 1,
"display_as": "Brand",
"format": "{0}",
"name": "brand",
"data_type": "string"
},
{
"order": 2,
"display_as": "Last Submit Time (Month)",
"format": "%m",
"name": "last-submit-time-month",
"data_type": "datetime"
},
{
"order": 3,
"display_as": "Agent Things",
"format": "{0}",
"name": "agent-thing-values",
"data_type": "string"
}
]
},
"cut_y": "brand",
"type": "",
"filter": { },
"cut_x": "last-submit-time-month"
},
"metrics": [
{
"name": "Agent - Feel Appreciated Mean",
"slug": "qcustomersatr4-mean"
}
]
}
]
}
]
run through a (super quick POC) funct:
for(let i = 0; i < data.length; i++){
var values = [];
var xcuts = [];
data[i].values.forEach(val => {
values.push(val.value);
xcuts.push(val.label);
});
chart.addSeries({
name: data[i].key,
data: values
})
chart.xAxis[0].setCategories(xcuts);
}
and this all works fine. But I need the clickthrough object so I can do something like:
plotOptions: {
series: {
allowPointSelect: true,
cursor: 'pointer',
point: {
events: {
click: function (event) {
console.log('CLICKTHROUGH DATA HERE');
console.log(event.point);
}
}
}
},
},
I'm unsure how to format the series data to include additional data that's accessible in an event function later down the line. I currently do this via d3 and it's fine, but am struggling with the Highcharts method to do the same. It seems I can't just add whatever I want to the series or data, so is this possible?
Have it. I have to set the y value explicitly and then I can add whatever else which is then avail in the event.
example:
data[i].values.forEach(val => {
values.push({link: val.clickthrough, y:val.value});
xcuts.push(val.label);
});
chart.addSeries({
name: data[i].key,
data: values
})

i need to convert array value to json in jquery [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
i have array value. need to convert this array value into json format. example is given bleow
Sample Array
[Management Portal!#!#Production Issue Handling!#!#/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!#!# Event Browser!#!#/IONSWeb/orderManagement/eventBrowser.do, Management Portal!#!# Order Workflow!#!#/IONSWeb/orderManagement/SearchOrdersWorkflow.do, ADMINISTRATION!#!#Admin Message!#!#/IONSWeb/userManagement/getMessageForBroadcast.do, ADMINISTRATION!#!#Audit!#!#/IONSWeb/userManagement/auditManagement.do, ADMINISTRATION!#!#Locks!#!#/IONSWeb/userManagement/lockSearch.do, ADMINISTRATION!#!#Queue!#!#/IONSWeb/GroupManagement/begin.do, ADMINISTRATION!#!#Role!#!#/IONSWeb/userManagement/goToRolePage.do, ADMINISTRATION!#!#Routing Rule!#!#/IONSWeb/ruleManagement/showRules.do, ADMINISTRATION!#!#Task Code!#!#/IONSWeb/ManageTaskCode/begin.do, ADMINISTRATION!#!#Trigger OutEvent!#!#/IONSWeb/triggerOutEvent.jsp, ADMINISTRATION!#!#User!#!#/IONSWeb/userManagement/begin.do, ADMINISTRATION!#!#Refresh Application Cache!#!#/IONSWeb/userManagement/refreshApplnCache.do]
sample Json
{
"name": "Administration",
"sub": [
{
"name": "Add Order",
"url": "/IONSWeb/userManagement/auditManagement.do"
},
{
"name": "Infrastructure sonet Add Order ",
"url": "/IONSWeb/userManagement/auditManagement.do"
},
{
"name": "fGNS Add Order",
"url": "/IONSWeb/userManagement/auditManagement.do"
}
]
}
Please anyone help on this
I think you want to do something like this. Split the string, get out the first element, that will be the name, and iterate through all the elements. Every even value will be the name, and every odd an url.
When it is odd, then add it to the sub array. Thats it.
var string = 'Management Portal!#!#Production Issue Handling!#!#/IONSWeb/refDataManagement/searchDynamicScripts.do, Management Portal!#!# Event Browser!#!#/IONSWeb/orderManagement/eventBrowser.do, Management Portal!#!# Order Workflow!#!#/IONSWeb/orderManagement/SearchOrdersWorkflow.do, ADMINISTRATION!#!#Admin Message!#!#/IONSWeb/userManagement/getMessageForBroadcast.do, ADMINISTRATION!#!#Audit!#!#/IONSWeb/userManagement/auditManagement.do, ADMINISTRATION!#!#Locks!#!#/IONSWeb/userManagement/lockSearch.do, ADMINISTRATION!#!#Queue!#!#/IONSWeb/GroupManagement/begin.do, ADMINISTRATION!#!#Role!#!#/IONSWeb/userManagement/goToRolePage.do, ADMINISTRATION!#!#Routing Rule!#!#/IONSWeb/ruleManagement/showRules.do, ADMINISTRATION!#!#Task Code!#!#/IONSWeb/ManageTaskCode/begin.do, ADMINISTRATION!#!#Trigger OutEvent!#!#/IONSWeb/triggerOutEvent.jsp, ADMINISTRATION!#!#User!#!#/IONSWeb/userManagement/begin.do, ADMINISTRATION!#!#Refresh Application Cache!#!#/IONSWeb/userManagement/refreshApplnCache.do';
var pieces = string.split('!#!#');
var first = pieces[0];
//Get out the first one, that will be the key
pieces.shift();
//Create the object
var object = {
'name': first,
'sub': []
};
//Iterate through elements
var i = 0;
var sub = [];
$.each(pieces, function (idx, piece) {
if (i % 2 == 0) {
sub['name'] = piece;
} else {
sub['url'] = piece;
object.sub.push(sub);
}
i++;
});
console.log(object);
Try something like this:
Fiddle: https://jsfiddle.net/ug85d7o7/6/
var jsonData = [],
item, name,
subItem, subUrl,
i, j,
a = [
"Management Portal!#!#Production Issue Handling!#!#/IONSWeb/refDataManagement/searchDynamicScripts.do",
"Management Portal!#!# Event Browser!#!#/IONSWeb/orderManagement/eventBrowser.do",
"Management Portal!#!# Order Workflow!#!#/IONSWeb/orderManagement/SearchOrdersWorkflow.do",
"ADMINISTRATION!#!#Admin Message!#!#/IONSWeb/userManagement/getMessageForBroadcast.do",
"ADMINISTRATION!#!#Audit!#!#/IONSWeb/userManagement/auditManagement.do",
"ADMINISTRATION!#!#Locks!#!#/IONSWeb/userManagement/lockSearch.do",
"ADMINISTRATION!#!#Queue!#!#/IONSWeb/GroupManagement/begin.do",
"ADMINISTRATION!#!#Role!#!#/IONSWeb/userManagement/goToRolePage.do",
"ADMINISTRATION!#!#Routing Rule!#!#/IONSWeb/ruleManagement/showRules.do",
"ADMINISTRATION!#!#Task Code!#!#/IONSWeb/ManageTaskCode/begin.do",
"ADMINISTRATION!#!#Trigger OutEvent!#!#/IONSWeb/triggerOutEvent.jsp",
"ADMINISTRATION!#!#User!#!#/IONSWeb/userManagement/begin.do",
"ADMINISTRATION!#!#Refresh Application Cache!#!#/IONSWeb/userManagement/refreshApplnCache.do"
];
for(i=0; i<a.length; i++)
{
item = a[i].split("!#!#");
name = item[0];
subName = item[1];
subUrl = item[2];
subItem = null;
for (j=0; j<jsonData.length; j++)
{
if (jsonData[j].Name == name)
{
subItem = jsonData[j].sub;
break;
}
}
if (!subItem)
{
jsonData.push({"Name" : name, "sub" : [] });
subItem = jsonData[jsonData.length-1].sub;
}
subItem.push({"Name" : subName, "url" : subUrl });
}
alert(JSON.stringify(jsonData));
Result:
[
{
"Name": "Management Portal",
"sub": [
{
"Name": "Production Issue Handling",
"url": "/IONSWeb/refDataManagement/searchDynamicScripts.do"
},
{
"Name": " Event Browser",
"url": "/IONSWeb/orderManagement/eventBrowser.do"
},
{
"Name": " Order Workflow",
"url": "/IONSWeb/orderManagement/SearchOrdersWorkflow.do"
}
]
},
{
"Name": "ADMINISTRATION",
"sub": [
{
"Name": "Admin Message",
"url": "/IONSWeb/userManagement/getMessageForBroadcast.do"
},
{
"Name": "Audit",
"url": "/IONSWeb/userManagement/auditManagement.do"
},
{
"Name": "Locks",
"url": "/IONSWeb/userManagement/lockSearch.do"
},
{
"Name": "Queue",
"url": "/IONSWeb/GroupManagement/begin.do"
},
{
"Name": "Role",
"url": "/IONSWeb/userManagement/goToRolePage.do"
},
{
"Name": "Routing Rule",
"url": "/IONSWeb/ruleManagement/showRules.do"
},
{
"Name": "Task Code",
"url": "/IONSWeb/ManageTaskCode/begin.do"
},
{
"Name": "Trigger OutEvent",
"url": "/IONSWeb/triggerOutEvent.jsp"
},
{
"Name": "User",
"url": "/IONSWeb/userManagement/begin.do"
},
{
"Name": "Refresh Application Cache",
"url": "/IONSWeb/userManagement/refreshApplnCache.do"
}
]
}
]

How can I do a multidimensional search with JSON in Javascript?

I am trying to write a basic, experimental search system using JavaScript and JSON, with the searchable data contained in the JSON file. Multiple 'posts' are listed in the file, and each post has an array of 'tags'. My intent is to search through each posts tags, and retrieve only the posts that have tags matching a query, such as "funny cat video" (the posts would have to have all three tags, "funny", "cat", and "video", to be returned).
My particular concern is performance. I am sure that this technique will be inefficient, as there are approximately 2000 posts, and each one has from 5 to 50 tags, but it has to be done with JavaScript. I am already referencing from this website on how to maximise performance, though I could do with some extra help.
Here is my code so far for storing the data:
{
"index": {
"count": "2",
"posts": [
{
"id": "1",
"date": "2014-11-21 17:16:39 GMT",
"url": "http://url/",
"image": "http://big_image/",
"thumbnail": "http://little_image/",
"tags": ["funny", "cat", "picture", "falling", "chair", "window sill", "funny"]
},
{
"id": "2",
"date": "2014-11-20 17:57:32 GMT",
"url": "http://url1/",
"image": "http://big_image1/",
"thumbnail": "http://little_image1/",
"tags": ["funny", "cat", "picture", "jumping", "water", "bath", "funny"]
}
]
}
}
And this is my Javascript:
var query = "funny cat bath".split(" ");
var data = JSON.parse("THE JSON GOES HERE");
var count = data.index.count;
var index = data.index.posts;
for (var i = 0, indexLength = index.length; i < indexLength; i++) {
tags = index[i].tags;
for (var q = 0, queryLength = query.length; q < queryLength; q++) {
if(tags.indexOf(query[q]) !== false) {
console.log(index[i]);
}
}
}
Unfortunately, I can't figure out how to get it to return only the posts that have all three tags, and it returns all posts with any of the tags supplied. Not only that, but it returns duplicates.
Does anybody have a better solution? I'm stuck.
You need to use a flag and only "write" out the match when they are all found, you are writing it out when one is found. Plus indexOf returns -1, not false. Basic idea below:
var data = {
"index": {
"count": "2",
"posts": [
{
"id": "1",
"date": "2014-11-21 17:16:39 GMT",
"url": "http://url/",
"image": "http://big_image/",
"thumbnail": "http://little_image/",
"tags": ["funny", "cat", "picture", "falling", "chair", "window sill", "funny"]
},
{
"id": "2",
"date": "2014-11-20 17:57:32 GMT",
"url": "http://url1/",
"image": "http://big_image1/",
"thumbnail": "http://little_image1/",
"tags": ["funny", "cat", "picture", "jumping", "water", "bath", "funny"]
}
]
}
};
var query = "funny cat bath".split(" ");
var filteredSet = []; //where the matched objects will reside
var posts = data.index.posts; //get the posts
for (var i=0; i<posts.length;i++) { //loop through the posts
var post = posts[i];
var tags = post.tags; //reference the tags
var hasMatch = true; //flag to hold the state if we have a good match - set to true by default
for (var j=0; j<query.length; j++) { //loop through the tags the user is looking for
var index = tags.indexOf(query[j]); //look for it in the set [Note older IEs needs polyfill see MDN for code]
if (index===-1) { //indexOf returns -1 if not found
hasMatch=false; //set Boolean flag so we do not record item
break; //exit loop - no reason to keep checking
}
}
if (hasMatch) { //if we found all the tags
filteredSet.push(post); // add to the filtered set
}
}
console.log(filteredSet); //show the filtered set

How to read JSON in order to get the last video from YouTube

I'd like to extract the last video (only video), with title, description, etc.
I am using JSON Data API from YouTube Data API and using the Video Upload By User Feed in order to get the data.
I got from youtube a JSON (object?) about my Youtube's space and tried to read the JSON text, but its a suicide.
My code is :
<div id="ytContent"></div>
<script type="text/javascript">
function showMyVideos(data) {
var feed = data.feed;
var entries = feed.entry || [];
for (var i = 0; i < entries.length; i++) {
var entry = entries[i];
var title = entry.title.$t;
$('#ytContent').append(title + "<br />");
}
}
</script>
<script type="text/javascript" src="http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads?alt=json-in-script&format=5&callback=showMyVideos"></script>
but if I try to do :
var p = eval("(" + data + ")");
alert(p);
I can't get a right parser. Why? How can I parse my JSON? I just need to understand which field I can use in order for me to get the last video from the feed. Also, hints/tips on getting the last video will also be helpful.
Thanks
You don't need to parse the data, it is already parsed.
The url inside your script tags gets rendered into a function call, passing the data object as a parameter: showMyVideos({ /* data object */ });.
Your problem is that you are trying to access the entry field in the data you are receiving (var entries = feed.entry || []), but there is no such field in data.feed:
var data = {
"version": "1.0",
"encoding": "UTF-8",
"feed": {
"xmlns": "http://www.w3.org/2005/Atom",
"xmlns$openSearch": "http://a9.com/-/spec/opensearchrss/1.0/",
"id": {
"$t": "http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads"
},
"updated": {
"$t": "2011-09-06T08:05:27.303Z"
},
"category": [
{
"scheme": "http://schemas.google.com/g/2005#kind",
"term": "http://gdata.youtube.com/schemas/2007#video"
}
],
"title": {
"$t": "Uploads by MYUSERNAME",
"type": "text"
},
"logo": {
"$t": "http://www.youtube.com/img/pic_youtubelogo_123x63.gif"
},
"link": [
{
"rel": "related",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/users/myusername"
},
{
"rel": "alternate",
"type": "text/html",
"href": "http://www.youtube.com/profile_videos?user=MYUSERNAME"
},
{
"rel": "http://schemas.google.com/g/2005#feed",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads"
},
{
"rel": "http://schemas.google.com/g/2005#batch",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads/batch"
},
{
"rel": "self",
"type": "application/atom+xml",
"href": "http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads?alt=json-in-script&start-index=1&max-results=25&format=5"
}
],
"author": [
{
"name": {
"$t": "MYUSERNAME"
},
"uri": {
"$t": "http://gdata.youtube.com/feeds/users/myusername"
}
}
],
"generator": {
"$t": "YouTube data API",
"version": "2.1",
"uri": "http://gdata.youtube.com/"
},
"openSearch$totalResults": {
"$t": 0
},
"openSearch$startIndex": {
"$t": 1
},
"openSearch$itemsPerPage": {
"$t": 25
}
}
}
When showMyVideos is called, data is already parsed. You don't need to parse it.
You don't get JSON! You get JavaScript!
If you execute it using eval(),the data is automatically passed to your showMyVideos function. You don't have to parse anything ;) The data is already parsed, its an object, not a string.
Based on the question, I am assuming you want to get the last video and show it as video player.
In order to show the last video, the possible steps are:
Include the script for the player itself
<script type="text/javascript" src="http://swfobject.googlecode.com/svn/trunk/swfobject/swfobject.js"></script>
Create your callback function. Basically what Google does is getting the JSON, parse it and call your callback function that you specified in callback parameter in your http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads?alt=json-in-script&format=5&callback=showMyVideos. In your callback you would want to show the video player for the last video. Something like:
// function to load your video
function loadVideo(playerUrl, autoplay) {
swfobject.embedSWF(
playerUrl + '&rel=1&border=0&fs=1&autoplay=' +
(autoplay?1:0), 'player', '290', '250', '9.0.0', false,
false, {allowfullscreen: 'true'});
}
// this is your callback function, Google call this function after parsing the JSON
// and passing it as data
function showMyVideos(data) {
var feed = data.feed;
var entries = feed.entry || [];
if (entries.length > 0) {
// show the video for the last entry
loadVideo(entries[entries.length-1].media$group.media$content[0].url, false);
}
}
Next you define somewhere where you want to put your video
<div id="playerContainer" style="width: 20em; height: 180px; float: left;">
<object id="player"></object>
</div>
Finally call the script that will invoke your callback. This should be the same as your code in the question
<script type="text/javascript" src="http://gdata.youtube.com/feeds/users/MYUSERNAME/uploads?alt=json-in-script&format=5&callback=showMyVideos"></script>

Categories