user3102785 user3102785 - 7 months ago 10
Javascript Question

Only one JavaScript function loading on page load.

I have a webpage with a few JavaScript functions set to load on document.ready.

However, if I have 4 of these, only the final one seems to load.

Here is the code I have.

$(document).ready(function ()
{
var nation = "ireland";
var irelandMatches = [];
var matchOrderReversed = false;

loadDoc();
showRSS("Irish Times");
loadWeather();
loadTwitter();


The loadDoc() and loadTwitter() methods load, but weather and showRSS do not. If I comment out loadTwitter(), then the weather loads fine.

If it makes any difference, all of these methods make use of an XMLHttpRequest, each of which is defined within each method, like so.

function loadYouTube()
{
var html = "";

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 ret = xmlhttp.responseText;
var spl1 = ret.split("~");

for (i = 0; i <= 10; i++)
{
var spl2 = spl1[i].split("*");
var current = "<a href='" + spl2[1] + "'><img src='" + spl2[2] + "' width='50' height='50'>" + "<a href='" + spl2[1] + "'>" + spl2[0] + "</a> <br/>";
html += current;
}

$("#yt").html(html);
}
}

xmlhttp.open("GET", "getyoutube.php?", true);
xmlhttp.send();
}


Thanks guys :)

Answer

It looks like when you define xmlhttp in your loadYouTube() example, you are doing so on the global scope due to the lack of var. So loadDoc() sets window.xmlhttp, then loadWeather() overwrites it shortly after, followed by loadTwitter().

Try something like this in your loading functions:

function loadYouTube()
    {
        var html = "";

        // define xmlhttp in block scope
        var xmlhttp;

        // rest of function...
    }