Re: Scores not updating
Posted: Sun Oct 21, 2018 9:03 am
Thanks @BobbyG63. I have this working now. Now have formWeek defined and set to what is coming from the form selection and the xmlweek variable set to the week value for the xml feed. Also watching the underlying network results, I can see that based on the week selected, the score updates are going to the proper feed (main XML URL for current week and the secondary URL for other weeks). Many thanks for the updates and post of the full code.
For anyone wanting to use this, I did run into some issues that I had to tweak. They all look to be coming from the paste. Going to try and paste here "as code" and hopefully that takes care of it for easy copy/paste. The issues I had to fix from the changes caused by the paste are noted below just in case anyone runs into the same, then you can check these areas.
Again, a big thanks to BobbyG63 for getting this working.
For anyone wanting to use this, I did run into some issues that I had to tweak. They all look to be coming from the paste. Going to try and paste here "as code" and hopefully that takes care of it for easy copy/paste. The issues I had to fix from the changes caused by the paste are noted below just in case anyone runs into the same, then you can check these areas.
- The secondary URL (for non-current weeks) got condensed, so had to get the full URL added.
Around line 98 in the code, the 's were removed in the "domutils" lines.
Around line 168ish where the first line is "var gameEls = xmlDoc.getElementsByTagName("g");", similar thing with the 's. I replaced the whole section from my previous updateScores.aps page that line down to last closing bracket (just above the commented out line that reads // Copy any new results to the appropriate form fields and reset).
Note that in the pasted code below, I started at the same place BobbyG63 did in his paste ("module: scoresLoader" section around line 22) and went all the way down to the end of the script code ( the "end if" statement around line 553).
Again, a big thanks to BobbyG63 for getting this working.
Code: Select all
//=========================================================================
// Module: scoresLoader
//
// Used to set game scores using data retrieved from the NFL.com web site.
//=========================================================================
var scoresLoader = function () {
// The update form.
var formEl = null;
// The week to update.
var week = "";
// Define an array to hold form field information for each game listed
// on the form.
var gameFields = [];
// Auto-update parameters.
var autoUpdate = false;
var autoUpdateLoadTimeoutID = null;
var autoUpdateLoadTimeout = 300000; // 5 minutes.
var autoUpdateDialogTimeout = 500; // one half second.
// Holds the data parsed from the scores page.
var gameData = null;
// Used for dialog messages.
var resultMsg = "";
var errorMsg = "";
var foundNewResults = false;
//---------------------------------------------------------------------
// Initializes the scores loader.
//---------------------------------------------------------------------
function init() {
// Get the scores update form.
formEl = document.getElementById("scoresForm");
// Get the week.
week = formEl.elements["week"].value;
// Scan the form and build the games fields array.
var i = 1;
var el;
while ((el = formEl.elements["id-" + i]) != null) {
var vid = formEl.elements["vid-" + i].value;
var hid = formEl.elements["hid-" + i].value;
var vscoreEl = formEl.elements["vscore-" + i];
var hscoreEl = formEl.elements["hscore-" + i];
var otEl = formEl.elements["ot-" + i];
gameFields.push({
"visitorID" : vid,
"visitorScoreEl" : vscoreEl,
"homeID" : hid,
"homeScoreEl" : hscoreEl,
"overtimeEl" : otEl
});
i++;
}
// If auto-update is checked, start it.
autoUpdate = formEl.elements["autoUpdate"].checked;
if (autoUpdate)
autoUpdateLoadTimeoutID = setTimeout(getScores, autoUpdateLoadTimeout);
}
//---------------------------------------------------------------------
// Initiates the retrieval of game results.
//---------------------------------------------------------------------
function getScores() {
// Clear any existing game data.
gameData = [];
// Clear any highlighting on the form fields.
for (var i = 0; i < gameFields.length; i++) {
domUtils.removeClass(gameFields[i].visitorScoreEl, "fieldLoaded");
domUtils.removeClass(gameFields[i].homeScoreEl, "fieldLoaded");
domUtils.removeClass(gameFields[i].overtimeEl.parentNode, "fieldLoaded");
}
// Initialize the display.
foundNewResults = false;
showLoadingDisplay("loadingActive");
processXMLScores();
return false;
}
//---------------------------------------------------------------------
// Get NFL Data Feeds.
//---------------------------------------------------------------------
function getDataFeed(url) {
var resp ;
var xmlHttp ;
resp = '' ;
xmlHttp = new XMLHttpRequest();
if(xmlHttp != null)
{
xmlHttp.open( "GET", url, false );
xmlHttp.send( null );
resp = xmlHttp.responseText;
}
return resp ;
}
//---------------------------------------------------------------------
// Parses the scores page and updates the form with any new game
// results.
//---------------------------------------------------------------------
function processXMLScores() {
var vid, hid, vscore, hscore;
var s, ot
var el, el2;
var vn, hn;
var formWeek = formEl.elements["week"].value;
var xmlURL = "http://www.nfl.com/liveupdate/scorestrip/ss.xml"
var myData = getDataFeed(xmlURL);
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(myData, "text/xml");
var gameEls = xmlDoc.getElementsByTagName("gms");
if (gameEls.length > 0) {
var xmlWeek = gameEls[0].getAttribute("w");
var xmlYear = gameEls[0].getAttribute("y");
var xmlType = gameEls[0].getAttribute("t");
}
if (formWeek != xmlWeek) {
var xmlURL = "http://www.nfl.com/ajax/scorestrip?season=2018&seasonType=REG&week="+formWeek;
var myData = getDataFeed(xmlURL);
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(myData, "text/xml");
}
var gameEls = xmlDoc.getElementsByTagName("g");
for (var i = 0; i < gameEls.length; i++) {
ot = false;
s = gameEls[i].getAttribute("q");
if ((s != null) && ((s.trim().toLowerCase() == "f") || (s.trim().toLowerCase() == "fo"))) {
vid = gameEls[i].getAttribute("v");
vscore = gameEls[i].getAttribute("vs");
hid = gameEls[i].getAttribute("h");
hscore = gameEls[i].getAttribute("hs");
if (s.trim().toLowerCase() == "fo") {
ot = true;
}
// Fix team IDs.
if (vid == "JAC")
vid = "JAX";
if (hid == "JAC")
hid = "JAX";
// Save the results.
gameData.push({
"visitorID" : vid,
"visitorScore" : vscore,
"homeID" : hid,
"homeScore" : hscore,
"overtime" : ot
});
}
}
// Copy any new results to the appropriate form fields and reset
// the display.
setGameFields();
if (foundNewResults) {
hideLoadingDisplay();
// If auto-update is on, submit the form to update the scores.
if (autoUpdate) {
// Add a new submit button to the form and click it to
// perform the update.
var inputEl = document.createElement("INPUT");
inputEl.name = "submit";
inputEl.type = "submit";
inputEl.value = "Update";
inputEl = formEl.appendChild(inputEl);
inputEl.click();
}
}
else {
showLoadingDisplay("loadingComplete");
// Handle auto-update.
if (autoUpdate) {
setTimeout(hideLoadingDisplay, autoUpdateDialogTimeout);
// Determine if any scores are still missing.
var missingScores = false;
for (i = 0; i < gameFields.length && !missingScores; i++)
if (gameFields.visitorScoreEl.value == "" || gameFields.homeScoreEl.value == "")
missingScores = true;
// If there are missing scores, set for the next attempt.
// Otherwise off turn auto-update.
if (missingScores)
autoUpdateLoadTimeoutID = setTimeout(getScores, autoUpdateLoadTimeout);
else
stopAutoUpdate();
}
}
}
//---------------------------------------------------------------------
// Grabs the scores from the NFL JSON feed
// Does not allow for Year / Season / Week selection.
// Only returns "Current" week info
//---------------------------------------------------------------------
function processJSONScores() {
var vid, hid, vscore, hscore;
var s, ot
var el, el2;
var vn, hn;
var mydata = getDataFeed("http://www.nfl.com/liveupdate/scorestrip/ss.json")
var jsonData = JSON.parse(mydata);
for (var i = 0; i < jsonData.gms.length; i++) {
var counter = jsonData.gms[i];
ot = false;
s = (counter.q);
if ((s != null) && ((s.trim().toLowerCase() == "f") || (s.trim().toLowerCase() == "f ot"))) {
vid = (counter.v);
vscore = (counter.vs);
hid = (counter.h);
hscore = (counter.hs);
if (s.trim().toLowerCase() == "f ot") {
ot = true;
}
// Fix team IDs.
if (vid == "JAC")
vid = "JAX";
if (hid == "JAC")
hid = "JAX";
// Save the results.
gameData.push({
"visitorID" : vid,
"visitorScore" : vscore,
"homeID" : hid,
"homeScore" : hscore,
"overtime" : ot
});
}
}
// Copy any new results to the appropriate form fields and reset
// the display.
setGameFields();
if (foundNewResults) {
hideLoadingDisplay();
// If auto-update is on, submit the form to update the scores.
if (autoUpdate) {
// Add a new submit button to the form and click it to
// perform the update.
var inputEl = document.createElement("INPUT");
inputEl.name = "submit";
inputEl.type = "submit";
inputEl.value = "Update";
inputEl = formEl.appendChild(inputEl);
inputEl.click();
}
}
else {
showLoadingDisplay("loadingComplete");
// Handle auto-update.
if (autoUpdate) {
setTimeout(hideLoadingDisplay, autoUpdateDialogTimeout);
// Determine if any scores are still missing.
var missingScores = false;
for (i = 0; i < gameFields.length && !missingScores; i++)
if (gameFields[i].visitorScoreEl.value == "" || gameFields[i].homeScoreEl.value == "")
missingScores = true;
// If there are missing scores, set for the next attempt.
// Otherwise off turn auto-update.
if (missingScores)
autoUpdateLoadTimeoutID = setTimeout(getScores, autoUpdateLoadTimeout);
else
stopAutoUpdate();
}
}
}
//---------------------------------------------------------------------
// Given an element, finds the first occurrence of the given tag with
// the given class name in its descendants.
//---------------------------------------------------------------------
function getFirstSubTagWithClass(el, tName, cName) {
if (el != null) {
var elList = el.getElementsByTagName(tName);
for (var i = 0; i < elList.length; i++)
if (domUtils.hasClass(elList[i], cName))
return elList[i];
}
return null;
}
//---------------------------------------------------------------------
// Given an element, finds the first occurrence of the given tag in
// its descendants.
//---------------------------------------------------------------------
function getFirstSubTag(el, tName) {
if (el != null) {
var elList = el.getElementsByTagName(tName);
if (elList.length > 0)
return elList[0];
}
return null;
}
//---------------------------------------------------------------------
// Given a url, returns the value assigned to the given query string
// parameter.
//---------------------------------------------------------------------
function getQueryStringParameter(qs, pName) {
var re = new RegExp( "[?&]" + pName + "=([^&$]*)", "i" );
var offset = qs.search(re);
if (offset == -1)
return "";
return RegExp.$1;
}
//---------------------------------------------------------------------
// Takes the parsed game results and updates the appropriate form
// fields.
//---------------------------------------------------------------------
function setGameFields() {
// For each game result found, find a matching set of form fields
// to load the data into.
if (gameData.length > 0) {
resultMsg = "All game results are up to date.";
for (var i = 0; i < gameFields.length; i++)
for (var j = 0; j < gameData.length; j++)
// Check if the teams match.
if (gameFields[i].visitorID == gameData[j].visitorID && gameFields[i].homeID == gameData[j].homeID)
{
// Set the individual form fields.
setFormField(gameFields[i].visitorScoreEl, gameData[j].visitorScore);
setFormField(gameFields[i].homeScoreEl, gameData[j].homeScore);
setFormField(gameFields[i].overtimeEl, gameData[j].overtime);
break;
}
}
else
resultMsg = "No results available, try again later.";
}
//---------------------------------------------------------------------
// Updates a single form field with the given value (if that value is
// different from the field's current value).
//---------------------------------------------------------------------
function setFormField(fieldEl, newValue) {
// Compare the old and new values.
var oldValue = fieldEl.value;
if (fieldEl.type == "checkbox")
oldValue = fieldEl.checked;
// If the values are the same, exit.
if (oldValue == newValue)
return;
// Set the form field value and highlight it.
if (fieldEl.type == "checkbox") {
fieldEl.checked = newValue;
domUtils.addClass(fieldEl.parentNode, "fieldLoaded");
}
else {
fieldEl.value = newValue;
domUtils.addClass(fieldEl, "fieldLoaded");
}
// Note that we have new results.
foundNewResults = true;
}
//---------------------------------------------------------------------
// Shows the loading display with the specified message box.
//---------------------------------------------------------------------
function showLoadingDisplay(id) {
// Hide all the message boxes.
document.getElementById("loadingActive").style.display = "none";
document.getElementById("loadingComplete").style.display = "none";
document.getElementById("loadingError").style.display = "none";
// Set the result and error messages.
var el = document.getElementById("loadingResultMsg");
while (el.firstChild != null)
el.removeChild(el.firstChild);
document.getElementById("loadingResultMsg").appendChild(document.createTextNode(resultMsg));
var el = document.getElementById("loadingErrorMsg");
while (el.firstChild != null)
el.removeChild(el.firstChild);
document.getElementById("loadingErrorMsg").appendChild(document.createTextNode(errorMsg));
// Show the specified message box.
el = document.getElementById(id);
if (el != null)
el.style.display = "";
// Make it visible.
document.getElementById("loadingDisplay").style.visibility = "visible";
}
//---------------------------------------------------------------------
// Hides the loading display.
//---------------------------------------------------------------------
function hideLoadingDisplay() {
document.getElementById("loadingDisplay").style.visibility = "hidden";
}
//---------------------------------------------------------------------
// Turns auto-update off.
//---------------------------------------------------------------------
function stopAutoUpdate() {
// Cancel any pending attempt.
if (autoUpdateLoadTimeoutID != null) {
clearTimeout(autoUpdateLoadTimeoutID);
autoUpdateLoadTimeoutID = null;
}
// Set the flag to false and clear the checkbox.
autoUpdate = false;
formEl.elements["autoUpdate"].checked = false;
}
//=====================================================================
// Initialization code.
//=====================================================================
// Initialize on page load.
domUtils.onready(init);
//=====================================================================
// Public properties and methods.
//=====================================================================
return {
//-----------------------------------------------------------------
// Loads game scores for the given week.
//-----------------------------------------------------------------
load : function () {
// Turn off auto-update, if it is on.
if (autoUpdate)
stopAutoUpdate();
getScores();
return false;
},
//-----------------------------------------------------------------
// Cancels a load.
//-----------------------------------------------------------------
cancel : function () {
getScoresCleanUp();
hideLoadingDisplay();
// If auto-update is on, turn it off.
if (autoUpdate)
stopAutoUpdate();
return false;
},
//-----------------------------------------------------------------
// Closes the load display.
//-----------------------------------------------------------------
close : function () {
hideLoadingDisplay();
return false;
},
//-----------------------------------------------------------------
// Toggles auto-update.
//-----------------------------------------------------------------
toggleAutoUpdate : function () {
// If auto-update is on, turn it off. Otherwise, turn it on and
// make an attempt.
if (autoUpdate)
stopAutoUpdate();
else {
autoUpdate = true;
getScores();
}
// Allow the check box to change.
return true;
}
}
}();
//]]></script>
<% end if %>