Can't get a global variable on http request function - javascript

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

Related

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

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.

Connecting JSON API for parsing

I am looking to parse the following page and extract every instance of a name. http://api.openparliament.ca/politicians/.
I have been following this guide for reference: https://www.taniarascia.com/how-to-connect-to-an-api-with-javascript/ However when it runs, there is nothing returned. What am I doing wrong?
var request = new XMLHttpRequest();
request.open('GET', 'api.openparliament.ca/politicians/?format=json', true);
request.onload = function () {
// Begin accessing JSON data here
var data = JSON.parse(this.response);
if (request.status >= 200 && request.status < 400) {
data.forEach(politicians => {
console.log(politicians.name);
});
} else {
console.log('error');
}
}
request.send();
Welcome Sean to StackOverflow.
Well, first of all you have some issues in your code.
Add the http:// in the URL in this line: request.open('GET', 'http://api.openparliament.ca/politicians/?format=json', true);.
You need to wait for XMLHttpRequest.readyState is DONE. In your code you can check the readyState property in this way:
if (request.readyState === 4) {
// Code goes here...
}
Check if the XMLHttpRequest has returned a 200 status code. You can do in this way:
if (request.status === 200) {
// Code goes here...
}
Then with the previous code you can do:
var data = JSON.parse(this.response);
Where data is an object that it has two properties: objects and pagination where objects is an array of objects and pagination is an object.
Then you can do:
data.objects.forEach(politician => {
console.log(politician.name);
});
Here is the complete demo:
(function() {
var request = new XMLHttpRequest();
request.open('GET', 'http://api.openparliament.ca/politicians/?format=json', true);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
var data = JSON.parse(this.response);
data.objects.forEach(politician => {
console.log(politician.name);
});
} else {
console.log('error');
}
}
}
request.send();
}());
Hope this helps.

Javascript make HTTP request on regular interval not working

I have a page to show the chat messages. I need to refresh the chat body every 30 seconds to load the new messages. I have set the interval to 30 seconds , the function is running , but its not making the HTTP request. Here is my code
function loadmessages(){
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/'+ ids );
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function(){
if(this.status == 200){
var resp = JSON.parse(this.responseText);
console.log(resp.message);
}
else{
console.log(this.status);
}
request.send(null);
}
}
loadmessages();
setInterval(function(){
loadmessages()
}, 30000);
Consistent indentation matters. You're putting request.send(null); inside the request.onload function, so of course it never gets sent in the first place. Try putting it outside, instead:
function loadmessages() {
var ids = document.getElementById("pid").value;
var request = new XMLHttpRequest();
request.open("get", '/refresh_message/' + ids);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.setRequestHeader("X-CSRF-TOKEN", document.querySelector('meta[name="csrf-token"]').content);
request.onload = function() {
if (this.status == 200) {
var resp = JSON.parse(this.responseText);
console.log(resp.message);
} else {
console.log(this.status);
}
}
request.send(null);
}

How to get a data from html element from ajax responseText without jquery

I'd like to get data from ajax response, but this code not working:
var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
alert(request.responseText.document.getElementById('div1').innerHTML);
}
}
The console shows this error:
Uncaught TypeError: Cannot read property 'getElementById' of undefined.
Any ideas what's causing this?
You can use DOMParser to convert html string to document fragment
var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var parser = new DOMParser();
var doc = parser.parseFromString(request.responseText, "text/html");
var elem = doc.getElementById("div1");
alert(elem.innerHTML);
}
}
alternatively, you can set the responseType to document
var request = new XMLHttpRequest();
request.open("GET", "file.html", true);
request.responseType = "document";
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
var doc = request.response;
var elem = doc.getElementById("div1");
alert(elem.innerHTML);
}
}
plnkr http://plnkr.co/edit/lkpveDD31fYY1gmflK9W?p=preview
Request object isn't a DOM element nor does it have the methods that the native DOM has.
Fix your code with:
var request = new XMLHttpRequest();
request.open("GET", "http://localhost/test/test.php", true);
request.send(null);
request.onreadystatechange = function() {
if (request.readyState == 4) {
alert(request.responseText);
}
}

Ionic controller XMLHttpRequest function doesn't work

does somebody know why this doesn't work? I get a error message at 'request.status' in Ionic
.factory('Nieuws', function() {
var url = "http://echo.jsontest.com/ID/2/bericht/test";
var request = new XMLHttpRequest();
request.open("GET", url);
var nieuws;
request.onload = function () {
if (request.status = 200) {
nieuws = JSON.parse(request.responseText);
//console.log(nieuws);
}
};
You're trying to assign a value to a read only property when you need to be making a comparison.
Replace = with ==.

Categories