Calling AJAX function after another one - javascript

I have something I cannot understand how to do it in AJAX. I have a sidebar and a div "content" in my page. The sidebar is made of button and onclick it call the classical function:
function loadDoc(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("content").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
It load the "url" of the button in the content. Well, at this point everything is ok. Now one of this url, say "TheUrl", is a document that contain title and so on, and a div "list" and in this list I would like to load an XML file. I have the function
function loadXML() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
myFunction(xhttp);
}
};
xhttp.open("GET", "file.xml", true);
xhttp.send();
}
function myFunction(xml) {
var i;
var xmlDoc = xml.responseXML;
var table="<ul>";
var x = xmlDoc.getElementsByTagName("ITEM");
for (i = 0; i <x.length; i++) {
table += "<li>" +
x[i].getElementsByTagName("ELEMENT")[0].childNodes[0].nodeValue +
"</li>"
};
table += "</ul>";
document.getElementById("list").innerHTML = table;
}
But I have no idea how to load the function loadXML() after loadDoc("TheUrl") so that the Xml data appears in the div list that was create in the div content... I am clear ?? :D
I would like something like that in my sidebar:
<ul>
<li><button type="button" onclick=loadDoc("OtherUrl.html")>OtherUrl</button></li>
<li><button type="button" onclick=loadDoc("TheUrl.html").done(loadXML())>TheUrl</button></li>
</ul>
Thanks you in advance for your kind help.

You can just call the loadXML function in the onreadystaechange event of the first AJAX call like so:
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("content").innerHTML = xhttp.responseText;
// call the other function
loadXML();
}

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

Calling javascript in a php page

I'm trying to call this JS function inside a php page (footer.php), but it's not working. I've tried multiple options, like placing the script inside a php echo, but that didn't work either. I'm stuck here. Any suggestions to call it properly?
<?php
/**
* Header for our theme
*/
electro_get_footer();
?>
<div class="kiyoh">
<span id="cijfer" class="review-cijfer"></span>
<span class="review-cijfer-after"> / 10</span>
<a href="https://kiyoh.nl/lumenlab">
<span id="beoordelingen" class="review-beoordelingen"></span>
<span class="review-beoordelingen-after"> beoordelingen</span>
</a>
</div>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET",
"https://www.kiyoh.nl/xml/recent_company_reviews.xml? connectorcode=xws9TE3TQSX7t7Hrj9xFAbYwhraBaenGFHYWt9jKyx4CRV5vFW&company
_id=16907&reviewcount=all&showextraquestions=1", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
document.getElementById("cijfer").innerHTML =
xmlDoc.getElementsByTagName("total_score")
[0].childNodes[0].nodeValue;
document.getElementById("beoordelingen").innerHTML =
xmlDoc.getElementsByTagName("total_reviews")
[0].childNodes[0].nodeValue;
}
</script>
I have change the url in the xhttp.open() function and it work.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
} else {
console.log("readyState: " + this.readyState);
console.log("Status: " + this.status);
}
};
xhttp.open("GET", "https://www.kiyoh.nl/xml/recent_company_reviews.xml?connectorcode=xws9TE3TQSX7t7Hrj9xFAbYwhraBaenGFHYWt9jKyx4CRV5vFW&company_id=16907&reviewcount=all&showextraquestions=1", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
document.getElementById("cijfer").innerHTML = xmlDoc.getElementsByTagName("total_score") [0].childNodes[0].nodeValue;
document.getElementById("beoordelingen").innerHTML = xmlDoc.getElementsByTagName("total_reviews") [0].childNodes[0].nodeValue;
}

selection in a loop freezes my page

i'm a complete newbie when it comes to Js, trying to make some very simple script that takes a string of binary numbers from a txt document on my server using ajax, to then put it in a string var and change the first 0 it finds in a 1, using an if construct inside a loop.
Problem is, when the page tries to execute the if line, it simply freezes. Taking the same if construct out of the loop, the script is executed no problem, so i'm guessing it has something to do with either that or/and some fundamental misunderstanding of how Js scripts works in the first place.
Here is the script:
function loadPos()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "posizioni.txt", true);
xhttp.send();
}
function takeFirst()
{
var i=0;
var check=false;
var oldPos=[];
loadPos();
oldPos = document.getElementById("demo").innerHTML;
for(i=0;!check||i<10;i++)
{
if(oldPos[i]=="0")
{
oldPos[i]="1";
check=true;
}
}
document.getElementById("demo").innerHTML=oldPos;
}
I don't see any use of loop in it if you can achieve the same without it. Please update your function to the following:
function takeFirst()
{
loadPos();
var oldPos = document.getElementById("demo").innerHTML;
if(oldPos.indexOf("0") > -1){
oldPos = oldPos.replace('0', '1');
}
document.getElementById("demo").innerHTML = oldPos;
}
I think you want for(i=0;!check && i<10;i++).
But there is another way to do this using break;
function loadPos()
{
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
document.getElementById("demo").innerHTML = this.responseText;
};
xhttp.open("GET", "posizioni.txt", true);
xhttp.send();
}
function takeFirst()
{
var i=0;
var oldPos=[];
loadPos();
oldPos = document.getElementById("demo").innerHTML;
for(i=0;i<10;++i)
{
if(oldPos[i]=="0")
{
oldPos[i]="1";
break;
}
}
document.getElementById("demo").innerHTML=oldPos;
}

How can i access a php page on a server from my local html page?

i have a php page on my server that controls my mysql database. there is also another page that displays everything. i downloaded that page into my pc and modified the code for it to be still able to connect to that php file on my server that controls the database.
when the html page is on the server it works fine. but, when i downloaded it it does not work anymore. here is some of the code:
btw, all functions are written in javascript.
function queryNumberOfQuestions() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var numberOfQuestions = parseInt(this.responseText);
populateSequence(questionOrder, numberOfQuestions);
shuffle(questionOrder);
}
};
xhttp.open("GET", "http://wael-alghamdi.com/getQuestionCount.php", true);
xhttp.send();
}
function queryNextQuestion(questionNumber) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
theQuestion = this.responseText.split(',');
updateGame();
}
};
var url = "http://wael-alghamdi.com/getQuestion.php?row=" + questionNumber.toString();
xhttp.open("GET", url, true);
xhttp.send();
}
function queryOtherAnswers(questionNumber) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
otherAnswers = this.responseText.split(',');
updateGame();
}
};
var url = "http://wael-alghamdi.com/getOtherAnswers.php?row=" + questionNumber.toString();
xhttp.open("GET", url, true);
xhttp.send();
}
what i changed was those three lines:
xhttp.open("GET", "http://wael-alghamdi.com/getQuestionCount.php", true);
var url = "http://wael-alghamdi.com/getQuestion.php?row=" + questionNumber.toString();
var url = "http://wael-alghamdi.com/getOtherAnswers.php?row=" + questionNumber.toString();
so my question is how can i make it work even if the php is on a different machine?

remove parsed element onclick

I have a parsed xml-file that shows twice the same element. Now I want a button that hides one of them with an onclick-statement. Does anyone know how to do this?
<!DOCTYPE html>
<html>
<body>
<p id="dasa"></p>
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "customers.xml", true);
xhttp.send();
function myFunction(xml) {
var xmlDoc = xml.responseXML;
var x = xmlDoc.getElementsByTagName("syl");
document.getElementById("dasa").innerHTML =
x[0].getAttribute('category') + "<br>";
document.getElementById("dasa").innerHTML +=
x[0].getAttribute('category');
}
function remove() {
x[0].removeAttribute('category');
}
</script>
<button onclick="remove()">remove</button>
</body>
</html>
x is undefined in your remove function.
function remove() {
x[0].removeAttribute('category');
}
You want something like this:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this);
}
};
xhttp.open("GET", "customers.xml", true);
xhttp.send();
var xmlDoc;
var x;
function myFunction(xml) {
xmlDoc = xml.responseXML;
x = xmlDoc.getElementsByTagName("syl");
document.getElementById("dasa").innerHTML =
x[0].getAttribute('category') + "<br>";
document.getElementById("dasa").innerHTML +=
x[0].getAttribute('category');
}
function remove() {
x[0].removeAttribute('category');
}
This will make x into a global var set by myfunction.

Categories