Overriding variable value inside the $.get() [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I am facing a quite Strange problem, I dont seem to be able to override variable jSonData from inside the success function of $.get()
$.fn.name = function(data, options) {
var jSonData = data;
var settings = $.extend({
....
}, options);
if(typeof data !== 'object') {
if(settings.debug) console.log('Getting configuration settings from: ', data);
$.get(data, function(d) {
jSonData = d; //I attempt to override the value here
}, 'json');
}
console.log(jSonData); // Gives the same value as it was before
};
Note: The success event of the $.get() is triggered

By the time you logged the value, the $.get() has not overridden jSonData yet since the AJAX request has not returned by that time. Do the console.log inside the function instead.
$.get(data, function(d) {
jSonData = d; //I attempt to override the value here - You just did!
console.log(jSonData);
}, 'json');

I was having that problem because AJAX calls are asynchronous and thus the call would not have been completed when console.log() was executed.
Solution I used to fix my issue was by using deferring methods.
$.fn.name = function(data, options) {
var jSonData = data;
var settings = $.extend({
....
}, options);
var getData = function() {
if(typeof data !== 'object') {
return $.get(data, 'json');
}
else { return jSonData; }
};
getData().done(function(result) {
jSonData = result;
console.log(jSonData); // Gives the same value as it was before
}).fail(function() {
//
});
};

Related

Always returning function returns undefined [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
There is this small function that should logically returns always, but I am getting undefined :-
function hasAccess() {
var dataObj = {
"id" : $scope.groupId
};
$http.post('http://vlinux:9099/GetItems', dataObj).then(
function(response) {
var result = response.data.result;
if(result.includes($scope.screenId)) {
return "ok";
} else {
return "nok";
}
});
}
I started getting downvotes, so wuickly adding, I debugged it and saw http call is bringing expected response and flow is jumping to the right if/else block. Problem is when I am calling this function in a variable its storing undefined.
The call is simple too :-
var allow = hasAccess();
$http.post is not synchronous, but asynchronous.
Thus, all that you have after $http.post is a promise, not the boolean you are expecting.
The documentation show wells how to provide a "callback" to your function, in case of success as well as failure :
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
// for example : manageWHenOk
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
// for example : manageWHenKO
});
Your function return a result only if the request is fine. If there is an error your function do nothing! I suggest you to add a catch function.
function hasAccess() {
var dataObj = {
"id" : $scope.groupId
};
$http.post('http://vlinux:9099/GetItems', dataObj).then(
function(response) {
var result = response.data.result;
if(result.includes($scope.screenId)) {
return "ok";
} else {
return "nok";
}
}).catch(function (error) {
// do something
});
}
If you still have undefined it means that your template is loaded before to obtain the response. In order to resolve that you can do the request in the resolve method of the $stateProvider.

jQuery: wait until $.get() return the value [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
This is my code example
var formValidate = function() {
var url = 'someurl';
var checkC = function (url, callback) {
$.get(url, function( data ) {
if(data.indexOf('OK') == 0) return callback('OK');
})
};
checkC(url, function(data) {
if(data == 'OK') return false;
});
return true;
}
My code is pretty similar to Adam Rackis's in this question Wait for jQuery $.get function to finish before running code. But unfortunately function dont wait for the data return. formValidate() just return true. I want use this function to check some conditions before sending data to server from form
form.on('submit', function(){
if(formValidate()) form_send();
})
Can someone tell me where was I wrong in code above?
The first problem is that formValidate() return true synchronously regardless to the ajax request.
var formValidate = function() {
.
.
.
return true;
}
If you want the to wait for return your values from the callback functions. Here you should call form_send() from the success callback to make it wait for the asynch call. And you can actually make it much simpler without checkC() also. Change the code a bit and use done and fail promises:
var formValidate = function () {
var url = 'someurl';
$.get(url)
.done(function (data) {
if (data.indexOf('OK') == -1) {
console.log("error");
return;
}
form_send();
})
.fail(function () {
console.log("error");
return;
})
}
You can't do this since $.get is called asynchronously.
var formValidate = function() {
var url = 'someurl';
var checkC = function (url, callback) {
$.get(url, function( data ) {
if(data.indexOf('OK') == 0) return callback('OK');
});
};
checkC(url, function(data) {
// this return to this enclosing callback function but not formValidate
if(data == 'OK') return false;
});
//this is the only return statement for formValidate function
return true;
}
A workaround i suggested is just call your form_send() in the callback, for example,
form.on('submit', formValidate);
And for your formValidate,
var formValidate = function () {
var url = "someurl";
$.get(url, function( data ) {
if(data.indexOf('OK') == 0) {
form_send();
}
});
};

Javascript - Pass callback value to calling variable [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
I have a function and a variable....
var imageURLs = retrieveRemoteImages(vinUrls)
if imageURLs !== undefined) {
// do something
}
function retrieveRemoteImages(urls) {
var imageURls = [];
processSpinnerActivity(START_IMAGES_IMPORT);
importImagesforSlideShow(REMOTE_IMAGES_URL, urls, function (images) {
if (images !== undefined) {
imageURls = images;
return imageURls;
}
})
return imageURls;
}
This does as intended ....
function importImagesforSlideShow(imagePath, urls, call_back) {
var functionName = 'importImagesforSlideShow'
$.ajax({
type: "POST",
url: LOCAL_PROCESSING_MODULE,
data: {data: [imagePath, urls, IMAGE_EXTENSION_QUALIFIER], functionid: functionName},
dataType:"json",
success: function (res) {
processSpinnerActivity(IMPORT_IMAGES_SUCCESS);
call_back(res);
},
error: function (err) {
processSpinnerActivity(IMPORT_IMAGES_ERROR);
console.log(err.message);
}
});
}
The callback works fine, but I am not able to pass the eventual value to imageURLs and I need to, as the next step cannot occur until it has a value.
Any ideas?
Thanks!
This is not a duplicate question, I have no issues with my AJAX returning the async value*
It's not possible like that, you are executing a piece of async code. So your code keeps running while their isn't any data yet. You have to process your data in a callback, for example like this:
function retrieveRemoteImages(urls, callback) {
processSpinnerActivity(START_IMAGES_IMPORT);
importImagesforSlideShow(REMOTE_IMAGES_URL, urls, callback);
}
retrieveRemoteImages(vinUrls, function(imageURLS) {
//do your stuff
});

Sequential execution of Ajax requests [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
The script should take the user's session via ajax and transfer it to other ajax requests that take the data for the charts. The first request succeeds, but others have not, becouse sessionId for them is undefined. Tried to wrap them in a function, but unfortunately nothing happened. What can be done?
var sessionId,
requestInWorkCount,
requestInWorkPower;
function getSession(){
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonLoginUser?UserID=User1&UserPassword=123", {},
function(data) {
$.each(data, function (key, val) {
sessionId = val.toString();
return sessionId;
})
});
};
function getData(session){
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonGetIndicator?SessionID="+session+"&IndNum=1", {},
function(data) {
$.each(data, function (key, val) {
requestInWorkCount = val;
return requestInWorkCount;
})
});
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonGetIndicator?SessionID="+session+"&IndNum=2", {},
function(data) {
$.each(data, function (key, val) {
requestInWorkCount = val;
return requestInWorkPower;
})
});
};
$(document).ready(function(){
getSession();
getData(sessionId);
setInterval('show()',1000);
});
ajax call is async so your second ajax call is executed before the first completes thats the reason sessionId is undefined.
Use the success function of first ajax call and call GetData() in it.
Also you don't need to return sessionId
function getSession(){
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonLoginUser?UserID=User1&UserPassword=123", {},
function(data) {
$.each(data, function (key, val) {
sessionId = val.toString();
getData(sessionId);
})
});
};
you call like this now:
$(document).ready(function(){
getSession();
});
The AJAX request are asynchronous and you cannot execute them sequentially.
An easy solution here would be to call getData() inside AJAX success block:
function getSession() {
$.getJSON("http://192.168.1.142/DashboardService.svc/web/jsonLoginUser?UserID=User1&UserPassword=123", {}, function(data) {
$.each(data, function (key, val) {
sessionId = val.toString();
getData(sessionId);
return sessionId;
});
});
};
You have to take the RESPONSE of the ajax request. You do not return it, I believe. But in your code you should perhaps do
sessionId = getSession();
getData(sessionId);
You forgot to dereference what it returned.

How to return a value from a function that calls $.getJSON?

function lookupRemote(searchTerm)
{
var defaultReturnValue = 1010;
var returnValue = defaultReturnValue;
$.getJSON(remote, function(data)
{
if (data != null)
{
$.each(data.items, function(i, item)
{
returnValue = item.libraryOfCongressNumber;
});
}
});
return returnValue;
}
Why is the returnValue from this function alway equal to the default value set at the beginning of the function and never to the value retrieved from the JSON lookup?
If you don't want to use asynchronous function, better use the following:
function getValue(){
var value= $.ajax({
url: 'http://www.abc.com',
async: false
}).responseText;
return value;
}
This function waits until the value is returned from the server.
This happens because that callback function (function(data) {...}) runs later when the response comes back...because it's an asynchronous function. Instead use the value once you have it set, like this:
function lookupRemote(searchTerm)
{
var defaultReturnValue = 1010;
var returnValue = defaultReturnValue;
$.getJSON(remote, function(data) {
if (data != null) {
$.each(data.items, function(i, item) {
returnValue = item.libraryOfCongressNumber;
});
}
OtherFunctionThatUsesTheValue(returnValue);
});
}
This is the way all asynchronous behavior should be, kick off whatever needs the value once you have it...which is when the server responds with data.
The function you pass to getJSON is run when the response to the HTTP request arrives which is not immediately.
The return statement executes before the response, so the variable hasn't yet been set.
Have your callback function do what needs doing with the data. Don't try to return it.
const getJson = (path) => {
return new Promise((resolve) => {
$.getJSON(path, function (data) {
setTimeout(() => {
resolve(data);
}, 1);
});
})
}
var result = await getJson('test.json');
console.log(result);

Categories