How to chain ajax calls using plain javascript - javascript

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

Related

Function output empty by succesfull AJAX response

There's an issue with my function in the AJAX.
I create an AJAX call to a PHP file that returns JSON.
For loop this JSON I created a fucntion that I run if the AJAX is successfull.
But in practice the data is empty.
<script>
document.getElementById("getproducts").addEventListener("submit", sendAjax);
function sendAjax(event) {
var q = document.getElementById('search').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
display(this.responseText);
}
}
xhttp.open("POST", "results.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('search='+q);
event.preventDefault();
}
function display( jsdata ){
for ( var key in jsdata ){
var htmltabel = '';
var datanode = document.createElement("div");
htmltabel += '<div class="id">' + jsdata[key]['id'] + '</div>';
content = htmltabel;
datanode.innerHTML = content;
document.getElementById("resultt").appendChild(datanode);
}
}
</script>
If I code the JSON hardcode in the function like this than everything is okay.
var hardcoded = {"1736":{"id":"1736","post_title":"Test explode","_sku":"12345","_stock":null,"_price":"9.50"}}
//PART OF THE CODE
if (this.readyState == 4 && this.status == 200) {
display(hardcoded);
}
How can I fix this that the function use the responded JSON?
here is a corrected script, You should just convert the responseData from string to Json Object!
document.getElementById("getproducts").addEventListener("submit", sendAjax);
function sendAjax(event) {
var q = document.getElementById('search').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
display( JSON.parse(this.responseText) ); // You should convert the response from string to a valid JSON
}
}
xhttp.open("POST", "results.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('search='+q);
event.preventDefault();
}
function display( jsdata ){
for ( var key in jsdata ){
var htmltabel = '';
var datanode = document.createElement("div");
htmltabel += '<div class="id">' + jsdata[key]['id'] + '</div>';
content = htmltabel;
datanode.innerHTML = content;
document.getElementById("resultt").appendChild(datanode);
}
}

XMLHttpRequest looping

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?

How to get multiple XMLHttpRequests to occur serially?

I have the following code, which works (sort of). When I run it, the page displays information about the two coins, but returns 'undefined' for the coin price. The call to alert() indicates that the getCoinPrice function is running AFTER the main code. How do you execute the code so that the function call happens serially? If that's not possible, would it be better to learn to use the Fetch API?
Here's the code, in its entirety:
<html>
<body>
<h2>Use the XMLHttpRequest to get the content of a file.</h2>
<p id="demo"></p>
<script>
function getCoinPrice(id) {
var xhr = new XMLHttpRequest();
var URL = "https://api.coinmarketcap.com/v2/ticker/" + id + "/";
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
var Obj = JSON.parse(xhr.responseText);
var price = Obj.data.quotes.USD.price;
alert(price);
return(price);
}
}
xhr.open("GET", URL, true);
xhr.send();
}
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var coins = [ "BTC","ETH" ]
for(j=0; j < coins.length; j++) {
for(i=0; i < myObj.data.length; i++) {
if (myObj.data[i].symbol == coins[j]) {
document.getElementById("demo").innerHTML +=
myObj.data[i].id + "," + myObj.data[i].name + "," +
myObj.data[i].symbol + "," +
getCoinPrice( myObj.data[i].id ) + "<br>" ;
}
}
}
}
};
xmlhttp.open("GET", "https://api.coinmarketcap.com/v2/listings/", true);
xmlhttp.send();
</script>
</body>
</html>

Cache pages using XMLHttpRequest

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

Ajax - For loop

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

Categories