Ajax calls an array of four strings, I then want to print each string to a new line.
I have this code:
window.onload = function () {
var obj;
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj = JSON.parse(xmlhttp.responseText);
for (var i = 0; i <= obj.length; i++) {
document.createTextNode(obj[i]);
}
}
}
xmlhttp.open("GET", "verify.php", true);
xmlhttp.send();
}
However, it doesn't work. obj.length returns 4, I don't know whether the loop isn't executing, or if I can't access the DOM? I'm very new to Javascript and DOM scripting.
Thanks in advance.
You need to actually put the nodes into the document.
var node;
for (var i = 0, n = obj.length; i < n; i++) { // NB: not <=
node = document.createTextNode(obj[i]);
document.body.appendChild(node);
node = document.createElement('br');
document.body.appendChild(node);
}
This only creates the textNode, you must still apply it to the DOM somehwere via appendChild:
https://developer.mozilla.org/en/DOM/document.createTextNode
Related
I know this question has been asked before, but I tried to apply the answers with no results.
I'm trying to do multiple requests on the same domain with a for loop but it's working for the entire record of my array.
Here is the code I use:
function showDesc(str) {
var prod = document.getElementsByName("prod_item[]");
var xhr = [], i;
for (i = 0; i < prod.length; i++) {
var txtHint = 'txtHint10' + i;
(function(i) {
var xhr = new XMLHttpRequest();
var url = "getDesc.php?q=" + str;
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
document.getElementById(txtHint).innerHTML = xhr.responseText;
}
};
xhr.open("GET", url, false);
xhr.send();
})(i);
}
}
PHP
<select name="prod_item[]" id="prod_item.1" onchange="showDesc(this.options[this.selectedIndex].value)"></select>
<div id="txtHint100"></div>
and then I will use dynamic table for the prod_item field and div_id.
Is there any mistake in my code?
I've looked for the answers but couldn't find anything with plain Javascript. What would be the appropriate way? I tried to use the same approach repetitively but it didn't work. How can I solve this with pure Javascript?
function someFunction(){
var url = "someUrl";
var xmlhttp = new XMLHttpRequest ();
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function (){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
obj = JSON.parse(xmlhttp.responseText);
length = obj.ajax.length;
for(var i = 0; i < length; i++ ){
try{
var someVar = obj.ajax.elements[i].id;
var url2 = "someOtherUrl"+someVar+"/features";
var xmlhttp = new XMLHttpRequest ();
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function (){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
obj2 = JSON.parse(xmlhttp.responseText);
length2 = obj2.ajax.length;
for(var j= 0; j < length2; j++){
var elementNames = obj2.elements[j].name;
}
}
}
}
}
}
You can call that someFunction() recursively. To do so, You just have to invoke that same function after 200 ok response.
In following code I've added a restriction to return form recursive callback stack after a fixed amount of requests in chain.
EDIT : for multiple urls
callDone = 0;
urls = ['http://url1','http://url2','http://url3'];
totalCall = urls.length - 1;
function someFunction(){
//Edit: > Fetch url from array
var url = urls[ callDone ] ;
var xmlhttp = new XMLHttpRequest ();
xmlhttp .open( "GET", url, true);
xmlhttp .send();
xmlhttp .onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
//your stuff with response...
if( callDone < totalCall ){
callDone++;
someFunction();
}
else{
return;
}
}
}
}
I have one input.txt file that have 3 columns like this:
1 0 0
2 8 8
3 272 280
4 462 742
5 702 1,444
6 990 2,434
7 1,326 3,760
8 1,691 5,451
9 2,200 7,651
10 2,640 10,291
...
I need a function (jQuery or javascript) to find a line on my input.txt and return to me the line that have the value in third column!
example:
HTML file
...
<script type="text/javascript">
var numberX = document.getElementById('id_x').value;
//FUNCTION
//var result = return of the function;
</script>
If numberX = 3,760 , the function open my file, check all last column until find the number and return 7, so result = 7
Thank you for all the help!
Try something like this:
var xhr = new XMLHttpRequest();
var data = null;
xhr.open("GET", "input.txt", true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
data = xhr.responseText.split('\n');
data = data.map(function(row) {
return row.split(/\s+/);
});
}
};
xhr.send();
var getRecord = function(lastValue) {
return data.find(function(row) {
return row[2] === lastValue;
})[0];
};
You would use it like so:
getRecord('3,760')
First of all, you need to find a way to read your file. Try it with XMLHttpRequest.
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "input.txt", false);
xhttp.send();
You real files with XMLHttpRequest object and process the result as string.
I have a quick plunker demo.
var value = '3,760';
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'data.txt');
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
var text = xmlhttp.responseText;
var rows = text.split('\n');
for (var i = 0; i < rows.length; i++) {
var columns = rows[i].split(' ');
for (var j = 0; j < columns.length; j++) {
if (columns[j] == value)
alert(columns[0]);
}
}
}
}
xmlhttp.send();
https://plnkr.co/edit/5TlTltp0TaZi98IPF8Ii?p=preview
Everything is and is run on the same domain in the latest versions of the major browsers.
var xmlhttp = new XMLHttpRequest();
var sites = ["/page1", "/page2", "/page3"];
var cache = {};
function xhrStart(url) {
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function isOkXhr() {
return (xmlhttp.readyState == 4 &&
(xmlhttp.status >= 200 && xmlhttp.status < 300));
}
function reload() {
var len = sites.length;
var i;
for (i = 0; i < len; i++) {
var url = sites[i];
xmlhttp.onreadystatechange = function() {
if (isOkXhr())
cache[url] = xmlhttp.responseText;
}
xhrStart(url);
}
}
Reload function should be to cache all pages, but in fact all queries return Aborted in the debugger, except the last one. What could be the problem?
You are using one XHR object and keep writing over it in the loop. When you call open() it aborts the previous request. The for loop does not wait for the request.
Either create a new XHR request or wait til the other request is done before you make the next request.
var sites = ["/page1", "/page2", "/page3"];
var cache = {};
function xhrStart(url) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", url, true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status >= 200 && xmlhttp.status < 300) {
cache[url] = xmlhttp.responseText;
} else {
//what are you going to do for error?
}
}
};
xmlhttp.send();
}
for (var i = 0; i < sites.length; i++) {
var url = sites[i];
xhrStart(url);
}
I have 3 Javascript functions called from the body onload in the HTML page.
Each Javascript function is contained in it's own Javascript file. Each Javascript file corresponds to another CGI script on the server.
The bodyonload.js looks like:
function bodyOnload() {
getElementsA();
getElementsB();
getElementsC();
}
Each getElements function simply calls a CGI script to get the contents for 3 different selectboxes.
The problem is that as all 3 functions are called asynchronously the select boxes are getting the wrong results. It's almost like the 3 functions are stepping on each other and putting the CGI responses in the wrong selectbox. I know the CGI responses are correct. This works fine if I serially call each function from the others. Like calling the 2nd function from the first and the 3rd function from the second. The asynchronous nature of them running at the same time seems to cause the problem.
This is the general code for each javascript file that contains the getElements functions.
function getElementsA() {
strURL = "http://test.com/scriptA.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxA(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxA(str)
{
document.getElementById("selectBoxA").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxA");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
-------------------
function getElementsB() {
strURL = "http://test.com/scriptB.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form- urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxB(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxB(str)
{
document.getElementById("selectBoxB").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxB");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
------------------------
function getElementsC() {
strURL = "http://test.com/scriptC.cgi";
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
fillselectboxC(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send();
}
function fillselectboxC(str)
{
document.getElementById("selectBoxC").length=0;
var results = new Array();
results = str.split(/\n/);
var size = results.length;
var select = document.getElementById("selectBoxC");
for (x=0;x<size;x++)
{
var element = results[x];
select.options.add(new Option(element, x))
}
}
It's almost like the 3 functions are stepping on each other
That's exactly what's happening, you're overwriting the onreadystatechange handler set on getElementsA when you call getElementsB, and then again when you call getElementsC. That's because this and self are the global object in all three functions (assuming they're all similar to getElementsA).
You can circumvent that by changing your function calls to object instantiation:
function bodyOnload() {
new getElementsA();
new getElementsB();
new getElementsC();
}