Function output empty by succesfull AJAX response - javascript

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

Related

Json parser and loop scheme

How can I loop my json file using my script, eg: I should choose whether to loop Schema A or Schema B.
My json file is:
{
"A":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
],
"B":[
{
"id":"1",
"title":"Primo"
},
{
"id":"2",
"title":"Secondo"
}
]
}
Maybe setting a variable so as to define the scheme I have to display
My javascript file is:
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
myFunction(myArr);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj= JSON.parse(this.responseText);
myFunction(obj, 'A');
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(obj, key) {
var arr = obj[key];
var out = "";
var i;
for(i = 0; i < arr.length; i++) {
out += arr[i].id + ' - ' + arr[i].title + '<br>';
}
document.getElementById("id01").innerHTML = out;
}
Assuming that what you presented as JSON file is a response form network and is passed to myFunction, then why not to do something like:
let myRootArray;
if(/* some confitions */) {
myRootArray = myArr.A
} else {
myRootArray = myArr.B
}
myFunction(myRootArray );
Beside that, your names are a bit confusing, var myArr = JSON.parse(this.responseText);, while JSON.parse will return object, not an array.

How to add Node.js result in my HTML project?

this is my project: http://cryptotipsitalia.sytes.net/.
I want add Ethereum value down to "Valore BTC" with Node.js: https://www.npmjs.com/package/crypto-price.
How can I add it?
That's my code:
function getValueBTC() { <!-- chiamata API --> /
var xmlhttp = new XMLHttpRequest();
var url = "https://api.coindesk.com/v1/bpi/currentprice.json";
var output;
console.log(url);
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
output = this.responseText;
var obj = JSON.parse(output);
var rightValue = (obj.bpi.EUR.rate).substring(0,obj.bpi.EUR.rate.length-2); /* eliminazione ultime due cifre */
document.getElementById("cellaValoreBTC").innerHTML= obj.bpi.EUR.symbol + " " + rightValue;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader("Content-type", "text/plain");
xmlhttp.send();
}
let price = require('crypto-price');
price.getCryptoPrice('EUR', 'ETH').then(obj => {
console.log(obj.price); // It will print ETH rate per BTC
document.getElementById("cellaValoreETH").innerHTML = obj.price;
}).catch(err => {
console.log(err);
});
table><tr><td width="75%">VALORE BTC:</td></tr><tr id="cellaValoreBTC" width="75%"></tr><tr><td width="75%">VALORE ETH:</td></tr><tr id="cellaValoreETH" width="75%"></table>
Why "document.getElementById("cellaValoreBTC").innerHTML = obj.price;" doesnt' work?
How can I add obj.price in my HTML code?
Thanks

Pass parameters to GET-Request

G'morning folks,
I just have a small problem to fix this issue:
I have a page which should GET some data from a url when opening and the display in the own content. But the GET url contains Parameters from my url.
So:
1. Get Parameters from my URL like www.mydomain.com?test=1&test1=bla
2. open GET with this parameters (1 and bla) and display result
Here my current version:
<body>
<h3>Visa Informationen</h3>
<p id="data"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("data").innerHTML = myObj.response.visa.content;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>
<script>
function getURLParameter(name) {
var value = decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, ""])[1]);
return (value !== 'null') ? value : false;
}
var param = getURLParameter('test');
if (param) document.getElementById("testnr").innerHTML = param;
var param1 = getURLParameter('test1');
if (param1) document.getElementById("testnr1").innerHTML = param1;
var url = "https://api01.otherdomain.com?test=" + param + "&test1" + param1 + "&trv=0&vis=1"
</script>
</body>
Any hint where the problem is with this code?
Kind regards,
Chris
It seems like you having issue with script execution order.
I assume that testnr element coming from your XML ajax request.
You have two script block in your HTML and it will executed while page load.
When second script block is running your fist XMLHttpRequest not completed so it not able to find given HTML tag document.getElementById("testnr").innerHTML
To overcome this issue you need to execute script only after XMLHttpRequest request is completed.
In your case :
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("data").innerHTML = myObj.response.visa.content;
// Execute new created function here
SetValues();
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function getURLParameter(name) {
var value = decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, ""])[1]);
return (value !== 'null') ? value : false;
}
function SetValues()
{
var param = getURLParameter('test');
if (param) document.getElementById("testnr").innerHTML = param;
var param1 = getURLParameter('test1');
if (param1) document.getElementById("testnr1").innerHTML = param1;
var url = "https://api01.otherdomain.com?test=" + param + "&test1" + param1 + "&trv=0&vis=1"
}
</script>
Okay, i fixed the matter.
Here my result which works fine for me:
<script>
function getURLParameter(name) {
var value = decodeURIComponent((RegExp(name + '=' + '(.+?)(&|$)').exec(location.search) || [, ""])[1]);
return (value !== 'null') ? value : false;
}
var param = getURLParameter('test');
var param1 = getURLParameter('test1');
var url = "https://api01.otherdomain.com?test=" + param + "&test1" + param1 + "&trv=0&vis=1"
</script>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("additionalContent").innerHTML = myObj.response.additionalContent;
document.getElementById("data").innerHTML = myObj.response.visa.content;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
</script>

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 do I refresh a div element after AJAX succes?

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

Categories