Twitch TV API JSON Issue - javascript

I work with Twitch API. If the streamer streams I work with with property "Stream". But If he's not streaming, then I need refer to another link. Then I again turn to the function of the getJSON and pass there the necessary API link. And I'm working with her. However, the loop does not work as it should. It takes the last streamer out of the "channels" array, but it should all those who do not stream. I can not understand what the problem is. Help...
JSFiddle: https://jsfiddle.net/e7gLL25y/
JS Code:
var getJSON = function(url, callback) {
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function() {
if(xhr.readyState == 4 && xhr.status == "200") {
callback(JSON.parse(xhr.responseText));
}
};
xhr.send();
};
var channels = ["summit1g", "esl_RuHub_CSGO", "Starladder1", "Senpai_Frozen", "tehvivalazz", "ESL_CSGO"];
var client_id = "hx3dea4ifwensxffoe8iwvekwvksnx";
var section = document.getElementById("main-section");
var streamer = [];
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
getJSON(url_streams, function(response) {
if( response["stream"] !== null ) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + response.stream.channel["url"] +
"'><img id='streamer-image' src='" +
response.stream.channel["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
response.stream.channel["name"] +
"</h2><p id='stream-status'>" +
response.stream["game"] + "</p></a>";
section.appendChild(streamer[i]);
} else {
getJSON(url_channels, function(r) {
streamer[i] = document.createElement("div");
streamer[i].className = "streamer";
streamer[i].innerHTML = "<a target='_blank' href='" + r["url"] +
"'><img id='streamer-image' src='" +
r["logo"] +
"' alt='Av' /><h2 id='streamer-name'>" +
r["name"] +
"</h2><p id='stream-status'>Offline</p></a>";
section.appendChild(streamer[i]);
});
}
});
}

You are having a common misconception about JavaScript contexts.
Refer to my answer here to see details about this problem: https://stackoverflow.com/a/42283571/1525495
Simply, the getJSON response is called after all the array is looped, so i will be the last index in all the responses. You have to create another context to keep the i number so is not increased.
for(var i = 0; i < channels.length; i++) {
var url_channels = "https://api.twitch.tv/kraken/channels/" + channels[i] + "?client_id=" + client_id;
var url_streams = "https://api.twitch.tv/kraken/streams/" + channels[i] + "?client_id=" + client_id;
(function(i) {
// i will not be changed by the external loop as is in another context
getJSON(url_streams, function(response) {
// Thingy things...
});
})(i);
}

Related

Javascript onmousehover event to connect information

So in my code I created a table pulling from an XML file that displayed two columns of information about plants. The goal of my program is to be able to hover over the first and print out the other information about that plant and print it in another section to the right of my table. The issue is that I am not gettign any console errors and the hover affect is not printing any information.
window.addEventListener("load", link_events);
var xhr = false;
function link_events() {
xhr = new XMLHttpRequest();
if(xhr) {
xhr.addEventListener("readystatechange", ShowFile);
xhr.open("GET", "plants.xml", true);
xhr.send();
} else {
alert("XHR not supported.");
}
}
function ShowFile() {
var i;
var title;
var cover;
var plant_table = "<table><tr><th>Common Name </th><th>Botanical Name </th></tr>";
if (xhr.readyState == 4) {
if (xhr.status == 200) {
//here we have gotten the file correctly
//loop through it and print out cover and title
var plantlist = xhr.responseXML.getElementsByTagName("PLANT");
//booklist is an array and each element is an object sub i
//so you have to use getElementBy something in order to pull the information
for (i = 0; i < plantlist.length; i++) {
var Common = plantlist[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Botanical = plantlist[i].getElementsByTagName("BOTANICAL")[0].firstChild.textContent;
plant_table += "<tr>" +
"<td class =\"plant\">" + Common + "</td>" +
"<td>" + Botanical + "</td>" +
"</tr>";
}
plant_table += "</table>";
document.getElementById("outarea").innerHTML = plant_table;
}
var plants = document.getElementsByClassName("plant");
for (i=0; i < plants.length; i++) {
plants[i].onmouseover = HoverChoice;
}
}
function HoverChoice() {
var input = xhr.responseXML.getElementsByTagName("PLANT");
for (i = 0; i < input.length; i++) {
Common = input[i].getElementsByTagName("COMMON")[0].firstChild.textContent;
var Zone = input[i].getElementsByTagName("ZONE")[0].firstChild.textContent;
var Light = input[i].getElementsByTagName("LIGHT")[0].firstChild.textContent;
var Price = input[i].getElementsByTagName("PRICE")[0].firstChild.textContent;
if (plants == this.innerHTML) {
document.getElementById("inarea").innerHTML =
"<h1>" + Common + "</h1>" + "<br />" + "<br />" +
"Zone: " + Zone + "<br />" +
"Light: " + Light + "<br />" +
"Price: " + Price;
}
}
}
}
you could try using addEventListener method instead and see whether it works?
plants.forEach(function(plant){
plant.addEventListener("onmouseover", HoverChoice);
});
or going with the original loop you made it would be
for (i=0; i < plants.length; i++)
{
plants[i].addEventListener("onmouseover", HoverChoice);
}
I'm not anything professional, a common problem I used to encounter in these kinds of event listening functions was that calling a global function sometimes fails but making the function on the spot inside the event listener would work like addEventListener("onmouseover" , function() { return 0; });

How to use Angular.js to populate multiple select fields using AJAX calls to different endpoints

I apologize up front for the possible lack of clarity for this question, but I'm new to Angular.js and my knowledge of it is still slightly hazy. I have done the Angular.js tutorial and googled for answers, but I haven't found any.
I have multiple select/option html elements, not inside a form element, and I'm populating them using AJAX. Each form field is populated by values from a different SharePoint list. I'm wondering if there is a way to implement this using Angular.js?
I would like to consider building this using Angular because I like some of it features such as data-binding, routing, and organizing code by components. But I can't quite grasp how I could implement it in this situation while coding using the DRY principle.
Currently, I have a single AJAX.js file and I have a Javascript file that contains an array of the different endpoints I need to connect to along with specific query parameters. When my page loads, I loop through the arrays and for each element, I call the GET method and pass it the end-point details.
The code then goes on to find the corresponding select element on the page and appends the option element returned by the ajax call.
I'm new to Angular, but from what I understand, I could create a custom component for each select element. I would place the component on the page and all the select and options that are associated with that component would appear there. The examples I've seen demonstrated, associate the ajax call with the code for the component. I'm thinking that I could use a service and have each component dependent on that service and the component would pass it's specific query details to the service's ajax call.
My current code - Program flow: main -> data retrieval -> object creation | main -> form build.
Called from index.html - creates the multiple query strings that are passed to ajax calls - ajax calls are once for each query string - the very last function in the file is a call to another function to build the form elements.
var snbApp = window.snbApp || {};
snbApp.main = (function () {
var main = {};
main.loadCount = 0;
main.init = function () {
function buildSelectOptions(){
//***
//Build select options from multiple SharePoint lists
//***
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
for(var i = 0; i < listsArray.length; i++){
var listItem = listsArray[i];
var qryStrng = listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
var listDetails = {
listName: listItem.list,
listObj: listItem,
url: "http://myEnv/_vti_bin/listdata.svc/" + listItem.list +
"?$select=" + listItem.codeDigits + "," + listItem.codeDescription + "," + listItem.ItemStatus + "&$orderby=" + listItem.codeDescription + "&$filter="+listItem.ItemStatus+" eq true" + "&$inlinecount=allpages"
};
var clientContext = new SP.ClientContext.get_current();
clientContext.executeQueryAsync(snbApp.dataretriever.letsBuild(listDetails), _onQueryFailed);
}
//***
//Build select option from other API endpoint
//***
var listDetails = {
listName:"SNB_SecondaryActivityCodes",
url: "http://myEnv/requests/odata/v1/Sites?$filter=(IsMajor eq true or IsMinor eq true) and IsActive eq true and IsPending eq false and CodePc ne null and IsSpecialPurpose eq false&$orderby=CodePc"
};
snbApp.dataretriever.letsBuild(listDetails);
}
buildSelectOptions();
//***
//Add delay to populate fields to ensure all data retrieved from AJAX calls
//***
var myObj = setTimeout(delayFieldPopulate,5000);
function delayFieldPopulate(){
var optObj = snbApp.optionsobj.getAllOptions();
var osType = $("input[name=os_platform]:checked").val();
snbApp.formmanager.buildForm(osType, optObj);
}
};
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return main
})();
AJAX calls here - called from main/previous file:
var snbApp = window.snbApp || {};
snbApp.dataretriever = (function () {
var listsArray = snbApp.splistarray.getArrayOfListsForObjects();
function getListData(listItem) {
var eventType = event.type;
var baseURL = listItem.url;
$.ajax({
url: baseURL,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
})
.done(function(results){
snbApp.objectbuilderutility.buildObjectFields(results, listItem);
})
.fail(function(xhr, status, errorThrown){
//console.log("Error:" + errorThrown + ": " + myListName);
});
}
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return{
letsBuild:function(item) {
getListData(item);
}
};
})();
Builds a item name object - called from recursive AJAX calls / previous file
var snbApp = window.snbApp || {};
snbApp.objectbuilderutility = (function () {
function formatItemCode(itemCode, eventType){
if(eventType !== 'change'){ //for load event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(0,3);
}
}else{ //for change event
var pattern = /^CE/;
var result = pattern.test(itemCode);
if(result){
return itemCode.slice(2);
}else{
return itemCode.slice(3);
}
}
}
return{
buildObjectFields: function(returnedObj, listItem){ //results:returnedObj, prevItem:listItem
//***
//For SharePoint list data
//***
if (listItem.listName !== "SNB_SecondaryActivityCodes") {
var theList = listItem.listName;
var firstQueryParam = listItem.listObj.codeDigits;
var secondQueryParam = listItem.listObj.codeDescription;
var returnedItems = returnedObj.d.results;
var bigStringOptions = "";
//regex to search for SecondaryFunctionCodes in list names
var pattern = /SecondaryFunctionCodes/;
var isSecFunction = pattern.test(theList);
if(isSecFunction){
bigStringOptions = "<option value='0' selected>Not Applicable</option>";
}else{
bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
}
$.each(returnedItems, function (index, item) {
var first = "";
var second = "";
for (var key in item) {
if (item.hasOwnProperty(key)) {
if (key != "__metadata") {
if (key == firstQueryParam) {
first = item[key];
}
if (key == secondQueryParam) {
second = item[key];
}
}
}
}
bigStringOptions += "<option value=" + first + " data-code=" + first + ">" + second + "</option>";
});
var str = theList.toLowerCase();
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
//***
//For other API
//***
} else {
var theList = listItem.listName;
var bigStringOptions = "<option value='0' disabled selected>Select Option</option>";
var returnedItems = returnedObj.value;
for(var i = 0; i < returnedItems.length; i++){
var item = returnedItems[i];
//***
//change event type means the user selected a field
//***
if(listItem.eventType === "change"){
var siteCodeChange = item.SiteCodePc;
if (typeof siteCodeChange === "string" & siteCodeChange != "null") {
siteCodeChange = siteCodeChange < 6 ? siteCodeChange : siteCodeChange.slice(3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeChange + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeChange + ") " + item.Name + "</option>";
snbApp.formmanager.buildSelectSiteLocations(bigStringOptions);
//***
//load event which means this happens when the page is loaded
//***
}else{
var siteCodeLoad = item.SiteCodePc;
if (typeof siteCodeLoad === "string" & siteCodeLoad != "null") {
var siteCodeLoad = siteCodeLoad.length < 4 ? siteCodeLoad : siteCodeLoad.slice(0, 3);
}
bigStringOptions += "<option value='" + item.Id + "' data-code='" + siteCodeLoad + "' data-isDivSite='" + item.IsDivisionSite + "' data-isDistSite='" + item.IsDistrictSite + "' data-divID='" + item.DivisionSiteId + "' data-distID='" + item.DistrictSiteId + "'>(" + siteCodeLoad + ") " + item.Name + "</option>";
snbApp.optionsobj.updateFunctionOrActivity(theList.toLowerCase(), bigStringOptions);
}
}
}
}
};
})();
Form management - called from previous file, gets all select elements on page and appends items from the object in previous file to each select element.
var snbApp = window.snbApp || {};
//Direct interface to the form on the page
snbApp.formmanager = (function(){
var form = {};
form.content_holder = document.getElementById("content_holder");
form.sec_act_codes = document.getElementById("snb_secondary_activity_codes");
form.prim_func_codes = document.getElementById("snb_primary_function_codes");
form.sec_func_codes = document.getElementById("snb_secondary_function_codes");
form.sec_func_nums = document.getElementById("snb_secondary_function_numbers");
form.host_options = document.getElementById("snb_host_options");
form.site_locs_div = document.getElementById("site_locations_div");
form.site_locs = document.getElementById("snb_site_locations");
form.dc_or_off_prem_div = document.getElementById("dc_or_off_premise_div");
form.dc_off_prem_codes = document.getElementById("snb_dc_offpremise_codes");
var snb_secondary_activity_codes = "";
var snb_primary_function_codes = "";
var snb_secondary_function_codes = "";
var snb_secondary_function_numbers = "";
var snb_host_options = "";
var snb_site_locations = "";
var snb_dc_op = "";
//builds the server location hosting options selection
function buildLocationTypeSelector() {
var locationOptionsString = "<option value='0' disabled selected>Select Option</option>";
for (var i = 0; i < locationOptions.length; i++) {
var location = locationOptions[i];
locationOptionsString += "<option value=" + location.hostLocale + " data-code=" + location.code + ">" + location.hostLocale + "</option>";
}
$("#snb_host_options").append(locationOptionsString);
}
function buildSiteLocations(bigString){
if(bigString === undefined){
var siteLocs = document.getElementById("snb_site_locations");
var newOption = document.createElement("option");
newOption.setAttribute("value", 0);
newOption.setAttribute("disabled","disabled");
newOption.setAttribute("checked","checked");
var newText = document.createTextNode("Select Option");
newOption.appendChild(newText);
siteLocs.appendChild(newOption);
} else{
var siteLocs = document.getElementById("snb_site_locations");
siteLocs.innerHTML = bigString;
}
}
return {
form:form,
buildSelectSiteLocations: function(bigString){
buildSiteLocations(bigString);
},
buildForm: function (osType, optObj) {
buildLocationTypeSelector();
buildSecondaryFunctionNumberSelector();
buildSiteLocations();
if(osType === 'windows'){
$("#snb_secondary_activity_codes").append(optObj.windows.secondary_activity);
$("#snb_primary_function_codes").append(optObj.windows.primary_function);
$("#snb_secondary_function_codes").append(optObj.windows.secondary_function);
$("#snb_site_locations").append(optObj.windows.site_location);
$("#snb_dc_offpremise_codes").append(optObj.windows.dc_offpremise);
}else{
$("#snb_secondary_activity_codes").append(optObj.unix.secondary_activity);
$("#snb_primary_function_codes").append(optObj.unix.primary_function);
$("#snb_secondary_function_codes").append(optObj.unix.secondary_function);
$("#snb_site_locations").append(optObj.unix.site_location);
$("#snb_dc_offpremise_codes").append(optObj.unix.dc_offpremise);
}
}
};
})();
Thanks in advance.

Get json data based on url

I have a problem with getting the specific data based on my id.
This is my main html.
<div class="container">
<div class="row">
<div class="col-md-12">
<button id="btn">Button</button>
<br>
<div id="id01"></div>
</div>
</div>
</div>
This is my main js
var btn=document.getElementById("btn");
btn.addEventListener("click", function(){
var ourRequest = new XMLHttpRequest();
var url = "url.../incident";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
});
function myFunction(response) {
var arr = JSON.parse(response);
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Address +
"</td><td><a href='lista.html?id="+arr[i].ID+"'>" +
arr[i].ID +
"</a></td><td>" +
arr[i].Category +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
This will show me only three data.
this is my lista.html
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="id02">
</div>
</div>
</div>
And this is my js for my lista.html.
var ourRequest = new XMLHttpRequest();
var url = "url../incident?id=";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function()
{
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
function myFunction(response)
{
var arr = JSON.parse(response);
var out = "<table>";
out +="<tr><td>" +
arr.Address +
"</td><td>" +
arr.CaseID +
"</td><td>" +
arr.Category +
"</td><td>" +
arr.Date +
"</td><td>" +
arr.Description +
"</td><td>" +
arr.ID +
"</td><td>" +
arr.InputDate +
"</td><td>" +
arr.Latitude +
"</td><td>" +
arr.Longitude +
"</td><td>" +
arr.ReportedBy +
"</td><td>" +
arr.Subcategory +
"</td><td>" +
arr.Time +
"</td></tr>"
out += "</table>";
document.getElementById("id02").innerHTML = out;
}
So when I click on that arr[i].ID it should send me to th lista.html with the specific ID and specific data.
For example if i click on ID=1, the url look like lista.html?id=1, but nothing shows.
Just pass the id to the request url if the api you send request to expects that
var url = "url?id={your id here}"
In your table you have to use arr.Address instead of response.Address, since the arr is the parsed json object.
You can use console.log to see if the data you need is really there:
function myFunction(response) {
var arr = JSON.parse(response);
console.log(arr);
}
You don't need to read the location href with jQuery, since you already know the id of the request you sent!
So My mistake was like this instead of :
var url = "url../incident?id=";
I should have written :
var url = "url../incident?id="+getQueryVariable("id");
And write this function in the end of my js for my lista.html
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}

getting XMLHttpRequest cannot load (URL) Response for preflight is invalid (redirect)

here am trying to get reccurring events from calendar list for sharepoint Online app and there am using code as like
hostWebUrl = decodeURIComponent(manageQueryStringParameter('SPHostUrl'));
function GetListData() {
var webUrl = hostWebUrl;// = "http://server/sitewhereyourlistexists";
var listGuid = "{2000da75-8663-42d9-9999-ad855c54b4e0}"
// An XMLHttpRequest object is used to access the web service
var xhr = new XMLHttpRequest();
var url = webUrl + "/_vti_bin/Lists.asmx";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xhr.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/sharepoint/soap/GetListItems");
// The message body consists of an XML document
// with SOAP elements corresponding to the GetListItems method parameters
// i.e. listName, query, and queryOptions
var data = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" +
"<soap:Body>" +
"<GetListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">" +
"<listName>" + listGuid + "</listName>" +
"<query>" +
"<Query><Where>" +
"<DateRangesOverlap>" +
"<FieldRef Name=\"EventDate\"/>" +
"<FieldRef Name=\"EndDate\"/>" +
"<FieldRef Name=\"RecurrenceID\"/>" +
"<Value Type=\"DateTime\"><Today/></Value>" +
"</DateRangesOverlap>" +
"</Where></Query>" +
"</query>" +
"<queryOptions>" +
"<QueryOptions>" +
"<ExpandRecurrence>TRUE</ExpandRecurrence>" +
"</QueryOptions>" +
"</queryOptions>" +
"</GetListItems>" +
"</soap:Body>" +
"</soap:Envelope>";
// Here we define what code we want to run upon successfully getting the results
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var doc = xhr.responseXML;
// grab all the "row" elements from the XML results
var rows = doc.getElementsByTagName("z:row");
var results = "Today's Schedule (" + rows.length + "):\n\n";
var events = {};
for (var i = 0, len = rows.length; i < len; i++) {
var id = rows[i].getAttribute("ows_FSObjType"); // prevent duplicates from appearing in results
if (!events[id]) {
events[id] = true;
var allDay = rows[i].getAttribute("ows_fAllDayEvent"),
title = rows[i].getAttribute("ows_Title"),
start = rows[i].getAttribute("ows_EventDate");
var index = start.indexOf(" ");
var date = start.substring(5, index) + "-" + start.substring(2, 4); // get the date in MM-dd-yyyy format
start = start.substring(index, index + 6); // get the start time in hh:mm format
var end = rows[i].getAttribute("ows_EndDate");
index = end.indexOf(" "); end = end.substring(index, index + 6); // get the end time in hh:mm format
results += date + " " + (allDay == "1" ? "All Day\t" : start + " to " + end) + " \t " + title + "\n";
}
}
alert(results);
} else {
alert("Error " + xhr.status);
}
}
};
// Finally, we actually kick off the query
xhr.send(data);
}
after calling this function in decument. ready section it is not retrieving any data but there is ine error which i can see in console of browser that is as below
You will click on the correct request in the left hand side panel, then select "Inspectors" in the right hand side top panel. Then choose between the different request and response options.

Ajax using jquery works on IE but not Firefox

My end goal is to have a home page that pulls RSS feeds and displays them on my home page for my personal website. This is all done from the client side and I'm not looking to build a server site script to do this (I will though only if no other way is possible).
Below is the page load code. (I don't think this is a problem area but it nice to see the starting point)
$(document).ready(function () { // Here
loadpageF(); //<- problems is in this function
GetBackGround(document.body); //this just messes with the css of the site
});
function loadpageF() {
addTableFeed("http://www.npr.org/rss/rss.php?id=1001");
addTableFeed("http://news.yahoo.com/rss/odd");
addTableFeed("http://www.nfl.com/rss/rsslanding?searchString=team&abbr=DAL");
addTableFeed("http://www.npr.org/rss/rss.php?id=1007");
$(".MainArea").css("width",$("iframe").length * (270));
}
//This function sets up where the RSS data will be place after formatting
function addTableFeed(feedlink) {
var numOfCell = maintb.getElementsByTagName("iframe").length;
maintb.innerHTML += "<iframe id='f" + numOfCell + "' class='iframeFeed'></iframe>";
getRSSFeed(feedlink, "f" + numOfCell);
}
This code basically calls a function for each rss to add and iframe and the passes the iframe id and the URL to another function (shown below and I am 99% sure is the problem) which getting the data.
function getRSSFeed(feedlink, iframeid) {
/*var xmlhttp; old way I did it below realizing it did not work in firefox
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var hold = xmlhttp.responseText
loadData(hold, iframeid);
}
}
xmlhttp.open("get", feedlink, false);
xmlhttp.send();*/ //end of the old way
//new way to try to use JSON of course failing at my in goal
$.ajax({
type: "GET",
url: feedlink,
async: true,
dataType: "text",
success: function(data){
loadData(data, iframeid);
},
error: function(data, statusCode) {
alert("ERROR: "+data.error)
}
});}
The function loadData works fine when called, however it is not called for the Yahoo.com and NFL.com feed. Instead I get an alert as shown below.
//Note I has to transcribe from dialog box there may be errors
ERROR: function () {
if( list ) {
// First, we save the current length
var start = list length;
(function add( args ) {
jQuery.each( args, function( _, arg ) {
¡f( jQuery.isFunction( arg ) && (!options unique || self.has( arg)
list .push( arg);
else if( arg && arg.length ) {
// Inspect recursively
add( arg);
}
});
})( arguments);
//Do we need to add the callbacks to the
// current firing batch?
if (firing ) (
firingLength = list length;
//wiIh memory, if we’re not firing then
// we should call right away
J else if ( memory ) (
firingstart = start;
fire( memory);
Just in case it is needed, below is the load data code.
function loadData(xml, ifid) {
var htmlStr;
var artCount = 0;
var $xml = $($.parseXML(xml));
$("#" + ifid)[0].contentDocument.open();
$("#" + ifid)[0].contentDocument.close();
$("#" + ifid)[0].contentDocument.write("<head><link rel='Stylesheet' type='text/css' href='" + document.getElementById("StyleSheet").href + "' /></head>");
//RSS 2.0 handler
$xml.find("channel item").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("description").text();
var link = $article.find("link").text();
var pubDate = $article.find("pubDate").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" +artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//Atom 1.0 handler
$xml.find("feed entry").each(function () {
var $article = $(this);
var title = $article.find("title").text();
var description = $article.find("summary").text();
var link = $article.find("link").attr("href");
var pubDate = $article.find("published").text();
htmlStr = "<div id='" + artCount + "Span" + ifid + "' class='ArticalHead'><h3>" + title + "</h3></div>\n";
htmlStr += "<div class='ArticalBody' id='" + artCount + "Div" + ifid + "'>\n";
htmlStr += "\t<p>" + description + "</p><a href='" + link + "' target='_blank' > Click Here For more </a>\n";
htmlStr += "\t<h6>" + pubDate + "</h6><br />\n";
htmlStr += "</div>\n"
$("#" + ifid)[0].contentDocument.write(htmlStr);
$("#" + ifid).contents().find("#" + artCount + "Span" + ifid).click(function () {
$("#" + ifid).contents().find("#" + $(this).attr("id").replace("Span", "Div")).toggle();
});
artCount++;
});
//$("#" + ifid).contents().find(".ArticalBody").hide();
}
Please forgive me for any typos or spelling errors. I can also post the whole web page if needed.

Categories