How do I add a variable to the end of a link? - javascript

I'm trying to add an id variable (in this case, demo) to the end of the link but I can't make it work, how can I do it?
var request = new XMLHttpRequest()
request.open('GET', 'https://discordapp.com/api/users/412315079598407691', true)
request.setRequestHeader("Authorization", "Bot bot-token")
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.avatar;
}
};
request.send()
function myFunction() {
var x = document.createElement("IMG");
x.setAttribute("src", `https://cdn.discordapp.com/avatars/412315079598407691/`+ demo);
x.setAttribute("width", "350");
document.body.appendChild(x);
}

Instead of
``https://cdn.discordapp.com/avatars/412315079598407691/+ demo
try doing
https://cdn.discordapp.com/avatars/412315079598407691/${demo}
Please make sure that demo.toString() returns what you want. As things can get weird when you stringify an object.

Related

javascript - function with setInterval not starting immediately on page load

I have this code that continuously accesses a url at given intervals:
window.setInterval(function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = JSON.parse(this.responseText);
document.getElementById("wind").innerHTML = valr5.wind;
}
};
xmlhttp.open("GET", "sample.com/", true);
xmlhttp.send();
}, 30000);}
My problem is that the script would run after 30s, as set in the code. So the page is blank for 30s.
What I want to happen is on page load, the script will run so I won't see I blank page, and from that, access the URL every 30s or so.
How can I do this? thanks.
Save the function in a variable first, call the function, then call setInterval with it:
const updateWind = () => {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var valr5 = JSON.parse(this.responseText);
document.getElementById("wind").innerHTML = valr5.wind;
}
};
xmlhttp.open("GET", "sample.com/", true);
xmlhttp.send();
};
updateWind();
window.setInterval(updateWind, 30000);

Accessing object properties in an array

I am using the following code to check my database for login information and receive it back inside the application but I am having the issue that I cannot parse the JSON information. I have parsed it into an array and when I run the following code the console returns:
I am wondering how do I take this a step further and read the number for "loggedin" and get the "username" also. I have tried replacing myArr with myArr[0].loggedin or even with myArr[0] but then I get a return of undefined.
Anyone any suggestions?
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('loginForm').addEventListener('submit', function() {
var usernameTest = document.getElementById('username').value;
var passwordTest = document.getElementById('username').value;
//alert("username is: " + usernameTest);
//console.log("password is: " + passwordTest);
//alert("test");
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
var myArr = JSON.parse(this.responseText);
chrome.extension.getBackgroundPage().console.log(myArr);
}
};
request.open('GET', 'http://localhost/api/login.php?username='+usernameTest+'&password='+passwordTest);
request.send();
});
});
What worked for me after GaetanoM's comment is:
myArr.UAPlugin[0].loggedin or myArr.UAPlugin[0].username

Can't get a global variable on http request function

it should be an easy one but I am stuck.
I would like to return the result of a function as a global variable. Here I have my function clearbit() for which I created the global variable clearbit_role.
But I can't alert this variable outside of the function... Any clue anyone?
Thanks!
EDIT: Added a fiddle here:
http://jsfiddle.net/luron01/sJ8Eu/9/
var clearbit_role ;
function clearbit (web){
var url = "https://prospector.clearbit.com/v1/people/search?domain=clearbit.com&seniorities[]=executive&seniorities[]=manager&limit=1";
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status == 200) {
var response = JSON.parse(request.responseText.replace('[','').replace(']',''));
var clearbit_fullname = response.name.fullName;
clearbit_role = response.role;
clearbit_role='test'
}
}
request.open('GET', url, true);
request.setRequestHeader("authorization", "Bearer sk_605e7e64cbb1ebcca9e28b8a97d23f22")
request.send();
}
clearbit()
alert(clearbit_role)
Thanks!
why don't you create the variable clearbit_role outside of the function
var clearbit_role ;
function clearbit (web){
var url = "myurl";
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status == 200) {
var response = JSON.parse(request.responseText.replace('[','').replace(']',''));
var clearbit_fullname = response.name.fullName;
clearbit_role = response.role;
}
}
request.open('GET', url, true);
request.setRequestHeader("authorization", "Bearer sk_1be5451252ba4e31518e9b")
request.send();
}
clearbit()
alert(clearbit_role)
The problem
is NOT in scoping, the clearbit_role variable is already a global variable. But the problem is clearbit function is take a time to make the http request.
so the alert function run before the clearbit_role variable declaration.
Solution
use a function to run after AJAX request done.
function clearbit (web){
var url = "myurl";
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState === 4 && request.status == 200) {
var response = JSON.parse(request.responseText.replace('[','').replace(']',''));
var clearbit_fullname = response.name.fullName;
clearbit_role = response.role;
someFunctionThatRunAfterAjaxDone(clearbit_role);
}
}
request.open('GET', url, true);
request.setRequestHeader("authorization", "Bearer sk_1be5451252ba4e31518e9b")
request.send();
}
clearbit()
// But all code you want to fun after AJAX done inside this function
function someFunctionThatRunAfterAjaxDone(clearbit_role) {
alert(clearbit_role)
}

Asynchronous request in react-native

I use this piece of code to asynchronously make a request with React-Native, but it seems like it doesn't get it. The request has been tested separately and the data should be valid.
var data = [{name: 'simon'}];
const req = new XMLHttpRequest();
req.open('GET', testedValidUrl, true);
req.send();
req.onreadystatechange = processRequest;
var name ="";
function processRequest(e) {
if(req.readyState == 4 && req.status == 200){
var response = JSON.parse(req.responseText);
data[0].name = response.name;
}
// setTimeout(()=>{},1000);
}
I thought that maybe it was because of concurrence and that the large array in the real application takes less time to construct than to get the data from the server. Adding setTimeout() did not fix it.
var data = [{name: 'simon'}];
const req = new XMLHttpRequest();
function processRequest(e) {
if(req.readyState == 4 && req.status == 200){
var response = JSON.parse(req.responseText);
data[0].name = response.name;
}
req.onreadystatechange = processRequest;
req.open('GET', testedValidUrl, true);
req.send();
var name ="";
If you set the event handler, (onreadystatechange) after you send/open the request, the readyState has already changed and thus it won't be called.

An AJAX call with JavaScript

I'm trying to learn how to make an AJAX call using vanilla JavaScript in an effort to move away from JQuery for a little project that I'm working on but don't seem to be getting past xmlhttp.onreadystatechange. Can anyone point to what I'm doing wrong (the function getDVDsAndBluRays() is getting invoked on DOMContentLoaded)? Thanks!
function getDVDsAndBluRays() {
console.log("Getting logged");
var xmlhttp = new XMLHttpRequest();
var url = 'http://www.omdbapi.com/?t=metropolis&y=&plot=short&r=json';
xmlhttp.onreadystatechange = function() {
console.log("Not getting logged");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
var myMovies = JSON.parse(xmlhttp.responseText);
myFunction(myMovies);
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
};
}
function myFunction(myMovies) {
for (var i = 0; i < myMovies.length; i++) {
var title = myMovies[i].Title.toLowerCase().split(' ').join('+');
var year = myMovies[i].Year;
console.log(title + ", " + "year");
}
}
It should be like that, notice the location of open and send functions:
function getDVDsAndBluRays() {
console.log("Getting logged");
var xmlhttp = new XMLHttpRequest();
var url = 'http://www.omdbapi.com/?t=metropolis&y=&plot=short&r=json';
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
console.log("Not getting logged");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
var myMovies = JSON.parse(xmlhttp.responseText);
myFunction(myMovies);
}
};
}
function myFunction(myMovies) {
for (var i = 0; i < myMovies.length; i++) {
var title = myMovies[i].Title.toLowerCase().split(' ').join('+');
var year = myMovies[i].Year;
console.log(title + ", " + "year");
}
}
onreadystatechange is executed after the call, you were actually "calling the service when it replies"
You have your .open() and .send() inside your onreadystatechange() handler. Put those outside of the onreadystatechange function and you should be good to go.
Onreadystatechange() is the event handler for when there is a change in state in the xmlhttp request, and will not get called until you open the request and send it.
Hope this helped!
You have put the calls to open and send inside the onreadystatechange event handler so they will never be called.
Move them outside it.

Categories