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 :)
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...
}
Related
I have a button which increments a variable value, and I use this variable to load specific content. My problem is that after the page has loaded, I have to click 3 times for the first content load:
1st time I click: I get an undefined result because no ID is loaded
2nd time: the input field value from before I reload the page disappears
3rd time: the first content finally loads
Once the first content has loaded everything works fine. From what I understood it is because the variable isn't initalized at page loading. So I added an onload event but it doesn't work at all.
the script :
var Pokemon_ID = 1
function changePokemon(Pokemon_ID) {
function resetID() {
document.getElementById("id-input").innerHTML = Pokemon_ID;
}
document.getElementById("right-btn").onclick = function() {
Pokemon_ID++;
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
document.getElementById("left-btn").onclick = function() {
if (Pokemon_ID > 1) {
Pokemon_ID--;
}
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { //IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var parts = xmlhttp.responseText.split('|')
document.getElementById("img").innerHTML = parts[0];
document.getElementById("name").innerHTML = parts[1];
document.getElementById("type-display1").innerHTML = parts[2];
document.getElementById("categorie").innerHTML = "Categorie: " + parts[3];
document.getElementById("talent").innerHTML = "Talent: " + parts[4];
document.getElementById("taille").innerHTML = "Taille: " + parts[5];
document.getElementById("poids").innerHTML = "Poids: " + parts[6];
}
}
xmlhttp.open("GET", "get_id.php?q=" + Pokemon_ID, true);
xmlhttp.send();
}
<div id="pokedex" onload="resetID()">
<a id="right-btn" onclick="changePokemon(this.value)"></a>
<a id="left-btn" onclick="changePokemon(this.value)"></a>
<form>
<input type="number" id="id-input" onclick="changePokemon(this.value)">
</form>
</div>
I also tried to declare my variable inside the changePokemon() function, but only the first id was loading I couldn't change the value of Pokemon_ID.
I tried to use const and let but both of them also didn't work
You use the same name Pokemon_ID for the global variable and the parameter to the changePokemon() function. The parameter is a local variable, so assignments to it don't affect the global variable. Give it a different name.
You need to take resetID() out of the changePokemon() function. It needs tobe in the global scope so it can be accessed from onclick.
To change an input, you need to assign to .value, not .innerHTML.
DIVs don't have a load event. You need to put onload="resetID()" in the <body> tag, or write:
window.onload = resetID;
in the Javascript.
var Pokemon_ID = 1
function resetID() {
document.getElementById("id-input").value = Pokemon_ID;
}
function changePokemon(Pokemon_val) {
document.getElementById("right-btn").onclick = function() {
Pokemon_ID++;
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
document.getElementById("left-btn").onclick = function() {
if (Pokemon_ID > 1) {
Pokemon_ID--;
}
document.getElementById("id-input").value = Pokemon_ID;
document.getElementById("id-input").click();
}
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { //IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var parts = xmlhttp.responseText.split('|')
document.getElementById("img").innerHTML = parts[0];
document.getElementById("name").innerHTML = parts[1];
document.getElementById("type-display1").innerHTML = parts[2];
document.getElementById("categorie").innerHTML = "Categorie: " + parts[3];
document.getElementById("talent").innerHTML = "Talent: " + parts[4];
document.getElementById("taille").innerHTML = "Taille: " + parts[5];
document.getElementById("poids").innerHTML = "Poids: " + parts[6];
}
}
xmlhttp.open("GET", "get_id.php?q=" + Pokemon_val, true);
xmlhttp.send();
}
<div id="pokedex" onload="resetID()">
<a id="right-btn" onclick="changePokemon(this.value)"></a>
<a id="left-btn" onclick="changePokemon(this.value)"></a>
<form>
<input type="number" id="id-input" onclick="changePokemon(this.value)">
</form>
</div>
I have a javascript function that reads an xml. From that function, it calls a second function to prompt the user to update the start price value. It successfully does it the first time then has this error.
2
Uncaught RangeError: Maximum call stack size exceeded.
43
Uncaught InvalidStateError: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
I am not sure what is going on here? Is it a recursion problem? If so, how can i solve this?
This is the javascript:
var xmlhttp=false;
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
function loadXMLDoc()
{
var table
var i;
xmlhttp.open("GET","auction.xml",false);
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
table=("<table border='1'><tr><th>Item Name</th><th>Category</th><th>Start Price</th></tr>");
var x=xmlDoc.getElementsByTagName("Product");
for (i=0;i<x.length;i++)
{
table+=("<tr><td>");
table+=(x[i].getElementsByTagName("ItemName")[0].childNodes[0].nodeValue);
iname=(x[i].getElementsByTagName("ItemName")[0].childNodes[0].nodeValue);
table+=("</td><td>");
table+=(x[i].getElementsByTagName("Owner")[0].childNodes[0].nodeValue);
iowner=(x[i].getElementsByTagName("Owner")[0].childNodes[0].nodeValue);
//document.getElementById('test').innerHTML=iowner;
table+=("</td><td>");
table+=(x[i].getElementsByTagName("StartPrice")[0].childNodes[0].nodeValue);
table+=("</td><td>");
table+="<input type=\"submit\" onclick=\"itembid('"+ iname + "','"+ iowner +"')\" value=\"Bid\">";
table+=("</td></tr>");
}
table+=("</table>");
document.getElementById('listinglist').innerHTML=table;
}
function itembid(iname,iowner)
{
var newbid = prompt("Please enter your bidding price");
var itemname = iname;
var ownername = iowner;
//document.getElementById('test').innerHTML=ownername;
//document.getElementById('test').innerHTML="AA";
xmlhttp.open("GET", "readxml.php?newbid=" + encodeURIComponent(newbid) + "&itemname=" + encodeURIComponent(itemname) + "&ownername=" + encodeURIComponent(ownername) +"&date="+ Number(new Date), true);
xmlhttp.onreadystatechange = loadXMLDoc;
xmlhttp.send();
}
You need to have a new request for reach request so try
function getXmlHttp() {
var xmlhttp = false;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
function loadXMLDoc() {
if (this.readyState != 4 || this.status != 200) {
return;
}
var table
var i;
var xmlhttp = getXmlHttp();
xmlhttp.open("GET", "auction.xml", false);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState != 4 || xmlhttp.status != 200) {
return;
}
var xmlDoc = xmlhttp.responseXML;
table = ("<table border='1'><tr><th>Item Name</th><th>Category</th><th>Start Price</th></tr>");
var x = xmlDoc.getElementsByTagName("Product");
for (i = 0; i < x.length; i++) {
table += ("<tr><td>");
table += (x[i].getElementsByTagName("ItemName")[0].childNodes[0].nodeValue);
iname = (x[i].getElementsByTagName("ItemName")[0].childNodes[0].nodeValue);
table += ("</td><td>");
table += (x[i].getElementsByTagName("Owner")[0].childNodes[0].nodeValue);
iowner = (x[i].getElementsByTagName("Owner")[0].childNodes[0].nodeValue);
//document.getElementById('test').innerHTML=iowner;
table += ("</td><td>");
table += (x[i].getElementsByTagName("StartPrice")[0].childNodes[0].nodeValue);
table += ("</td><td>");
table += "<input type=\"submit\" onclick=\"itembid('" + iname + "','" + iowner + "')\" value=\"Bid\">";
table += ("</td></tr>");
}
table += ("</table>");
document.getElementById('listinglist').innerHTML = table;
};
xmlhttp.send();
}
function itembid(iname, iowner) {
var newbid = prompt("Please enter your bidding price");
var itemname = iname;
var ownername = iowner;
//document.getElementById('test').innerHTML=ownername;
//document.getElementById('test').innerHTML="AA";
var xmlhttp = getXmlHttp();
xmlhttp.open("GET", "readxml.php?newbid=" + encodeURIComponent(newbid) + "&itemname=" + encodeURIComponent(itemname) + "&ownername=" + encodeURIComponent(ownername) + "&date=" + Number(new Date), true);
xmlhttp.onreadystatechange = loadXMLDoc;
xmlhttp.send();
}
I am getting some information from database, this information is getting back into JSON format now I need to print this JSON information. But my code is not working getCountryDetails.php is php file for interacting with the database. Following code is the script, When I click the button It intersects with database.
<script type="text/javascript">
$(document).ready(function() {
$("#quickSearch").click(function(){
var countries = [];
$.each($("#select-choice-1 option:selected"), function(){
countries.push($(this).val());
});
if (countries == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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) {
//myFunction(xmlhttp.responseText);
myFunction(xmlhttp.responseText);
}
}
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
xmlhttp.open("GET","webservices/getCountryDetails.php?q="+countries,true);
xmlhttp.send();
}
});
});
function myFunction(response) {
var arr = JSON.parse(response);
var i;
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Name +
"</td><td>" +
arr[i].City +
"</td><td>" +
arr[i].Country +
"</td></tr>";
}
out += "</table>"
document.getElementById("id01").innerHTML = out;
}
</script>
Firstly, countries will never be an empty string, you've defined it as an array
var countries = [];
...
if (countries == "") { // always fail
secondly, you can't concantenate an array into a string, and XMLHttpRequest doesn't accept arrays
xmlhttp.open("GET","webservices/getCountryDetails.php?q=" + countries, true);
Thirdly, you seem to be using jQuery, so why not use it as it does accept an array
$.ajax({
url : 'webservices/getCountryDetails.php',
data : countries
}).done(myFunction);
I'm trying to dynamically generate a table with JavaScript using AJAX and displayed using Bootstrap but I can't seem to get the table to show.It only shows the header fields. Any help would be greatly appreciated.
<button onclick="display();">Generate Table</button>
<div id="myTable"></div>
function display(){
var HTML = "<table class='table table-striped table-bordered table-hover' style='width:500px'>";
HTML += "<tr><th>Place</th><th>Description</th></tr>";
var search = 106;
makeRequest('findplace.php?searchbynumber='+search,function(data){
var data = JSON.parse(data.responseText);
for(var i = 0;i<data.length;i++){
HTML += "<tr><td>" + data[i].place + "</td><td>" + data[i].description + "</td></tr>";
}
});
HTML += "</table>";
document.getElementById('myTable').innerHTML = HTML;
}
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
As Tim says in the comment, this is to do with the asynchronous nature of the call you're making in makeRequest.
You essentially build the outside of the table and add that the HTML, then the callback is called later, builds up a new variable and never does anything with it.
You have a number of options, but the simplest is probably to move the creation of the HTML into the callback and build it in one go on return from the onreadychangestate and you have everything you need to output.
I.E. Move ALL the HTML construction into your callback and the problem should go away:
function display(){
var search = 106;
makeRequest('findplace.php?searchbynumber='+search,function(data){
var HTML = "<table class='table table-striped table-bordered table-hover' style='width:500px'>";
HTML += "<tr><th>Place</th><th>Description</th></tr>";
var data = JSON.parse(data.responseText);
for(var i = 0;i<data.length;i++){
HTML += "<tr><td>" + data[i].place + "</td><td>" + data[i].description + "</td></tr>";
}
HTML += "</table>";
document.getElementById('myTable').innerHTML = HTML;
});
}
function makeRequest(url, callback) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest(); // IE7+, Firefox, Chrome, Opera, Safari
} else {
request = new ActiveXObject("Microsoft.XMLHTTP"); // IE6, IE5
}
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
callback(request);
}
}
request.open("GET", url, true);
request.send();
}
As for other options:
As one idea, you could build the outside of the table as you do, but with a "Loading..." bit of text in there and then add the rows in the callback - but if you're looking for that I'd say that's an exercise for the reader...
I have an AJAX function which loads content from a file and displays in the file that called it.
But the script that was called I want to loop an array which is actually set in the script that called it... this is main script that calls the file:
function call_file(file, div_id) {
var xmlhttp;
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) {
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", file, true);
xmlhttp.send();
}
var global = new Array();
global[0] = 1;
global[1] = 2;
call_script('html.html', 'main');
html.html is the file that is called which has this:
<script>
i = 0;
for(var id in global) {
alert(i + ' = ' + id);
i++;
}
</script>
Is this at all possible?
One way is to extract the script and eval it yourself. For example:
//....
document.getElementById(div_id).innerHTML = xmlhttp.responseText;
var str = xmlhttp.responseText;
var reg = /<script>([^>]*)<\/script>/img;
while(reg.test(str))eval(RegExp.$1);
//...