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...
Related
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...
}
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 need to know how can I get json data using JavaScript without using Jquery. I just want to know how to get data only using JavaScript.
My Json file.
{"JsonProjectIDResult":[{"_capacity":15,"_description":"Meeting Room","_dev_default_view":3,"_deviceID":1,"_deviceName":"MobiTech","_deviceTypeID":1,"_projectID":1,"_roomID":2,"_roomName":"Room2","_room_admin_mail":null}]}
My home.html file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript Get Json</title>
</head>
<body>
<h1>My Home Page</h1>
<div id="results">
<!-- Display Jason Data -->
</div>
<script>
var resultDiv = document.getElementById("results");
var newsURL = "http://localhost:81/testjs/data.json";
var e;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
e = new XMLHttpRequest();
} else {
// code for IE6, IE5
e = new ActiveXObject("Microsoft.XMLHTTP");
}
e.onreadystatechange = function() {
var html = " ";
if (e.readyState == 4 && e.status == 200) {
response = JSON.parse(e.responseText);
if(typeof(e.responseText)==="string") {
d = e.responseText;
} else {
if (typeof(e.responseXML)==="object") {
d = e.responseXML;
};
}
var myData = response['JsonProjectIDResult'];
//Print results
html = myData[0]._capacity+"<br />";
html += myData[0]._description+"<br />";
html += myData[0]._dev_default_view+"<br />";
html += myData[0]._deviceID+"<br />";
html += myData[0]._deviceName+"<br />";
html += myData[0]._deviceTypeID+"<br />";
html += myData[0]._projectID+"<br />";
html += myData[0]._roomID+"<br />";
html += myData[0]._roomName+"<br />";
html += myData[0]._room_admin_mail+"<br />";
resultDiv.innerHTML = html;
}
};
e.open("GET", newsURL, true);
e.send();
</script>
</body>
</html>
After my friends gave me some helpful answer I wondered my code like this. It's working. Now I need to run this as a loop. When every records display using a loop. Can I do it in JavaScript.
<script>
var resultDiv = document.getElementById("results");
var newsURL = "http://localhost:81/testjs/data.json";
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) {
response = JSON.parse(xmlhttp.responseText);
//here you can manipulate the response as you wish, for example you can:
var myData = response['JsonProjectIDResult'];
// myData now is an array of the json object
var html = '<ul>';
for(var prop in myData ) {
if(myData.hasOwnProperty(prop))
html += '<li>' + prop + ' = ' + myData[prop] + '</li>';
}
html += '</ul>';
//and so on
resultDiv.innerHTML = html;
}
}
xmlhttp.open("GET", newsURL, true);
xmlhttp.send();
</script>
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);
//...