Pass parameters to GET-Request - javascript

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>

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>

AJAX - How can I make certain all data is received? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Background: I am attempting to retrieve data, using AJAX, and assign it to a variable. I have tried to set the AJAX request to synchronous, but Firefox will not allow it.
Question: How can I make certain all the data is received?
function search(){
var data = [];
this.init = function(){
data = getData({"url":"/imglib/Inventory/cache/2335/VehInv.js"});
console.log(data); // Returns as 'undefined'. Possibly because of asynchronous call?
};
var d = new Date();
function getData(url){
var xhttp: new XMLHttpRequest();
var dataURL = url + '?v=' String(d.getTime());
xhttp.onreadystatechange = function(){
if(this.readyState = 4 && this.status == 200){
var r = this.responseText;
var s = r.indexOf('[') + 1;
var e = r.indexOf(']');
var jsonData = JSON.parse("[" + r.slice(s,e) + "]");
return jsonData;
}
};
xhttp.open("GET", dataURL, true);
xhttp.send();
}
};
you have to use a callback when working with asynchronous stuff..
function search(){
this.init = function(){
getData("http://www.petesrvvt.com/imglib/Inventory/cache/2335/VehInv.js", function(data){
console.log(data); // Returns as 'undefined'. Possibly because of asynchronous call?
});
};
var d = new Date();
function getData(url, callback){
var xhttp: new XMLHttpRequest();
var dataURL = url + '?v=' String(d.getTime());
xhttp.onreadystatechange = function(){
if(this.readyState = 4 && this.status == 200){
var r = this.responseText;
var s = r.indexOf('[') + 1;
var e = r.indexOf(']');
var jsonData = JSON.parse("[" + r.slice(s,e) + "]");
callback(jsonData);
}
};
xhttp.open("GET", dataURL, true);
xhttp.send();
}
};
Call the function that will deal with the data from the function invoked on "onreadystatechange". The reason it doesn't work is that the variable "data" isn't defined with the result of the async query when you are attempting to use it.
(function search() {
var data = [];
this.init = function() {
data = getData({
"url": "http://www.petesrvvt.com/imglib/Inventory/cache/2335/VehInv.js"
});
// This is definitely caused by the asynchronous XMLHttpRequest
//console.log(data); // This needs to be moved to the callback that is invoked when the request completes. See below
};
var d = new Date();
function getData(url) {
var xhttp: new XMLHttpRequest();
var dataURL = url + '?v='
String(d.getTime());
xhttp.onreadystatechange = function() {
if (this.readyState = 4 && this.status == 200) {
var r = this.responseText;
var s = r.indexOf('[') + 1;
var e = r.indexOf(']');
var jsonData = JSON.parse("[" + r.slice(s, e) + "]");
// This is how you be sure you get your data
console.log(jsonData);
}
};
xhttp.open("GET", dataURL, true);
xhttp.send();
}
})();

JS search returned xhr.responseText for div then remove div

I would like to search a xhr.responseText for a div with an id like "something" and then remove all the content from the xhr.responseText contained within that div.
Here is my xhr code:
function getSource(source) {
var url = source[0];
var date = source[1];
/****DEALS WITH CORS****/
var cors_api_host = 'cors-anywhere.herokuapp.com';
var cors_api_url = 'https://' + cors_api_host + '/';
var slice = [].slice;
var origin = self.location.protocol + '//' + self.location.host;
var open = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function () {
var args = slice.call(arguments);
var targetOrigin = /^https?:\/\/([^\/]+)/i.exec(args[1]);
if (targetOrigin && targetOrigin[0].toLowerCase() !== origin &&
targetOrigin[1] !== cors_api_host) {
args[1] = cors_api_url + args[1];
}
return open.apply(this, args);
};
/****END DEALS WITH CORS****/
var xhr = new XMLHttpRequest();
xhr.open("GET", cors_api_url+url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = xhr.responseText;
var respWithoutDiv = removeErroneousData(resp);
}
else{
return "Failed to remove data.";
}
}
xhr.send();
}
remove div here:
/*This must be in JS not JQUERY, its in a web worker*/
function removeErroneousData(resp) {
var removedDivResp = "";
/*pseudo code for removing div*/
if (resp.contains(div with id disclosures){
removedDivResp = resp.removeData(div, 'disclosures');
}
return removedDivResp;
}
You can dump the response in a div and then search for that div you want empty its content.
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var resp = xhr.responseText;
$('div').attr('id', 'resp').html(resp);
$('#resp').find('disclosures').html('');
//var respWithoutDiv = removeErroneousData(resp);
}
else{
return "Failed to remove data.";
}
}

Categories