Below function only works to fetch URL that is function 1. Function 2 which makes another ajax call to fetch and display data in one of the pages that fetched by function 1, doesn't work. WHy is it so, is there any conflict here? I believe can use same object which is xmlhttp in this case for multiple function?
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="js/jquery-1.11.2.min.js"></script>
<script>
var xmlhttp = false;
try {
xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);
//alert("javascript version greater than 5!");
} catch (e) {
try {
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
// alert("you're using IE!");
} catch (E) {
xmlhttp = new XMLHttpRequest();
//alert("non IE!");
}
}
//function 1
function sendtobox(param, param2) {
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var ajaxElm = document.getElementById('boxA');
//ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML; // append in front
jQuery(ajaxElm).prepend(this.responseText);
}
}
}
xmlhttp.open("GET", "getsubjects.php?q=" + param + "&r=" + param2, true);
xmlhttp.send();
}
//function 2
function makerequest(serverPage, objID) {
var obj = document.getElementById(objID);
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
html
<div class="row">
<div class="small-11 medium-12 large-12 small-centered medium-centered large-centered text-center columns top_menu">
<ul class="small-block-grid-4 maedium-block-grid-4 large-block-grid-4">
<li>
Home
</li>
<li>
Search Tutors</li>
<li>
Become a tutor
</li>
<li>
How it works
</li>
</ul>
</div>
</div>
<div class="row">
<div class="small-11 medium-12 large-12 columns">
<section id="content">
<div class="row">
<div class="small-12 medium-12 large-12 columns" id="hw">
</div>
</div>
</section>
</div>
</div>
Create different xmlHTTP request objects for each call
function getXmlHttp() {
var xmlhttp = false;
try {
xmlhttp = new ActiveXObject(Msxml2.XMLHTTP);
//alert("javascript version greater than 5!");
} catch (e) {
try {
xmlhttp = new ActiveXObject(Microsoft.XMLHTTP);
// alert("you're using IE!");
} catch (E) {
xmlhttp = new XMLHttpRequest();
//alert("non IE!");
}
}
return xmlhttp;
}
//function 1
function sendtobox(param, param2) {
var xmlhttp = getXmlHttp();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if (this.responseText !== null) {
var ajaxElm = document.getElementById('boxA');
//ajaxElm.innerHTML = this.responseText + ajaxElm.innerHTML; // append in front
jQuery(ajaxElm).prepend(this.responseText);
}
}
}
xmlhttp.open("GET", "getsubjects.php?q=" + param + "&r=" + param2, true);
xmlhttp.send();
}
//function 2
function makerequest(serverPage, objID) {
var xmlhttp = getXmlHttp();
var obj = document.getElementById(objID);
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
Related
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;
});
}
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>
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");
}
}
}
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);
The function below gets results in ie but not on the other browsers. Any suggestion?
function show_packet(str, company) {
var cam = document.getElementById("company");
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("packet_1").innerHTML = xmlhttp.responseText;
document.getElementById("icon_1").innerHTML = "";
}
}
xmlhttp.open("GET", "show_packet.php?car_moto=" + encodeURIComponent(str, true) + "&cam=" + encodeURIComponent(cam.value, true));
xmlhttp.send();
}
vars and functions are hoisted to the top of their containing function. Declare your var once at the top, and only assign it in the if/else.