JSON parse will not execute with JavaScript - javascript

This is my current code, any help would be greatly appreciated. I need to call my listApp.json file and parse it. I want to display my list which currently has one link. I'm new to this.
<script type = "text/javascript">
// If the .js files are linked correctly, we should see the following output inside the JavaScript Console
console.log("starting...");
// Gets the .json file and applies the function
var json;
// When the document is ready then run the function
$(document).ready(function(){
// Standard jQuery ajax technique to load a .json file
$.ajax({
type: "GET", // Requests data from a specified resource
url: "include/listApp.json", // Gets the file on which the url is directed to
dataType: "json", // Data Type needs to be json in this case. This can be xml
success: jsonParser // If successful then run the, 'jsonParser' function
});
});
// Actual parse function
function jsonParser(data) {
JSON = data;
$(JSON).find("games").each(function (){
games = $(this);
var name = $(games).find("name").text();
var url = $(games).find("url").text();
var id = $(ganes).find("id").text();
console.log(name);
// Appends list + link + name
$("#myList").append('<li>'+ ""+name+""+'</li>');
$('#myList').listview('refresh');
$("#pages").append('<div data-role="page" id = "'+ id +'"><img src = '+ url +'> test</div>');
});
}
</script>

Since data is an object, you can access the games array using data.listApp.games and iterate over it using $.each(), then inside the loop callback you will the game object as second param and you can access its properties using member operator
function jsonParser(data) {
$.each(data.listApp.games, function (i, game) {
var name = game.name;
var url = game.url;
var id = game.id;
console.log(name);
// Appends list + link + name
$("#myList").append('<li>' + "" + name + "" + '</li>');
$('#myList').listview('refresh');
$("#pages").append('<div data-role="page" id = "' + id + '"><img src = ' + url + '> test</div>');
});
}

Related

How to speed up my Ajax call when there are multiple same ajax call made on a page?

When the page loads, I am also dynamically creating a block . I am using ajax call to go and fetch data from another page and then populating it and creating my structure that is then added to a particular dom element. However, the problem is when I do this several times on the page during page loads, it takes quite some time for all Ajax call to finish. Do you know how I can speed up the ajax call?
$('.content-tile').each(function (idx, ele) {
// Step 1: Get the stuffs and add it in the right place on page load
var node_id = $(ele).find('article').attr('data-history-node-id');
$.get('/node/' + node_id , function (data) {
var $title = $(data).find('.title').text();
var $summary = $(data).find('.article__body').text();
var $ctaText = $(data).find('.article__field-read-more-text').text();
var $redirectToFile = $(data).find('.article__field-nova-redirect-to-file').find('a').attr('href');
var $redirectToLink = $(data).find('.article__field-redirect-link').find('a').attr('href');
// Either redirect to file or redirect to link in the order
var $ctaLinkHref = $redirectToFile;
if ($redirectToLink) {
$ctaLinkHref = $redirectToLink;
}
var $contentHover = "<a class='content-added contenthover hoveredLink' href= " + $ctaLinkHref + "></a>";
$(ele).find('article').after($contentHover); // Add the div that will be targeted for the hover
var $contentHoverHeader = "<h2 class='contenthover__header'>" + $title + '</h2>';
var $contentHoverContent = "<p class='contenthover__content'>" + $summary + '</p>';
var $contentHoverLink = "<a class='contenthover__link' href=" + $ctaLinkHref + '>' + $ctaText + '</a>';
$(ele).find('.contenthover').append($contentHoverHeader, $contentHoverContent, $contentHoverLink);
});
});
As Rory mentioned, instead of calling multiple times, just create the single object, post it back and return all the related data in one go.
// construct the array
var nodes = []
$('.content-tile').each(function (idx, ele) {
var node_id = $(ele).find('article').attr('data-history-node-id');
nodes.push(node_id);
}
// call ajax now
$.ajax({
url: "/node/RetrieveDataByNodes", //the new method which can accept the array and return data
data: JSON.stringify(nodes),
type: 'GET',
dataType: 'json'
}).done(function(result) {
$.each(result, function (k, v) {
//do something for each value
console.log(v);
}
});

How to get the facebook user id to another javascript file after login?

I understand that I can get the facebook id by doing:
FB.api('/me', function(response) {
alert('Your id is ' + response.id);
});
However, I want to have the user login and then grab that id in a different file so I can handle it. Right now I have:
var id = "";
var fburl = "http://graph.facebook.com/" + id + "?callback=?"
$(function(){
$("#fb-profile-picture")[0].src = "http://graph.facebook.com/" + id +"/picture";
$.getJSON(fburl, function(data){
console.log(data);
$("#name").append(data.name);
$("#user-id").append(data.id);
});
});
and if I manually enter the id in the id var it works however I'd like to be able to grab that response.idas the value and use it in this other javascript file but I haven't figured out how to.
Assuming you
cannot control which of the scripts is executed first
you are working in an environment with a global window object
part one is only executed once
you are using jQuery
making a global and firing an event might be a solution, although not considered best practice.
Script 1:
FB.api('/me', function(response) {
window.fbCustomId = response.id;
console.log(window.fbCustomId);
$(window).trigger('fbResponseLoaded');
});
Script 2:
function renderProfile() {
var fburl = "//graph.facebook.com/" + window.fbCustomId + "?callback=?"
$(function () {
$("#fb-profile-picture")[0].src = "//graph.facebook.com/" + window.fbCustomId + "/picture";
$.getJSON(fburl, function (data) {
console.log(data, window.fbCustomId);
$("#name").append( $('<span>').text(data.name) );
$("#user-id").append( $('<span>').text(data.id) );
});
});
}
if (window.fbCustomId) {
renderProfile();
} else {
$(window).on('fbResponseLoaded', renderProfile);
}

How do I extract data from xml and post to a div using jquery/javascript

I am trying to get the title for a twitch.tv stream from an xml file using either jQuery or JavaScript and then post that title to a div (as a section header). The title is found in the <status> section of the xml file.
Below the code I currently have which doesn't seem to be working:
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://www.twitch.tv/meta/koibu.xml",
dataType: "xml",
success: function(xml) {
var xmlDoc = $.parseXML(xml),
$xml = $(xmlDoc);
$(xml).find('meta status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
}
});
});
Here is a jsfiddle -with my broken script in- to play with.
Edit: solved it using a json call instead of reading xml
$(document).ready(function(){
var names = ["koibu"];
var obj = jQuery.parseJSON('{"name": {"life": "{life}","logo": "{logo}","status": "{status}","preview": "{preview}","url": "{url}"}}');
grabJSON();
function grabJSON() {
setTimeout(grabJSON,1000);
for (index = 0; index < names.length; ++index) {
$.getJSON("https://api.twitch.tv/kraken/channels/" + names[index] + "/?callback=?", function (json) {
$('#lefttitle').empty(),
$('#lefttitle').append("<h2>" + json.status + "</h2>");
});
}
}
});
This also allows me to set up a nice little array to grab more data from multiple channels if I want to extend it in future.
If you're not suffering from CORS, then the actual problem is below
$(xml).find('status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
xml variable represents the unparsed XML.
It has to like
$xml = $(xmlDoc);
$xml.find('status').each(function(){
$('#block').append("<h2>" + $(this).text() + "</h2>");
});
I managed to get your XML file, and the status tag contains Monday Mafia!

Javascript - Getting data from XML for later use... put in array or object?

I am extracting a bunch of data from an XML file using jQuery. I need to use the data to fill in image paths, names, etc.
What is the best way to gather all of this data for use? For instance, I get everything like so:
$(document).ready(function() {
$.ajax({
type: "GET",
url: "stuff.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('speaker').each(function(){
var img_path = $(this).find('speaker_image').text();
var name_text = $(this).find('speaker_name').text();
// should I build an array or object here?
});
}
});
});
Should I stick everything into an array in the success method? Maybe in an object? What I will do is take the collected data and use it to build a list of names and images. There will be quite a few elements in this and it will look something like (with img_path being used in the image url and name_text being used for the label:
<ul>
<li><img src="images/bobsmith.jpg" /><br /><lable>Bob S. Smith</label></li>
<li><img src="images/crystalforehead.jpg" /><br /><lable>Crystal X. Forehead</label></li>
...
</ul>
What is the best way to handle the collected data so I can go through and build the html I need using it?
If you do not need to re-use the data from the XML file, why not build the DOM elements whilst you are reading it?
So for example in your success method:
$(xml).find('speaker').each(function(){
var img_path = $(this).find('speaker_image').text();
var name_text = $(this).find('speaker_name').text();
var html = '<li><img src="' + img_path + '" /><br /><label>' + name_text + '</label></li>';
$("#myList").append(html);
});
This will put the retrieved results in an array using push:
success: function(xml) {
var results = [];
$(xml).find('speaker').each(function(){
results.push($(this));
});
Put it into an array object if you need to re-use:
function linkItem(linkImage, linkText)
{
this.linkImage = linkImage;
this.linkText = linkText;
};
function mylist()
this.speakerList = new Array();
$(xml).find('speaker').each(function()
{
this.speakerList [$(this).index()] = new linkItem($(this).find('speaker_image').text(), $(this).find('speaker_name').text());
};
};
Just build it if you use only once:
var myhtml = ""
$(xml).find('speaker').each(function(){
myhtml = myhtml + '<li><img src="' + $(this).find('speaker_image').text() + '" /><br /><label>' + $(this).find('speaker_name').text() + '</label></li>';
});
then use it:
$(selector).append(myhtml);
or
$(selector).innerHtml(myhtml);

Using Ajax callback variable values in JQuery dynamic click handlers

I'm doing a simple ajax query which retrieves a variable-length list of values as JSON data. I'm trying to make a list based on this data which has click-functions based on the values I got from the JSON query. I can make this work just fine by writing the onClick-methods into the HTML like this:
function loadFooList() {
var list_area = $("#sidebar");
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' onClick='alert(\"" +
link_id + "\");'>" +
item.name + "</a></li>");
});
list_area.html(list_area.html() + "</ul>");
}
});
}
I don't like writing the onClick-function into the HTML and I also want to learn how to create this same functionality via JQuery click-function.
So the problem is obviously variable-scoping. My naive attempt here obviously won't work because the variables are no longer there when the click happens:
function loadFooList2() {
var list_area = $("#sidebar");
var link_ids = Array();
list_area.html("<ul>")
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
list_area.html(list_area.html()
+ "<li> <a href='#' id='" + link_id + "'>"+item.name+"</a></li>");
link_ids.push(link_id);
});
list_area.html(list_area.html() + "</ul>");
for (link_index=0; link_index<link_ids.length; link_index++) {
$("#" + link_ids[link_index]).click(function() {
alert(link_ids[i]);
});
}
}
});
}
Obviously I'd like to do something else than just alert the value, but the alert-call is there as long as I can get that working and move forward.
I understand that I'll have to make some kind of handler-function to which I pass a state-variable. This works for a single value (I can store the whole link_ids array just fine, but then I don't know which of them is the right value for this link), but how would I do this for arbitrary-length lists?
Here is an example from JQuery docs which I'm trying to copy:
// get some data
var foobar = ...;
// specify handler, it needs data as a paramter
function handler(data) {
//...
}
// add click handler and pass foobar!
$('a').click(function(){
handler(foobar);
});
// if you need the context of the original handler, use apply:
$('a').click(function(){
handler.apply(this, [foobar]);
});
And I quess the last example here, "if you need the context of the original handler..." would probably be what I want but I don't know exactly how to get there. I tried to store the current link_id value into this, use it from this in the applied function (using apply()) but I didn't succeed. The necessary values were still undefined according to FireFox. I'm using JQuery 1.3.2.
So what's the right solution for this relatively basic problem?
Use append instead of html():
function loadFooList() {
var ul = $('<ul>');
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
$.each(json, function(i, item) {
var link_id = "choosesfoo" + item.id;
var a = $('<a>').attr('href','#').bind('click', function(e) {
alert(link_id,item_name);
e.preventDefault();
});
$('<li>').append(a).appendTo(ul);
});
ul.appendTo('#sidebar'); // this is where the DOM injection happens
}
});
}
So the problem appears to be getting the link id associated with the link so that your click handler has access to it. Note that if it's alphanumeric it will qualify for the id attribute and you can extract it from there. If it is purely numeric, it will be an illegal id attribute. In that case, you can either use an attribute, like rel, or the jQuery.data() method to store the link id with the link. You can also simplify by using append. I'll show both examples.
var link = $("<li><a href='#' id='" + link_id + "'>" + item.name + "</a></li>";
link.click( function() {
alert( $(this).attr('id') );
});
list_area.append(link);
or (if numeric)
var link = $("<li><a href='#'>" + item.name + "</a></li>";
link.data('identifier', link_id )
.click( function() {
alert( $(this).data('identifier') );
});
list_area.append(link);
Try this:
function loadFooList() {
var list_area = $("#sidebar");
$.ajax({
type: 'GET',
url:'/data/foo/list',
dataType: 'json',
success: function (json) {
var out = '<ul>';
$.each(json, function(i, item) {
var link_id = "choosefoo" + item.id;
out +="<li><a href='#' id='" + link_id + "'>"+item.name+"</a></li>";
});
out +="</ul>"
var $out = $(out);
$out.find('a').click(function(){
var link_id = this.id;
var item_name = $(this).text();
alert(link_id);
alert(link_name);
})
list_area.html($out);
}
});
}
Using multiple appends causing the browser to redraw multiple times in a row. You only want to modify the dom once.

Categories

Resources