How to use Promise JS in this case? - javascript

I have :
function loadDoc123() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
I want to implement promiseJS to this code but dont editing code . How do i do?

Without editing you can't. You need to wrap the code into the Promise
function loadDoc123() {
return new Promise((res, rej) => {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
res(this.responseText);
}
};
xhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
});
}
And use
loadDoc123().then(text => document.getElementById("demo").innerHTML = text);

Related

Anyone knows what I could do to this javascript code to make it more reliable?

I don't really know all that much about javascript at all yet, I just recently started learning it bc I needed it for a microcontroller project where we needed to use an MCU with network capabilities so apart from making the mcu code I was tasked with creating the web pages it would provide to the user.
In one instance I made a section where the user would be able to see all (actually most, at least the ones I thought of importance to them) the parameters for the Led matrix that they get to set up. The problem is that, in order to load the parameters I used a method that I believe isn't really efficient, and the fact that I still don't know much about js doesn't help it. Does any of this seem to have a much easier solution to you?
<div class="row">
<div id="column1" class="column">
</div>
<div class="column middle">
<h3 style="color: rgb(187, 187, 187);">Parámetros guardados: </h3>
<div class="guardado">
<p >Mensaje guardado inicial: <span id="mensaje"></span></p>
<p >Brillo guardado: <span id="brightness"></span></p>
<p >Velocidad guardada: <span id="speed"></span></p>
<p >Alineación: <span id="text_align"></span></p>
<p >Modo operando: <span id="MODO"></span></p>
<p >Tiempo entre mensajes (M2): <span id="TIME"></span></p>
<p >Efecto (M1): <span id="EM1"></span></p>
<p >Efecto inicio (M2): <span id="E1M2"></span></p>
<p >Efecto salida (M2): <span id="E2M2"></span></p>
</div>
</div>
<script>
//Load parameters
var xhttp = new XMLHttpRequest(); //Message
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("mensaje").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/mensaje", true);
xhttp.send();
var xhttp = new XMLHttpRequest(); //Brightness
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("brightness").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/brillo_guardado.txt", true);
xhttp.send();
var xhttp = new XMLHttpRequest(); //Speed
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("speed").innerHTML = this.responseText;
document.getElementById("speed").innerHTML += "%";
}
};
xhttp.open("GET", "/velocidad_guardado.txt", true);
xhttp.send();
var xhttp = new XMLHttpRequest(); //MODE
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("MODO").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/modo_guardado.txt", true);
xhttp.send();
var xhttp = new XMLHttpRequest(); //Text alignment
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("text_align").innerHTML = this.responseText;
}
};
xhttp.open("GET", "/alineacion_guardado.txt", true);
xhttp.send();
var xhttp = new XMLHttpRequest(); //var initial_time
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("TIME").innerHTML = this.response;
document.getElementById("TIME").innerHTML += "ms";
}
};
xhttp.open("GET", "/tiempo_guardado.txt");
xhttp.send();
var xhttp = new XMLHttpRequest(); //EFFECT MODE 1
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("EM1").innerHTML = this.response;
}
};
xhttp.open("GET", "/effecto_modo1_guardado.txt");
xhttp.send();
var xhttp = new XMLHttpRequest(); //EFFECT 1 MODE 2
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("E1M2").innerHTML = this.response;
}
};
xhttp.open("GET", "/effecto1_m2_guardado.txt");
xhttp.send();
var xhttp = new XMLHttpRequest(); //EFFECT 2 MODE 2
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("E2M2").innerHTML = this.response;
}
};
xhttp.open("GET", "/effecto2_m2_guardado.txt");
xhttp.send();
</script>
This is what it looks like after loading
The page is going to be asking the mcu for several parameters it has stored and then it'll display them.
The code can be cleaned up a lot:
function loadText(elementId, url, suffix = ""){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById(elementId).innerHTML = this.responseText + suffix;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
//Load parameters
loadText("mensaje", "/mensaje");
loadText("brightness", "/brillo_guardado.txt");
loadText("speed", "/velocidad_guardado.txt", "%");
loadText("MODO", "/modo_guardado.txt");
loadText("text_align", "/alineacion_guardado.txt");
loadText("TIME", "/tiempo_guardado.txt", "ms");
loadText("EM1", "/effecto_modo1_guardado.txt");
loadText("E1M2", "/effecto1_m2_guardado.txt");
loadText("E2M2", "/effecto2_m2_guardado.txt");
When you're repeating code like that, put it into a function.
Other than that, there's not much you can do to make it faster, as you're loading every individual string from a separate url.
Instead of the old-fashioned XMLHttpRequest, you can also make use of the fetch API:
function loadText(elementId, url, suffix = ""){
fetch(url).then((response) => {
document.getElementById(elementId).innerHTML = response + suffix;
});
}

Show item before loading AJAX reply

I am trying to show an item if the user clicks on my button which is connect with my AJAX response. The div should by show after clicking button and hidden after the whole page is loading.
My AJAX:
document.getElementById('mainContent').style.display = 'none';
document.getElementById('productDetail').style.display = 'block';
//ajax
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "product/" + id + "/", true);
xhttp.send();
I try this:
(I added a show div if the code is loaded and I wanted to hide it after loading)
document.getElementById('divForShow').style.display = 'block';
document.getElementById('mainContent').style.display = 'none';
document.getElementById('productDetail').style.display = 'block';
//ajax
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "product/" + id + "/", true);
xhttp.send();
document.getElementById('divForShow').style.display = 'none';
I also tried
(The concealment code I wanted to associate with the onload event in the last div from the ajax response)
document.getElementById('divForShow').style.display = 'block';
document.getElementById('mainContent').style.display = 'none';
document.getElementById('productDetail').style.display = 'block';
//ajax
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "product/" + id + "/", true);
xhttp.send();
*and added onload function on the end of my div in html AJAX response
</div id="myLastDivFromAjaxRespone" onload="hiddenDiv()">
document.getElementById('divForShow').style.display="none"; //hiddenDiv function
How to show the div after clicking the button and hide if the entire AJAX response has been loaded.
You can simply split the code in 2 functions.
Then, on button click, calls the before_ajax(), then
Example:
function before_ajax(){
document.getElementById(".element").innerHTML = "<b>Loading...</b>";
}
function do_ajax(){
document.getElementById('mainContent').style.display = 'none';
document.getElementById('productDetail').style.display = 'block';
//ajax
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("response").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "product/" + id + "/", true);
xhttp.send();
}
function reload_page(){
window.location.reload();
}

Beginner Js : REST API returns "undefined" on successful call

{
let request = new XMLHttpRequest();
request.open('GET', url);
request.responseType = "text";
var response = XMLHttpRequest.responseText;
request.send();
document.getElementById("price").innerHTML = response;
}
What could be my mistake? I am trying to print the response as text but it simply says "undefined"
You have to listen for response data byonreadystatechange
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("price").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();

Use JSON-value from one httprequest in another httprequest

Im trying to combine open data with 2 http-requests. I need to use one value of the first response, to make the second request-url (the value is part of the second url). How can i do that?
here is my code:
https://codepen.io/1234cb/pen/wvBGKze
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<h3>XMLHttpRequest</h3>
zipcode <input type="text" id="zip" value="3136jr" title="zipcode"><br><br>
housnr <input type="text" id="housenr" value="77" title="housenr"><br><br>
<button type="button" onclick="loadDoc();loadDoc2()">Get Content</button>
<p id="demo">response 1</p>
<p id="demo2">response 2</p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.response.docs[0].id;
//myObj.response.docs[0].id is the value/variable I need for the next httprequest
}
};
xhttp.open("GET", "https://geodata.nationaalgeoregister.nl/locatieserver/v3/suggest?q=" + document.getElementById("zip").value + "+" + document.getElementById("housenr").value + "&wt=json", true);
xhttp.send();
};
function loadDoc2() {
var url = "https://geodata.nationaalgeoregister.nl/locatieserver/v3/lookup?id=adr-16dc4e7caee6f2b34222fb02b91a464e" //the value/variable myObj.response.docs[0].id should be the last part of the url (from "adr." to "64e")
var vhttp = new XMLHttpRequest();
vhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var Obj = JSON.parse(this.responseText);
document.getElementById("demo2").innerHTML = this.responseText;
}
};
vhttp.open("GET", url, true);
vhttp.send();
};
</script>
</body>
</html>
you have to pass id to loadDoc2 as :
function loadDoc2(id) {
var url = "https://geodata.nationaalgeoregister.nl/locatieserver/v3/lookup?id="+id;//the value/variable myObj.response.docs[0].id should be the last part of the url (from "adr." to "64e")
var vhttp = new XMLHttpRequest();
vhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var Obj = JSON.parse(this.responseText);
document.getElementById("demo2").innerHTML = this.responseText;
}
};
vhttp.open("GET",url, true);
vhttp.send();
};
and call it on success of loadDoc:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.response.docs[0].id;
loadDoc2(myObj.response.docs[0].id)
//myObj.response.docs[0].id is the value/variable I need for the next httprequest
}
};
xhttp.open("GET", "https://geodata.nationaalgeoregister.nl/locatieserver/v3/suggest?q=" + document.getElementById("zip").value +"+"+ document.getElementById("housenr").value +"&wt=json", true);
xhttp.send();
};
You can simply call loadDoc2() with a parameter for the id:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
var response_id = myObj.response.docs[0].id;
document.getElementById("demo").innerHTML = response_id;
//myObj.response.docs[0].id is the value/variable I need for the next httprequest
loadDoc2(response_id);
}
};
xhttp.open("GET", "https://geodata.nationaalgeoregister.nl/locatieserver/v3/suggest?q=" + document.getElementById("zip").value +"+"+ document.getElementById("housenr").value +"&wt=json", true);
xhttp.send();
};
function loadDoc2(response_id = '') {
var url = "https://geodata.nationaalgeoregister.nl/locatieserver/v3/lookup?id="+response_id;
var vhttp = new XMLHttpRequest();
vhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var Obj = JSON.parse(this.responseText);
document.getElementById("demo2").innerHTML = this.responseText;
}
};
vhttp.open("GET",url, true);
vhttp.send();
};
In the onreadystatechange handler, you can then extract the id into request_id and call loadDoc2(request_id) with it.Also, don't forget to change the onclick-handler to only call loadDoc():
<button type="button" onclick="loadDoc();" >Get Content</button>

How to call a piece of code only after a callback function has been executed?

Consider this code, just like a toy example:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
Let's consider that there are five kinds of asynchronous calls inside the function loadDoc(). What I want to do is now is to call another function or any piece of code when all five callback functions are executed. Does Javascript provide anything to help with this situation, or we need to set a flag to check if all 5 tasks are executed?
If you use promises you'll be able to use Promise.all([promises]).
"Promisifying" your current ajax request:
function loadDoc() {
req().then(function (responseText) {
document.getElementById("demo").innerHTML = responseText;
})
}
function req () {
return new Promise(function (resolve, reject) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
resolve(this.responseText);
} else {
reject();
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
});
}
You can either use a callback or a promise,
callback example:
function loadDoc(cb) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
cb(xhttp.responseText); // <= run the callback
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
loadDoc(function(res) {
console.log(res);
// do something
});
promise example:
function loadDoc(cb) {
return return new Promise(function (resolve, reject) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
resolve(xhttp.responseText); // <= run the callback
} else {
reject(xhttp.responseText);
}
};
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true);
xhttp.send();
}
loadDoc()
.then(function(res) {
console.log(res);
// do something
})
.catch(function(err) {
console.error(err);
// do something
});

Categories

Resources