Show item before loading AJAX reply - javascript

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

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

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>

Ajax doesn't fire onreadystatechange

I know the URL is working as intended as i logged that to the console and it is fine. However I can't get "Good News" to log to the console when readyState == 4 and status == 200. I tried removing readState and it still wouldn't log. I tried logging the status and It would only fire once with a value of 0. This is the first time I am working with Ajax so any help is appreciated.
function setupRequest(){
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData () {
console.log('ran')
var url = 'localhost/bev/drinks.php';
var data = document.getElementById('input').value;
url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
request.send;
console.log('sent')
}
You need to actually call send(). You aren't doing anything whenever you say request.send;
function setupRequest() {
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData() {
console.log('ran')
var url = 'https://jsonplaceholder.typicode.com/posts';
var data = document.getElementById('input').value;
//url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
// You wrote (without parentheses):
///////////////////
// request.send; //
///////////////////
// You need to write
request.send();
console.log('sent')
}
<button type="button" id="send">Btn</button>
<input type="text" id="input">

How do I make an HTTP request to bitstamp?

I'm trying to use an API from bitstamp to fetch a currency trading price on my webpage.
I have researched this problem, but I still cannot get it to work as it always returns ERROR
The link used is https://www.bitstamp.net/api/ticker/ and the response should be last
Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
}
else {
window.alert("ERROR");
} }
Try this:
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonRes= JSON.parse(this.responseText);
if (jsonRes.hasOwnProperty('last')) {
document.getElementById("demo").innerHTML =
jsonRes.last;
alert(jsonRes.last);
}
}
};
xhttp.open("GET", "https://www.bitstamp.net/api/ticker", true);
xhttp.send();
}
<h2>Using the XMLHttpRequest object</h2>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
<p>last attribute is: <span id="demo"></span></p>
Here is one way:
<script src="./jquery.min.js">
//none secure web page ?
jQuery.get("https://www.bitstamp.net/api/ticker/", function (data, status)
{
// use response here; jQuery passes it as the first parameter
var response = JSON.parse(data);
window.alert(response.last);
console.log("MyFunc: " + "response : " + response + "\nStatus: " + status);
});
</script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
} else {
window.alert("ERROR");
}
}
}

update ajax send() content

I'm trying to receive data from ajax call and then send this data back using ajax.
javascript code:setInterval (function ()
{
var xmlhttp = new XMLHttpRequest();
var content = "data=1";
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
content = "data=" + xmlhttp.responseText;
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST" , "execute-page.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(content);
},5000);
the problem now is that it keeps sending the old content. how can I update content variable with ajax response text?
Move the line var content = "data=1"; out of the function:
var content = "data=1";
setInterval (function ()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
content = "data=" + xmlhttp.responseText;
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST" , "execute-page.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(content);
},5000);

Categories

Resources