I am using rest API in Javascript, Jquery to gepcoding. in this code i cant get data outside from xmlhttp.onreadystatechange = function() function
There is my Code to get data From Google API
var postdata = '{"cellTowers":[{"cellId": '+cid+',"locationAreaCode": '+lac+',"mobileCountryCode": '+mcc+',"mobileNetworkCode": '+mnc+'}]}'
xmlhttp = new XMLHttpRequest();
var url = "https://www.googleapis.com/geolocation/v1/geolocate?key=YOURKEY";
xmlhttp.open('POST',url,true);
xmlhttp.setRequestHeader("Content-Type", "application/json");
xmlhttp.send(postdata);
var lat;
var lng;
var data = '';
var json;
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if (xmlhttp.responseText)
{
var data = xmlhttp.responseText;
var json = JSON.parse(data);
lat = json.location.lat;
lng = json.location.lng;
alert(lat+""+lng); //Working [1 operation]
}
}
};
alert(lat+""+lng); //Not Working [2 operation]
in this Code i am trying to get postdata out side xmlhttp.onreadystatechange = function() function and but i get null value. because when i run program i see first [2 operation] operation after then i see [1 operation]
have any problem in my code? or give me suggestion about that problem. or can any different way to use that API
Your code works just fine. Function runs asynchronous, when event happens. It is normal that 2 operation gets executed before the answer gets back from remote API. Please let me know what makes you unhappy. Code is fine, works as intended, gets the answer from remote API when available. The answer can only be received inside the function, then you should continue calling followup code, as for you app logic from there.
Related
I have a XML http requests but for some reason it doesn't work. It is supposed to check the number of friends the person has then if there aren't enough displayed you know, do all that stuff. And don't worry, I checked the database and all the sql, it removes/adds friends successfully but the problem is that the console says it executes it but the function doesn't do anything
Here is the function :
x = document.getElementsByClassName("numoffriends");
numoffriends = x.length;
var fullurl = "../backend/friends.php?numoffriends=" + numoffriends + "&loadfriends=true";
var request = new XMLHttpRequest();
request.open("GET", fullurl , false);
request.onload = function(){
if(request.status == 200){
let testdivvv = document.createElement("element");
testdivvv.innerHTML = this.responseText;
groupchat = document.getElementById("leftsmallbox");
groupchat.append(testdivvv);
}
}
request.send();
}
setInterval(loadfriends, 1500);
If it makes any difference there are also 4 other functions on the same timing i.e gets executed. I checked, there is indeed an object called leftsmallbox.
If you have any questions just ask, I'll be available for a while
i have a function with a XML-HTTP-Request. Unfortunately i don't get back my DB-result when i call this function getUserdataByToken() <-- working, via a second Function sendPost(wall).
I just want to have the return value (array) inside my second function but the value is always "undefined". Can someone help me?
function getUserdataByToken() {
var token = localStorage.getItem("token");
var userDataRequest;
//-AJAX-REQUEST
var xhttp;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var url= window.location.protocol+"//"+window.location.host+"/getuserdatabytoken";
var param = "token=" + token;
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
userDataRequest = JSON.parse(xhttp.responseText);
if (userDataRequest.success === "false") {
warningMessage('homeMessage', false, userDataRequest.message);
} else {
return userDataRequest;
}
}
};
xhttp.open("POST", url, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(param);
}
Function call via second Function (AJAX) leads too "undefined" Value for "userDataRequest" (return of function 1).
function sendPost(wall) {
var content;
var token = localStorage.getItem("token");
var userData = getUserdataByToken(); // PROBLEM
console.log(userData); // "leads to undefined"
alert(userData); // "leads to undefined"
… Ajax Call etc…
P.S. it's my first post here in stackoverflow, I'm always grateful for tips.
Thanks!
The userdata value only exists within the anonymous Ajax callback function, and you only return it from there. That is pointless because there is nowhere for it to be returned to; certainly the value does not get returned from getUserdataByToken. Don't forget that Ajax calls are asynchronous; when sendPost calls getUserdataByToken the request won't even have been made.
Generally you'd be much better off using a library like jQuery for this whole thing. Apart from making your code much simpler, it will allow you to use things like Promises which are explicitly intended to solve this kind of problem.
(And, do you really need to support IE5? Are you sure?)
Just to point out, I know how to do this with jQuery and AngularJS. The project I am currently working on requires me to use plain JavaScript.
I'm trying to get AJAX to work with just plain JavaScript. I am using Java/Spring for backend programming. Here is my JavaScript code:
/** AJAX Function */
ajaxFunction = function(url) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.status == 200) {
var JSONResponse = JSON.parse(xhttp.responseText);
return JSONResponse;
}
}
xhttp.open('GET', url, true);
xhttp.send();
}
/** Call Function */
searchResults = function() {
var test = ajaxFunction('http://123.456.78.90:8080/my/working/url');
console.log(test);
}
/** When the page loads. */
window.onload = function() {
searchResults();
}
It's worth noting that when I go directly to the URL in my browser's address bar (example, if I go directly to the link http://123.456.78.90:8080/my/working/url), I get a JSON response in the browser.
When I hover over xhttp.status, the status is saying 0, not 200, even though I know that the link I am calling works. Is this something that you have to set in Spring's controllers? I didn't think that was the case because when I inspect this JS URL call in the Network tab, it states that the status is 200.
All in all, this response is coming back as undefined. I can't figure out why. What am I doing wrong?
An XMLHttpRequest is made asynchronously meaning that the request is fired off and the rest of the code continues to run. A callback is provided and when the asynchronous operation completes the callback function is called. The onreadystatechange function is called upon completion of an AJAX request. In your example the ajaxFunction will return immediately after the xhttp.send() line executes, so your var test won't have the JSON in it as I assume you expect.
In order to do something when an AJAX request completes you need to use a callback function. If you wanted to log the result to the console as above you could try something like the following:
var xhttp;
var handler = function() {
if(xhttp.readyState === XMLHttpRequest.DONE) {
if (xhttp.status == 200) {
var JSONResponse = JSON.parse(xhttp.responseText);
console.log(JSONResponse);
}
}
};
/** AJAX Function */
var ajaxFunction = function(url) {
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = handler;
xhttp.open('GET', url, true);
xhttp.send();
};
/** Call Function */
var searchResults = function() {
ajaxFunction('http://123.456.78.90:8080/my/working/url');
};
/** When the page loads. */
window.onload = function() {
searchResults();
};
If you want to learn more about how XMLHttpRequest works then MDN is a much better teacher than I am :)
This is my HTML text:
<input type="text" class="resizedsearch" name="searchdb">
<button id="submit" onclick="ajaxCall()">Search!</button>
This is Javascript:
ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
}
And this is where I am trying to display the response that I am receiving from the PHP file:
<b><font size="24" face="Cambria"><p id="democity"></p></font></b>
<font size="6" face="Cambria"><p id="demodes"></p></font>
</br>
The output of the PHP file is stored in $outp and it is in the JSON format.
Any help appreciated. Thank you.
!!UPDATE!!
function ajaxCall()
{
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080/CSE%205335%20Project%20One/userInfo.php";
xmlhttp.onreadystatechange=function()
{
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
myFunction(xmlhttp.responseText);
}
}
}
function myFunction(response)
{
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML =
obj.city;
document.getElementById("demodes").innerHTML =
obj.description;
document.getElementById("latlon").innerHTML =
obj.latitude + "," + obj.longitude;
}
This is how the improvised code looks. Still not working.
Example by FactoryAidan is not going to work as it violates Same Origin Policy (unless you'll run the code in browser console on Google page). Try replacing http://www.google.com with your local address. I tested the code with a little modification and it works, or at least gives alert, so the function is called. Here's it is:
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://localhost:8080"; /* but make sure the url is accessible and of same origin */
xmlhttp.onload=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here');
}
Your code update after my first answer looks like it was done in haste and I think makes the question a little harder. The .open() and .send() methods ended up inside your .onreadystatechange function definition but they need to be outside. Your first one didn't have those placement issues. The code I wrote below has your exact building blocks but with no placement issues so you should be able to follow along with how it matches your example code. I also tested it and it sucessfully sends and receives data back and successfully calls the myFunction() callback function.
Nonetheless, I took your code and rewrote it a bit. If you get an alert('') message when you run it, that means that your xml request worked perfectly. If you don't see an alert('') message. It means your xml request is returning a http 404 error, which means your request URL is bad. Try changing your request URL to something you know won't give you a 404 error, like 'http://www.google.com'. If it works and you get the alert message, then the only problem is that your localhost:8080 url is a bad url.
Also, in your myFunction callback function, javascript treats line-breaks as the end of a line of code. So you must write assignments that use an '=' sign on the same line with no line-breaks. Due to this javascrit principle, you also don't need a semicolon ';' at the end of a single line like you would in PHP script.
Finally, a big cause of errors can be the JSON.parse() call. The data received MUST be a valid json string. So if the URL you call returns anything other than pure json... your myFunction() callback function will break on the JSON.parse() command.
Lastly, if there is an error in your myFunction() callback function, your browser inspector will not report it in a useful way and will instead throw an error that points to your xmlhttp.onreadystatechange=function(){} as being the culprit because that is where the browser thinks the error resides (being the calling function), even though the real error is in your myFunction() callback function. Using my edit of your ajaxCall(){...} code and with a valid url, you can be positive that the ajax call works and any errors you have are in your myFunction() callback function.
Lastly again, You have to be careful in your callback function because there are so many things that could break it. For example, document.getElementById() will cause an error if no html element exists on your web-page with the id you provided. Also, if the JSON you received back from the ajax call is missing any properties you mentioned like (city or latitude) it is likely that the innerHTML will be set to 'undefined'. But some browsers may treat the missing json properties as an error instead of just saying they are 'undefined' when you try to call them.
function ajaxCall(){
var xmlhttp = new XMLHttpRequest();
var url = "http://www.google.com";
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send('searchdb');
}
function myFunction(response){
alert('I made it here')
/*
var obj = JSON.parse(response);
document.getElementById("democity").innerHTML = obj.city
document.getElementById("demodes").innerHTML = obj.description
document.getElementById("latlon").innerHTML = obj.latitude + "," + obj.longitude
*/
}
I am trying to figure out the best way to handle this scenario. Basically I want the flow to work like this:
1.) Get configuration data from server (async)
2.) Run doStuff() after configuration data is received (async)
3.) Run postResults after doStuff() completes
Currently I seem to have this flow working using PubSub.js, however I am trying to figure out how I can provide the results from config data (#1) to postResults (#3). While I seem to have the flow working with PubSub, I'm not sure how to access the configuration (#1) callback data from postResults (#3)
Here is a code summary:
PubSub.subscribe('config', doStuff());
fetchConfigurations();
function fetchConfigurations () {
var req = new XMLHttpRequest();
var url = CONFIGURATION_SERVER_URL;
req.onreadystatechange = function() {
if (req.readyState == 4 && req.status == 200) {
var configObject = eval('(' + req.responseText + ')');
PubSub.publish('config', configObject);
} else {
console.log("Requesting config from server: " + url);
}
}
req.open("GET", url, true);
req.send(null);
}
function doStuff() {
PubSub.subscribe('results', postResults);
var results = {};
// do some async work...
results['test1'] = "some message";
results['test2'] = "another message";
PubSub.publish('doStuff', results);
}
function postResults (doStuffId, doStuffData) {
var req = new XMLHttpRequest();
var url = TEST_RESULTS_URL; // I want to get this from the configObject is get in fetchConfigurations
req.open("POST",url,true);
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
req.send(doStuffData['test1'] + doStuffData['test2']);
}
Using promise seemed like the a better fit for this problem instead of pub/sub, here is the implementation I ended up using:
https://github.com/hemanshubhojak/PromiseJS