I have a one variable file like this.
var geography = [
{ id:"Country", header:"", width:150},
{ id:"Capital", header:"Capital", width:150},
{ id:"Falg", header:"Falg", width:150},
{ id:"Language", header:"Language", width:150},
{id:"Population", header:"Population", width:150},
],
Now I wanted to load this data from the json. I placed this data into JSON file and Using this code.
getGeography function(){
var geography;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "data.json",true);
}
Now from here how to store into a variable and return that.
It should be read when the ready state of xmlhttp is 4 and response status is 200. You should parse the response with JSON.parse(). However you can't return the value from the function. Because XMLHTTPRequest is asynchronous by default.
function getGeography() {
var geography;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "data.json",true);
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
geography = JSON.parse(xmlhttp.responseText;)
}
}
}
Instead of returning geography you have to programmatically read the value of geography when the AJAX request is complete. Something like this (read this):
Instead of writing code like this:
function anotherFunc() {
var geography = getGeography();
thenDoSomething(geography);
}
Write like this:
function anotherFunc() {
getGeography();
}
function getGeography() {
var geography;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "data.json",true);
xmlhttp.onreadystatechange = function () {
if(xmlhttp.readyState === 4 && xmlhttp.status === 200) {
geography = JSON.parse(xmlhttp.responseText);
thenDoSomething(geography);
}
}
}
It's like handing over the control of execution of rest of the code to getGeography() function, instead of expecting a return value from the function and then using that value. The getGeography() function resumes execution of rest of the code with the value received from AJAX response, when the AJAX call completes.
I'm not a fan of jQuery but in this case, you would probably benefit from this.
$.get( "ajax/test.html", function( data ) {
// data is your result
console.log(data);
console.log(JSON.parse(data));
});
https://api.jquery.com/jquery.get/
Here is how to use XMLHttRequest() :
<script>
const req = new XMLHttpRequest();
var geography = [];
req.onreadystatechange = function(event) {
// XMLHttpRequest.DONE === 4
if (this.readyState === XMLHttpRequest.DONE) {
if (this.status === 200) {
geography = JSON.parse(this.responseText);
console.log(geography);
alert("Great Success : check console !");
} else {
alert("Something has gone really Bad !");
}
}
};
req.open('GET', 'data.json', true);
req.send(null);
Be careful to use correct JSON :
[
{"id":"Country","header":"","width":150},
{ "id":"Capital","header":"Capital", "width":150},
{ "id":"Falg","header":"Falg","width":150},
{ "id":"Language","header":"Language", "width":150},
{ "id":"Population", "header":"Population", "width":150}
]
Related
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.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
I've got two functions in Javascript. One gets JSON data from a php file.
{"company_name":"","job_title":"Superhero","unix_time_convert":"Posted 06th of September '18","link":"2"}
The javascript function to return the JSON is this:
function assignJsonData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = (this.response);
return data;
//alert( data );
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
Notice that alert( data ); will return the JSON data in a box.
But when I assign the function to a variable elsewhere like so, it returns undefined.
window.onload = function () {
var data = assignJsonData();
alert(data);
}
What am I missing here?
Sorry to ask, I've been on this for hours...
Thanks
Andy
You should use callBack to retrieve data from ajax request , and get data when ajax request is finieshed , your could should look like :
function assignJsonData(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.response);
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
window.onload = function () {
assignJsonData(function(data){
alert(data);
});
}
As Jafar pointed, you should use a callback!
If you want to check the order the things is executed, run the code bellow.
var returnData = "";
function assignJsonData() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
console.log(this.readyState, this.status);
if (this.readyState == 4 && this.status == 200) {
returnData = this.response;
console.log('enter');
//console.log(this.response);
//return data;
//alert( data );
}
};
xmlhttp.open("GET", 'https://jsonplaceholder.typicode.com/todos/1', true);
xmlhttp.send();
}
assignJsonData();
console.log("returnData: " + returnData);
XMLHttpRequest is asynchronous. You need to either use a callback or a Promise.
function assignJsonData(callback) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = this.response
callback(data)
}
};
xmlhttp.open("GET", 'test_echo.php?row=1', true);
xmlhttp.send();
}
window.onload = function () {
assignJsonData(function(data) {
alert(data)
});
}
You need to use Promise.
Check - How do I promisify native XHR?
You don't have the data in alert, because the response is not ready I guess.
hello sorry for the question but i don't know like to do what i want...
If i run this link https://api.onwater.io/api/v1/results/10,10 API say if this point (latitude 10°N; longitude 10°E) is in water or land.
the result in this case is:
{"lat":9.999237824938984,"lon":10.000257977613291,"water":false}
How i can to print value's water ??
Thanks a lot
Assuming you are looking for an AJAX Call you can do it with pure JS like this
function callAjax() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE) { // XMLHttpRequest.DONE == 4
if (xmlhttp.status == 200) {
var response = JSON.parse(xmlhttp.responseText);
document.getElementById("myDiv").innerHTML = response.water;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400');
}
else {
alert('something else other than 200 was returned');
}
}
};
xmlhttp.open("GET", "https://api.onwater.io/api/v1/results/10,10", true);
xmlhttp.send();
}
callAjax();
<div id="myDiv"></div>
Using jquery would be like this
$.ajax({
url: "https://api.onwater.io/api/v1/results/10,10",
context: document.body,
success: function(data){
console.log(data.water);
}
});
Normally you could access it by its property name:
const response = {"lat":9.999237824938984,"lon":10.000257977613291,"water":false}
console.log(response.water);
Assume that you're retrieving the data through AJAX
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if (this.readyState === 4 && this.status === 200){
// parse the response to object
var obj = JSON.parse(this.responseText);
// print it out (obj.water and obj['water'] produces the same result)
alert(obj.water);
console.log(obj['water']); // prints it in console
}
};
xhr.open("GET", "https://api.onwater.io/api/v1/results/10,10", true);
xhr.send();
You can learn more about AJAX here.
somehow this code just blanks and isn't really doing anything.
Doesn't even show any errors.
So can Someone help?
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
mycon; //calls the makeAnn() Function
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
function makeAnn(){
return function(){
console.log(jsonReturn);
if ( jsonReturn !== "NO"){
alert("Announcement Was Posted");
} else {
alert("Error Encoding Data");
}
} //end of return function()
}
function mainFunction(){ //is called by an onclick event
var myvar = "I Shall Return!";
connectStart(makeAnn()); // i used invocation to combine them
}
Somehow it never shows any actual complaints or anything on the console log.
No alerts or whatever.
Doesn't write the data sent to the php or database.
No nothing really.
And I have tried the Php and html, their both fine.
It's just this part of my code that won't work.
You are not calling the function inside your onreadystatechange handler. See below.
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
// mycon; //wouldn't do anything
mycon(); // THIS should work better...
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
EDIT:
The other problem which I now noticed is that you are referencing jsonReturn way, way out of its scope.
function connectStart(mycon){ //connection start for contacting
return function(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonReturn = JSON.parse(this.responseText);
mycon(jsonReturn); // pass jsonReturn as a parameter
}
};
// mypref() stands for the preference code location for the myphp.php
xmlhttp.open("GET", mypref()+"myphp.php?q="+myvar,true);
xmlhttp.send();
}
}
function makeAnn(){
return function(jsonReturn){ // pass in as a parameter
console.log(jsonReturn);
if ( jsonReturn !== "NO"){
alert("Announcement Was Posted");
} else {
alert("Error Encoding Data");
}
} //end of return function()
}
function mainFunction(){ //is called by an onclick event
var myvar = "I Shall Return!";
connectStart(makeAnn()); // i used invocation to combine them
}
I'm trying to import some data through a PHP file with this function:
sendJsonRequest("initial", startID);
json = JSON.parse(request);
function sendJsonRequest(type, id) {
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
request = xmlhttp.responseText; //writing the response in an already defined variable
}
}
xmlhttp.open("GET","../RequestHandler.php?"+type+"_"+id,true);
xmlhttp.send();
}
The import of the data works very well. My problem now is that I want to use my request right after calling this function, to which point it's still not available (I realized this happens because onreadystatechange runs as function independently), therefore I have to put in some delay until it is so. I find the use of setTimeout or setInterval very uncomfortable, since those aren't blocking the code and I had to refactor some of my code very badly and inefficient. That's why I was looking for a way to modify/block out the function at its end, until the request is available, but neither using an empty while-loop nor the wait/pause/sleep-functions are recommended. Can anybody figure out another way to accomplish this?
Could you just pass a callback?
function sendJsonRequest(type, id, callback) {
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
request = xmlhttp.responseText; //writing the response in an already defined variable
if(callback) {
callback(request);
}
}
}
xmlhttp.open("GET","../RequestHandler.php?"+type+"_"+id,true);
xmlhttp.send();
}
and use it like:
sendJsonRequest("initial", startId, function(req) {
var json = JSON.parse(req);
});
Try utilizing Promise
var sendJsonRequest = function sendJsonRequest(type, id) {
return new Promise(function (resolve, reject) {
if (window.XMLHttpRequest) {
var xmlhttp = new XMLHttpRequest();
} else {
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
request = xmlhttp.responseText;
resolve(request);
}
}
xmlhttp.error = reject;
xmlhttp.open("GET","../RequestHandler.php?"+type+"_"+id,true);
xmlhttp.send();
}
sendJsonRequest("initial", startID)
.then(function(data) {
// do stuff
var json = JSON.parse(data);
console.log(json);
}, function err(e) {
console.log(e);
});