How to print xmlhttp response? - javascript

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);

Related

Json parser and loop scheme

How can I loop my json file using my script, eg: I should choose whether to loop Schema A or Schema B.
My json file is:
{
"A":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
],
"B":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
]
}
Maybe setting a variable so as to define the scheme I have to display
My javascript file is:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj= JSON.parse(this.responseText);
myFunction(obj, 'A');
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(obj, key) {
var arr = obj[key];
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
Assuming that what you presented as JSON file is a response form network and is passed to myFunction, then why not to do something like:
let myRootArray;
if(/* some confitions */) {
myRootArray = myArr.A
} else {
myRootArray = myArr.B
}
myFunction(myRootArray );
Beside that, your names are a bit confusing, var myArr = JSON.parse(this.responseText);, while JSON.parse will return object, not an array.

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 :)
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...
}

AJAX Maximum call stack size exceeded

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();
}

Generate Table dynamically with AJAX data using Javascript

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...

Parsing or using variables from a called 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);
//...

Categories