How do I refresh a div element after AJAX succes? - javascript

Posting this because I found a lot of jquery answers, but no raw javascript answers.
So I have a function to post a comment to a comment section, and I want the comment section to refresh after posting a comment, But for some reason my code isn't working.
The code for loading the comment section:
function loadCommentSection() {
console.log("loading section")
imgid = imgid.replace("img/pic (", "");
imgid = imgid.replace(").jpg", "");
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("commentsection").innerHTML = this.responseText;
}
};
xhttp.open("GET", "commentsection.php?imgid=" + imgid, true);
xhttp.send();
}
and the code for submitting the comment:
function submitComment() {
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var comment = document.getElementById("comment").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
}
};
xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);
xhttp.send();
loadCommentSection();
}
The problem is that the loadCommentSection function in the submitComment function isn't executing.

You should allow the comment to be sent to the server and be registered before calling loadCommentSection. So, it is probably best to call it when the response becomes available:
function submitComment() {
var title = document.getElementById("title").value;
var name = document.getElementById("name").value;
var comment = document.getElementById("comment").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
loadCommentSection(); // <<---- moved here.
}
};
xhttp.open("GET", "comment.php?imgid=" + imgid + "&title=" + title + "&comment=" + comment + "&name=" + name, true);
xhttp.send();
}

Related

How to make this JavaScript function with two nested functions return the correct string [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
I'm trying to implement JavaScript tool for generating a random video from specific channel from youtube, I coded everything and it works fine in the console, however I cannot save the value in variable and to display the video later on my website. Is it possible to make the value of x (defined on the end of the pasted code) have the value of youtubeUrl
function getVideo() {
var channelId = "";
var apiKey = "";
var videosUrl = "https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=" + channelId + "&maxResults=50&key=" + apiKey;
var ajax = new XMLHttpRequest();
ajax.open("GET", videosUrl, true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
var videos = json.items;
var randomNumber = Math.floor(Math.random() * (videos.length + 1));
var randomVideo = videos[randomNumber];
var videoId = randomVideo.id.videoId;
var videoUrl = "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&part=snippet,contentDetails,statistics&key=" + apiKey;
var ajax = new XMLHttpRequest();
ajax.open("GET", videoUrl, true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
var singleVideo = json.items[0].id;
var youtubeUrl = "https://www.youtube.com/embed/" + singleVideo;
}
};
}
};
}
let x = getVideo(); // how to make it such that x has the value of youtubeUrl
Just wrap the content of your function inside a new Promise constructor and resolve it with the youtubeUrl:
function getVideo() {
return new Promise((resolve, reject) => {
var channelId = "";
var apiKey = "";
var videosUrl = "https://www.googleapis.com/youtube/v3/search?order=date&part=snippet&channelId=" + channelId + "&maxResults=50&key=" + apiKey;
var ajax = new XMLHttpRequest();
ajax.open("GET", videosUrl, true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
var videos = json.items;
var randomNumber = Math.floor(Math.random() * (videos.length + 1));
var randomVideo = videos[randomNumber];
var videoId = randomVideo.id.videoId;
var videoUrl = "https://www.googleapis.com/youtube/v3/videos?id=" + videoId + "&part=snippet,contentDetails,statistics&key=" + apiKey;
var ajax = new XMLHttpRequest();
ajax.open("GET", videoUrl, true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var json = JSON.parse(this.responseText);
var singleVideo = json.items[0].id;
var youtubeUrl = "https://www.youtube.com/embed/" + singleVideo;
resolve(youtubeUrl);
}
};
}
};
}
let x = await getVideo();

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

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>

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?

Parsing JSON File from XMLHttpRequest

I would like to use data within a JSON file which I get by using the XMLHttpRequest. I already checked that I recieve the file.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
var obj = xhttp.open("GET", "../data/data.json", true);
xhttp.send();
var obj1 = JSON.parse(obj);
a0 = obj1.a0;
This is my JSON file.
{"a0":2, "a1": -2.356, "a2": 4.712}
I can't find the mistake I am doing here. Can you help?
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
var obj=this.responseText;
var obj1 = JSON.parse(obj);
a0 = obj1.a0;
}
};
xhttp.open("GET", "../data/data.json", true);
xhttp.send();
You need to get the response text inside the xhttp response.
onreadystatechange is a callback. That means that it's called asynchonously when the request ended. SO a part of your code is misplaced. Here the correction:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
var obj1 = JSON.parse(this.responseText);
var a0 = obj1.a0;
}
};
xhttp.open("GET", "../data/data.json", true);
xhttp.send();

Categories