scope of var in jquery function? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does Asynchronous means in Ajax?
why my var "temp" is 0 after the ajax?
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}

Because the ajax call is asynchronous, so temp is returned before being updated ...

Because the success function doesn't run until the HTTP response is comes back from the server.
Ajax is asynchronous.
Do what you want to do with the data in the success function (or in functions you call from it).
Don't try to wait for a response and then return data to a calling function.

Ajax calls are asynchronous but you can use CommonJS Promises/A pattern to achieve what you want. jQuery provides it's own implementation of it: jQuery.Deferred().

As others have mentioned here, because ajax is asynchronous, you're not guaranteed to get the updated temp variable before your return statement. It would be best to work within your success function. However, if you absolutely have to wait for that call to finish and return the temp variable, you can make it Non-asynchronous by adding async: false
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
async: false,
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}

S.ajax/$.post/$.get etc etc, all these are asynchronous process (which means, you will come out of the loop even before $.ajax is completed, even though it will be going to server side after coming out of the loop)
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
.............
..............
}
});
return temp;
}
So just after the loop if you will check, the following statement might not have executed(depending upon the data set).
temp = parseFloat(myJSONObject.bindings[0].value);
so to check the data in temp variable you should put a debugger/alert inside $.ajax. example :
function calc7() {
var temp = 0;
$.ajax({
type: "POST",
url: 'Helpers/CalcResult7.ashx',
data: { GU_ID: '<%=Request.QueryString["GUID"] %>' },
success: function (data) {
list1 = eval(data);
temp = parseFloat(myJSONObject.bindings[0].value);
alert(temp);
$("#<%=ProResult7.GetSpanId %>").text(addCommas(temp));
}
});
return temp;
}
now you will get the value of temp

Related

JS Function including AJAX returning undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
function idToUnitNum(id){
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
console.log(result);
return result;
}
});
}
This is the function. It's called from another function. I tried testing it's output by logging result before it returns, and it displays the appropriate result.
Result (JSON):
{"success":"true","time":1524462577,"data":"ADMIN"}
However, when I try catching the variable (a string), it does shows as "undefined".
It's probably a stupid mistake.
Calling the function:
var unitnum = idToUnitNum(adata.arresting_officer);
console.log(unitnum);
Thank you for your assistance!
pass callback function to idToUnitNum. something like below
function idToUnitNum(id,callback){
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
console.log(result);
callback(result);
}
});
}
Hi Please change the AJAX function like this :
function idToUnitNum(id){
var dfd = $.Deferred();
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
var result = ofd.data;
dfd.resolve(result);
// return result;
}
});
return dfd.promise();
}
And you can use this function like this
idToUnitNum(adata.arresting_officer).done(function(response){
console.log(response);
});
FYI : not tested code
function idToUnitNum(id){
var result = '';
$.ajax({
type: "POST",
url: "ajax_officerFromId.php",
async: false,
data: {'id': id},
success: function(dataString) {
ofd = JSON.parse(dataString);
result = ofd.data;
}
});
return result;
}
Thank you to whoever suggested I turn off async and call it outside fo the AJAX request. Solved the issue.
You should either use a callback function as a parameter or, even better, use promises. Simply put return in front of your ajax call and call .then() on the return value to read the result when it is available.
This has been asked many times, so you shouldn’t have any trouble finding more information about these solutions

Javascript global variables not updating properly [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I need lines to be a global array but when I use console.log to compare values inside the function and outside the function, the inside one works fine but the outside one remains empty. Am I missing something here?
var lines = new Array();
$.ajax({
type: "GET",
url: "posts_replied_to.txt",
success: function(content) {
console.log("success");
lines = content.split('\n');
console.log(lines);
},
error: function() {
console.log("error");
}
});
console.log(lines);
The problem here is not regarding global variables. Its the asynchronicity problem.By the time the console.log() outside your ajax request is called, the ajax success callback is not called.Thats why you won't get the right value.
async function doAjax() {
return await $.ajax({
type: "GET",
url: "posts_replied_to.txt"
});
}
let lines = await doAjax()
lines = content.split('\n')
console.log(lines)
Try this code using
Async to get the expected result.
Yes,AJAX is asynchronous function.So, in outside 'console.log(lines)' command run before AJAX.
You can AJAX asyn:false
What does "async: false" do in jQuery.ajax()?
Before your GET response come your second console.log code also execute due to ajax is not async. Change as below,
var lines = new Array();
$.ajax({
type: "GET",
url: "posts_replied_to.txt",
async: false,
success: function(content) {
console.log("success");
lines = content.split('\n');
console.log(lines);
},
error: function() {
console.log("error");
}
});
console.log(lines);
Try using promise object returned by ajax call.
var lines = new Array();
var promise_obj = $.ajax({
type: "GET",
url: "posts_replied_to.txt"
}).promise();
promise_obj.done(function(response)
{
lines = response.split('\n');
console.log(lines);
// Rest of your logic goes here where you want to use lines.
});

Jquery Ajax Call Return

I have made a function which is the one below that i pass data to and returns the result as is. I made this way because i will be needing a lot of ajax call and i just made a function that i pass the data to and get the result as is and work with the result.
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}});
return ret;}
Now i am calling it where i need it:
$('#register-name, #register-surname').keyup(function(e) {
var x = FunctionsCall({query: $(this).val(), funcid: 1});
(x!==1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });
But strange is that i always see x as undefined. Pointing out the ret is filled with either 1 or 0 i don't know why it is not being passed to x.
Can you please help me out? It might be simple but i just experiment when needed with javascript and jquery.
Regards
ret doesn't get set until the success function runs, which is when the ajax finishes. FunctionCall returns straight away however. You'll either need to return the ajax deferred object or put your addClass/removeClass functionality in your success function.
A way to add your addClass/removeClass functionality to your success function would be like this:
function FunctionsCall(data, successFn) {
$.ajax({
type: 'GET',
url: 'includes/helpers/functions.php',
dataType: "json",
data: data,
success: successFn
});
}
$('#register-name, #register-surname').keyup(function(e) {
var element = $(this);
var data = { query: element.val(), funcid: 1 };
var successFn = function(x) {
if (x !== 1) {
element.addClass('input-has-error')
} else {
element.removeClass('input-has-error');
}
}
FunctionsCall(data, successFn);
});
The problem is that the ajax call takes time to execute, whereas your processing of x is immediately after the call to FunctionsCall
Imagine that in order to go to the php file and get the result, the browser has to send a request over the wire, the server needs to process the request and return the value, again over the wire. This process takes an unpredictable amount of time as it relies on network connections and server specs / current load.
The code to call the function and process the result happens immediately after this step and as such won't have the required values when it is run (browsers are much quicker at executing the next step than networks are at processing requests).
The best thing to do is to wrap your processing code up in it's own function, so it isn't immediately called, then call that function with the result once you get it. Like this:
// function defined, won't be called until you say so
var processMe = function(result) {
alert(result);
}
$.ajax({
// ajax params
success: function(result) {
// function called within success - when we know the request is fully
// processed, however long it takes
processMe(result));
}
});
You could also do the processing directly in the success block but the advantage of using a function is it's there to re-use in the future, plus, you also get to give it a nice understandable name, like outputValidatedMessage.
you must send ajax request syncronous
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
async: false,
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}
});
return ret;
}
Ajax calls are asynchronous.
This means that while you call $.ajax(), the function continues to run and return x which is undefined, as the ajax response has not been send yet.
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
async: false,
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
}
});
return ret;
}
The below should work for you
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
(result !==1 ) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error'); });
}});
}
maybe is because the ajax function is called asynchronously so the line var x= .... doesn't wait for the asignment and thats why is undefined. for that you should use a promise here is an example http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/
http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html
check if the following works, may be your GET method is taking time to execute.
var x;
function FunctionsCall(data){
var ret;
$.ajax({
type:'GET',
url: 'includes/helpers/functions.php',
dataType:"json",
data: data,
success: function(result){
ret = result;
x= result;
alert(x)
}});
return ret;}
if the snippet works, you should make you synchronous async: false or make callback function
try this code.
function FunctionsCall(data,callback) {
try {
ajax({
type: 'GET',
url: 'includes/helpers/functions.php',
dataType: "json",
data: data,
success: function (result) {
callback(result);
}
});
} catch(e) {
alert(e.description);
}
}
$('#register-name, #register-surname').keyup(function (e) {
var data = {
uery: $(this).val(),
funcid: 1
};
FunctionsCall(JSON.stringify(data), function (result) {
(result !== 1) ? $(this).addClass('input-has-error') : $(this).removeClass('input-has-error');
});
});

Ajax jsonp data to an array using Jquery [duplicate]

This question already has answers here:
Use variable outside the success function from an ajax/jquery call
(5 answers)
Closed 7 years ago.
I have created an jsonp request that retrieves data. The only problem is I cant seem to get the data in a array outside my loop:(
var lookbook_data = new Array();
$.ajax({
url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp",
success: function(data) {
for(var i = 0; i<4; i++) {
lookbook_data[i] = data.posts[i].custom_fields.image1[0];
}
}
});
console.log(lookbook_data);
So when I console.log they array inside the look it output the data the way it should. However outside the function it does not. But I did decleare the variable outside so I really dont get why:(
Btw Sorry for messy codebock cant seem to get it right with 4 spaces:(
That ajax call is asynchronous, so you immediatly reach the last line of your code before it can finish.
You could make is synchronous (not recommended) with
async = 'false'
within the ajax call
or do something like this
$.ajax({
url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp",
success: function(data) {
for(var i = 0; i<4; i++) {
lookbook_data[i] = data.posts[i].custom_fields.image1[0];
}
continueHere()
}
});
function continueHere() {
// rest of the code that handles your ajax call
}
var lookbook_data = new Array(),
XHR = $.ajax({
url: "http://lookbook.king-quinna.nl/api/get_recent_posts/?callback=1&custom_fields=image1",
dataType: "jsonp"
});
//anywhere else in your script you can call :
XHR.done(function() {
for(var i = 0; i<4; i++) {
lookbook_data[i] = data.posts[i].custom_fields.image1[0];
}
console.log(lookbook_data);
});
use this inside your for loop console.log(lookbook_data[i]); inside the success function
use console.log(lookbook_data); inside the success function

jquery trouble with getJSON call

Got some basic problem again.
I need to modify a function that previously returned a in code written object.
Im now trying to get the object from json through $.getJSON
function getEventData() {
var result = '';
$.getJSON("ajax.php?cmd=getbydate&fromdate=&todate=", function(data) {
result = data;
});
return result;
}
Problem is that result isn't set in the callback function for obvious reasons.
Do you guys have a solution for this?
Edit:
Ok i got an answer that was removed.
I just had to change it abit..
This is the answer that works:
function getEventData() {
var result = '';
url = "ajax.php?cmd=getbydate&fromdate=&todate=";
$.ajax({
url: url,
async: false,
dataType: 'json',
success: function(data) {
result = data;
}
});
return result;
}
You should program your application in an asynchronous way, which means, that you should use callback functions for you application flow, too, or continue in the getJson callback function. You can also make the request synchronously which should then be able to return the value (or at least assign it and block the function till the callback is completed), but this is not recommended at all:
function getEventData() {
var result = '';
result = $.ajax({
url: "ajax.php?cmd=getbydate&fromdate=&todate=",
async: false,
dataType: "json",
data: data,
success: function(data) {
return data;
}
});
return result;
}
Are you sure that the server returns valid json? It will be better to validate it using a tool like jsonlint. Also make sure that application/json is used as content type for the response.

Categories

Resources