Wait for Json call to be completed in javascript - javascript

I am using the below json call in my javascript method
function go123(){
var cityName = "";
var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) {
if (data.properties.city != null){
cityName = data.properties.city;
check = true;
} else {
cityName = "NaN"
}
}); // end of my Json Call.
// my validation is done below
if(cityName != "NaN"){
return false;
} else {
// here I except the cityName to not be "" but be some value which is set as :cityName = data.properties.city;
return true;
}
} // end of my function
Now what problem I am facing is that before my Json call is compelete the next set of statements ( in the code below the line "// my validation is done below " ) is already executed.
I want to get the values set in my json call (cityName) and only once when the call is completed then only I want the next set of statements to be executed.
Please help me on this. Any advice/ideas/suggestions will be highly appreciated ! Thanks.

The function you passed into $.getJSON() is the callback run when the function completes successfully. All else being equal, stick the "rest of it" inside that method. If you can't do so, what you're after is called a jQuery Deferred. See http://www.erichynds.com/jquery/using-deferreds-in-jquery/ and http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ for code that looks like so:
var req = $.getJSON('blah', 'de', 'blah');
req.success(function(response){
// The request is done, and we can do something else
});

AJAX calls are asyncrhonous. They don't wait for the reply. They operate in the background and execute the code that follows it immediately after the call. Therefore, the data received in getJSON is not yet there when the operations below it are executed.
You can put the operations you want in the callback so that they get executed when the data is revceived:
function go123(callback){
var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) {
//execute the callback, passing it the data
callback(data);
});
}
//when you call go123, it get's back the result:
function goBefore123(){
//get our JSON
go123(function(data){
//when we get our data, evaluate
if (data.properties.city != null){
cityName = data.properties.city;
check = true;
alert('executed after returned');
afterCall();
} else {
cityName = "NaN"
}
});
alert('i am executed before anything else');
}
function afterCall(){
alert('im also executed after');
}

Calling an external url will take too much time, wait for the result
Check below
var jqxhr = $.getJSON("example.json", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
http://api.jquery.com/jQuery.getJSON/

.success
http://api.jquery.com/jQuery.getJSON/

Related

how to get data outside javascript function

im wondering if i can get some help here, im not a skilled coder by far, but im trying to retrieve results outside the function and the result in log im getting is Undefined
var pricecrex;
getDataFromAPI("https://api.crex24.com/CryptoExchangeService/BotPublic/ReturnTicker?request=[NamePairs=BTC_WAGE]",
true,
function(data){
var resultcrex = JSON.parse(data);
if (resultcrex !== "undefined") {
if (resultcrex) {
var pricecrex = resultcrex.Tickers[0].Last
}
else {
msg.reply("0")
}
}
}
);
console.log(pricecrex);
It is because Ajax requests are async. console.log() gets executed before response is received from request, and thus before setting value in pricecrex. So you were getting undefined.
var pricecrex;
getDataFromAPI("https://api.crex24.com/CryptoExchangeService/BotPublic/ReturnTicker?request=[NamePairs=BTC_WAGE]",
true, function(data) {
var resultcrex = JSON.parse(data);
if (resultcrex !== "undefined") {
if (resultcrex) {
pricecrex = resultcrex.Tickers[0].Last;
print(pricecrex);
}
else {
msg.reply("0")
}
}
}
);
function print(data) {
console.log(data);
}
The nature of Javascript is continue running code once an asynchronous function has been started. So you run getDataFromAPI(), and then while that's running, the interpreter goes to the next piece of code, which is your console.log(pricecrex).
So you can either run the console.log(pricecrex) directly in the callback, function(data){}, or to keep things cleaner, wrap your console.log() within a function and call that function from within your callback.
Example:
let someVar;
someAsync('someurl.com', (data) =>{
someVar = data;
callTheConsole()
})
function callTheConsole(){
console.log(someVar)
}
Instead of assigning the value to the variable. Pass it to another function. Thus the value passed to another function is not 'undefined'.
function validation(pricecrex){
console.log(pricecrex);
}
getDataFromAPI("https://api.crex24.com/CryptoExchangeService/BotPublic/ReturnTicker?request=[NamePairs=BTC_WAGE]",
true,
function(data){
var resultcrex = JSON.parse(data);
if (resultcrex !== "undefined") {
if (resultcrex) {
var pricecrex = resultcrex.Tickers[0].Last;
validation(pricecrex);
}
else {
msg.reply("0")
}
}
}
);
For more information, check out the below link. Detailed information with examples is available.
How to return the response from an asynchronous call??

JavaScript - slow down a loop

I have these codes in controller that call webservice using $http get to retrieve some data. Here is the following code:
UPDATE CODES:
var boolGetBoothCoords = false;
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
var data = response.data
console.log('data', data.arrBoothDesignatedCoords)
boothDesignatedCoords = data.arrBoothDesignatedCoords;
boolGetBoothCoords = true;
})
console.log("boothDesignatedCoords ", boothDesignatedCoords ); // undefined
// And a lot of other codes
However, since $http get is asynchronous method, the program will invoke the console log and the codes after immediately and boothDesignatedCoords will be undefined. I do not want that. I want the program to invoke the console log and the codes after ONLY when the webservice consumption is completed. So I did the following using this answer: how to slow down a javascript loop:
go();
function go() {
console.log("hello");
if (boolGetBoothCoords == false) {
setTimeout(go, 1000);
}
else
{
}
}
go()
console.log("boothDesignatedCoords ", boothDesignatedCoords ); // undefined
// OTHER CODES that uses variable boothDesignatedCoords will be undefined as well
However, I do not know why it will still invoke the console log but the web service consumption is not completed yet, despite using this method. Can someone please help me? Thanks.
setTimeout is asynchronous, so actually you don't really make a difference calling go function.
What will happen is:
call go() function
call setTimeout inside the function - that will schedule go to be called in (roughly) 1s
call console.log immediately after that
What you probably want is to put your console.log in then callback like that:
var boolGetBoothCoords = false;
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
return response.data.arrBoothDesignatedCoords;
})
.then(function(boothDesignatedCoords) {
console.log("boothDesignatedCoords ", boothDesignatedCoords );
});
The other option (not recommended) would be to put console.log in the else part of the if statement in your go function.
In this case, you should also define boothDesignatedCoords before the whole code snippet.
The code that suppose to be run after the response, should be invoked after the response.
var boolGetBoothCoords = false;
BoothDesignatedCoordsService.getBoothDesignatedCoords(
strListShortListedBooth[i], 3)
.then(function(response) {
var data = response.data
console.log('data', data.arrBoothDesignatedCoords)
boothDesignatedCoords = data.arrBoothDesignatedCoords;
boolGetBoothCoords = true;
codeThatUsesTheResponseData();
});
function codeThatUsesTheResponseData() {
console.log("boothDesignatedCoords ", boothDesignatedCoords ); // undefined
// And a lot of other codes
}

jQuery submit form calls a function with ajax

jQuery(document).ready(function(jQuery) {
function checkEmail(email){
jQuery.post('someroute.php',
{email:eamil},
function(data){
if(data==error){
return false;
}
);
return true;
}
jQuery('#myform').submit(function(){
// como code and at the momment this
var result true;
//then I check email
var email = ('#myemail').val();
result = checkEmail(email);
return result;
});
The problem is this, a checkEmail function, first return true, and then return value jQuery.post function. Why?
I checked and in submit, first return true, and if you stop submit then you release that post return the value. Post works fine, but I don't understand why function checkEmail does not wait until post returns the value and goes on until the end to return true.
Because the jQuery.post() function is an AJAX request, and the first A in AJAX stands for asynchronous. That's exactly what asynchronous is, it doesn't stop code execution while it waits for a response. It fires the request and then immediately moves on to any code after the line making the request, in this case your return true statement.
Like Anthony Grist said. .post is an asynchronous call which means it doesn't wait to finish.
I've looked up the .post method (http://api.jquery.com/jQuery.post/).
It's basicly a shortcut for .ajax. You're missing the fail method in here so I would say use the .ajax call.
var value = 1;
var handlerUrl = "someroute.php";
//Do the Ajax Call
jQuery.ajax(
{
url: handlerUrl,
data: { email:eamil },
type: 'POST',
success: function (data)
{
return true;
},
error: function (jxhr, msg, err)
{
return false;
}
});
#user1727336 : Hi! You might want to edit your code and add the missing } and });. Here's a fix:
// enter code here
jQuery(document).ready(function(jQuery) {
function checkEmail(email){
jQuery.post('someroute.php', {email:eamil},
function(data){
if(data==error){
return false;
}
});
return true;
}
});

Jquery get text file and return the value to other function

Can any one help me what im wrong in
function separateerror()
{
var jqxhr = $.get("/errormsg.txt", function(data) {
line = data;
array = line.split(',');
getmsg=array[0];
})
return getmsg;
}
i need to return "getmsg" to another function, but its not working, where as if i add alert inbetween
function separateerror()
{
var jqxhr = $.get("/errormsg.txt", function(data) {
line = data;
array = line.split(',');
getmsg=array[0];
})
//alert(getmsg)
return getmsg;
}
the value returns, what wrong im doing in code?
$.get is an async call and what happens is that if you add an alert in between, you give time for the async call to finish and then your value is already set by the time the separateerror function finishes. Otherwise, the separateerror function returns before the $.get call finishes and then your getmsg is probably still a null value.
While working with async calls you should not use this simple model of calling functions and expecting theirs values in return, you should use callback functions to accomplish that the right way.
EDIT:
Also, you should handle the $.get error callback, in case something happens and you can not load the txt file.
function separateerror()
{
var jqxhr = $.get("/errormsg.txt", function(data) {
line = data;
array = line.split(',');
getmsg=array[0];
dosomething(getmsg);
})
.error(function() { alert("error"); });
}
function dosomething(msg) { ... }
Insert that to the top of your script. That /should/ fix it.
$.ajaxSetup({
async: false
});

Getting undefined via ajax JSON

when I check the log from Console using chrome browser, I keep getting sideType is undefined. It is not returning data to sideType variable.
when I put console.log(sideType); in the sideGroupData() function - it work fine without problem.
Code:
function sideGroupData(GroupID) {
$.getJSON("group_data.php",{GroupID:GroupID}, function(j){
return j;
});
}
function reloadProduct(productID) {
$.post("product.php", { productID:productID }, function(data) {
var sideType = sideGroupData(123);
console.log(sideType);
});
}
reloadProduct(999);
It's because you're running your call in a closure. The ajax call is being made asynchronously, which means that your code continues moving even though you're making an ajax call:
function setVar () {
var retVal = 1;
$.ajax(..., function(data){
retVal = data; //retVal does NOT equal data yet, it's still waiting
});
return retVal; //will return 1 every time because code doesn't wait for ajax
}
var someVar = setVar(); // will be 1
If you want to return that value, include a callback function to run when the data is returned, and run it with the data supplied, like so:
function sideGroupData(GroupID, callback){
$.getJSON('group_data.php', {GroupID: GroupID}, callback);
}
function reloadProduct(productID) {
$.post("product.php", { productID:productID }, function(data) {
sideGroupData(123, function(sideType){
console.log(sideType);
});
});
}
or, just make the call inside the function itself:
function reloadProduct(productID, groupId) {
var prod, sideType;
$.post("product.php", { productID:productID }, function(data) {
prod = data;
$.getJSON('group_data.php', {GroupID: groupId}, function(json){
sideType = json;
// you now have access to both 'prod' and 'sideType', do work here
});
});
}
the sidegroupdata() function call will return immediately - it'll trigger the ajax request and keep on executing. That means sideType is being assigned a null value, because sideGroupData doesn't actually explicitly return anything after the ajax call section.
Is there any reason you're doing an ajax request WITHIN an ajax request? Wouldn't it make more sense to modify the product.php page to return a data structure containing both that product ID AND the 'sidegroupdata' included in a single response?

Categories

Resources