I need to get a variable from inside the GET request and use it inside the function. It's not working. Here is my code:
function chooseChosenOne() {
$.get("generate.php", function(data) {
var chosenOne = targetLocation[data.randomNumber];
}, "json");
alert(chosenOne);
}
How can I fix this? How can I use the variable "chosenOne" outside of that function in the GET request?
You have to use the jQuery plugin getURLParam
value = $.getURLParam("paramName");
'chosenOne' only exists inside your callback function, and your code will hit the alert() before the callback has even run...
function chooseChosenOne() {
$.get("generate.php", function(data) {
doSomethingWithChosenOne(targetLocation[data.randomNumber]);
}, "json");
}
function doSomethingWithChosenOne(v){
alert(v);
}
At the time you call alert(chosenOne);, the Ajax callback is not executed yet. Ajax is asynchronous. The function chooseChosenOne will not wait until the Ajax called finished, it will return immediately.
You can only work the return value in the callback:
function chooseChosenOne() {
$.get("generate.php", function(data) {
var chosenOne = targetLocation[data.randomNumber];
alert(chosenOne);
}, "json");
}
So what you have to do is to make your function accept a callback which gets called as soon as the value is available:
function chooseChosenOne(callback) {
$.get("generate.php", function(data) {
callback(targetLocation[data.randomNumber]);
}, "json");
}
chooseChosenOne(function(theOne) {
// now do stuff with theOne here
});
See also:
jQuery: Return data after ajax call success
What I have to say about how to return data from an Ajax call.
Related
I'm not so much pro in javascript variable scopes and got stuck with one question.
If i have function which dose ajax call and then call my callback
function doAjaxFunc(param, callback)
{
$.ajax({
type: 'GET',
url: '/some/url/'+param,
success: function(data){
callback(data);
},
dataType:'json'
});
}
function someCallback1(ajaxResp){
// DO someting 1
}
function someCallback2(ajaxResp){
// DO someting 2
}
// exec
doAjaxFunc(1, someCallback1);
doAjaxFunc(2, someCallback2);
As ajax is async and it can be that sever will process param=1 case longer then param=2 is it possible that someCallback1 and someCallback2 will process not their responses. I mean callback argument value will be somehow mixed ?
If possible give some explanation details in answer
I mean callback argument value will be somehow mixed?
No. The callbacks will be called in completely separate invocations within scope of the originating AJAX success handler. There will be no cross-contamination of the data from either request.
Also, just as an aside, you can change this:
success: function(data){
callback(data);
},
To just this:
success: callback,
Check this example , i hope it is some helpful to understand scope in JavaScript
var isFirstCall=false;
function doAjax(param)
{
if(!isFirstCall)
{
//for example after do ajax
var millisecondsToWait = 1000;
setTimeout(function() {
console.log(param);
}, millisecondsToWait);
}
isFirstCall=true;
console.log(param);
}
doAjax('first call');
doAjax('second call');
Within my code I have a function that depends on the result of an async call to an API endpoint. In order for the function to execute properly it needs to wait for the result of the call. So I've read up on async calls and from another Stack Overflow question I read that you should make use of callback functions to enable correct execution.
The code below is my attempt to make use of callbacks to allow my function to run successfully, but it doesn't work and at the moment I think the calls are messed up.
I'm not sure how I need to structure this code, but I first need the getInstructionType() call to return its value, then the GetValidationResult() call to return its value, and then the setValidationRowColor() function needs to execute.
getInstructionType(applicationNumber, function(result) {
getInstructionValidationResult(applicationNumber, function(type) {
setValidationRowColor(result);
});
});
function getInstructionValidationResult(applicationNumber) {
var url = //-snip-;
$.get(url, function(data) {
return data;
});
}
function getInstructionType(applicationNumber) {
var url = //-snip-;
$.get(url, function(data) {
return data;
});
}
You could add arguments to the functions which you can use as callbacks. Then you can call those when the AJAX request completes, something like this:
getInstructionType(applicationNumber, function(result) {
getInstructionValidationResult(applicationNumber, function(type) {
setValidationRowColor(result);
});
});
function getInstructionValidationResult(applicationNumber, callback) {
$.get(/*-snip-*/, function(data) {
// some custom logic to work with the response here...
callback && callback(data);
});
}
function getInstructionType(applicationNumber, callback) {
$.get(/*-snip-*/, function(data) {
// some custom logic to work with the response here...
callback && callback(data);
});
}
The alternative to callbacks (which are completely valid) are promises - which is really just another form or callbacks. Assuming you are using jQuery's $.get, you are already making use of Promises:
getInstructionType(applicationNumber, function(result) {
return getInstructionValidationResult(applicationNumber)
.then(function() {
setValidationRowColor(result)
})
});
function getInstructionValidationResult(applicationNumber) {
var url = //-snip-;
return $.get(url)
}
function getInstructionType(applicationNumber) {
var url = //-snip-;
return $.get(url)
}
Note that all I did was return the $.get and added a .then which accepts your callback inside getInstructionType
I'm no professional in JavaScript and I've seen searching a long time for this on the internet.
I'm having a problem getting a variable from another function. My code is looking like this:
var variabeltje;
$.post('js/ajax/handle_time.php', {'time': $(this).find('input').val()},
function(data) {
alert(data);
variabeltje=data;
}
);
alert(window.variabeltje);
The variable variabeltje must get the information from data. When I put the alert below variabeltje=data it's working, but I need the data variable after the function.
Edit:
I have changed it to what people said, I now have this:
var XHR = $.post('js/ajax/handle_time.php', {time: $(this).find('input').val()});
XHR.done(function(data) {
console.log(data);
getData(data);
});
function getData(data) {
if(data == 'true') {
alert(data);
$(this).unbind('keypress');
$(this).html($(this).find('input').val());
}
}
But now the $(this) isn't passing into the function. How can I solve this?
As it's asynchronous the data will only be available after the ajax call is completed, so you'll have to modify your code to work with that and wait until after the ajax is done to do your stuff:
var XHR = $.post('js/ajax/handle_time.php', {time: $(this).find('input').val()});
XHR.done(function(data) {
console.log(data);
});
or in other function:
function XHR(time){
return $.post('js/ajax/handle_time.php', {time: time});
}
function doStuff(element) {
XHR($(element).find('input').val()).done(function(data) {
console.log(data);
});
}
EDIT:
based on your edit, it looks like it's a scoping issue:
var self = this,
XHR = $.post('js/ajax/handle_time.php', {time: $(self).find('input').val()});
XHR.done(function(data) {
console.log(data);
getData(data);
});
function getData(data) {
if(data == 'true') { //normally you'd try to pass true as a boolean, not string
alert(data);
$(self).unbind('keypress').html($(self).find('input').val());
}
}
This is because the $.post method runs asynchronously.
Please take a look at this question on SO.
Edit: You can change your code and put the part after post method inside the body of the anonymous function triggered on success. As follows:
$.post('js/ajax/handle_time.php', {'time': $(this).find('input').val()},
function(data) {
alert(data);
variabeltje=data;
alert(window.variabeltje); // or whatever function you need to call, call it here...
}
);
The problem is that post method is executed asynchronously. This is, a post is sent to the server but execution flow continues so your alert is trying to access a value that wasn't set since post haven't returned yet.
You could use ajax method if you need a synchronic execution.
What I'm trying to do is the following in JS:
function getSuccessForTest(testName,version,fromRev,toRev,res) {
var params = {
"methodToRun":"getSuccessForTest",
"version":version,
"startRev":fromRev,
"endRev":toRev,
"testName":testName
};
$.post("Stats.php", params,function(data){
return parseInt(data.toString(),10);
}, "json");
}
getSuccessForTest(data[i],version,fromRev,toRev,res);
What am I doing wrong ? whenever I make the call to getSuccessForTest, I get the POST result in Stats.php but the value isn't returned to the calling function.
Thanks in advance !
It's not working because the return is in the callback function given to $.post as a parameter. Since you're dealing with an ajax request which is asynchronous you need to use a callback for getSuccessForTest as well. Try this:
function getSuccessForTest(testName,version,fromRev,toRev,res, callback) {
var params = {
"methodToRun":"getSuccessForTest",
"version":version,
"startRev":fromRev,
"endRev":toRev,
"testName":testName
};
$.post("Stats.php", params,function(data){
callback(parseInt(data.toString(),10));
//return parseInt(data.toString(),10);
}, "json");
}
getSuccessForTest(data[i],version,fromRev,toRev,res, function (data) {
alert(data); // This would be the value you wanted to return
});
That's beacuse value is returned to the anonymous function (function(data){...). Use callbacks. Try this:
function getSuccessForTest(testName,version,fromRev,toRev,res, callback) {
var params = {
"methodToRun":"getSuccessForTest",
"version":version,
"startRev":fromRev,
"endRev":toRev,
"testName":testName
};
$.post("Stats.php", params,function(data){
callback(parseInt(data.toString(),10));
}, "json");
}
getSuccessForTest(data[i],version,fromRev,toRev,res, function(res) {
alert(res)
} );
use echo when you are return from stats.php. if this is not solving your issue then I would like to know what is the return method you are using for your ajax call handling script.
return parseInt(data.toString(),10);
You cant return like that.
either assign in some global variable or do process there with data
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 4 years ago.
The function I called inside jquery returns undefined. I checked the function and it returns correct data when I firebugged it.
function addToPlaylist(component_type,add_to_pl_value,pl_list_no)
{
add_to_pl_value_split = add_to_pl_value.split(":");
$.ajax({
type: "POST",
url: "ds/index.php/playlist/check_folder",
data: "component_type="+component_type+"&value="+add_to_pl_value_split[1],
success: function(msg)
{
if(msg == 'not_folder')
{
if(component_type == 'video')
{
rendered_item = render_list_item_video(add_to_pl_value_split[0],add_to_pl_value_split[1],pl_list_no)
}
else if(component_type == 'image')
{
rendered_item = render_list_item_image(add_to_pl_value_split[0],add_to_pl_value_split[1],pl_list_no)
}
}
else
{
//List files from folder
folder_name = add_to_pl_value_split[1].replace(' ','-');
var x = msg; // json
eval('var file='+x);
var rendered_item;
for ( var i in file )
{
//console.log(file[i]);
if(component_type == 'video')
{
rendered_item = render_list_item_video(folder_name+'-'+i,file[i],pl_list_no) + rendered_item;
}
if(component_type == 'image')
{
rendered_item = render_list_item_image(folder_name+'-'+i,file[i],pl_list_no) + rendered_item;
}
}
}
$("#files").html(filebrowser_list); //Reload Playlist
console.log(rendered_item);
return rendered_item;
},
error: function()
{
alert("An error occured while updating. Try again in a while");
}
})
}
$('document').ready(function()
{
addToPlaylist($('#component_type').val(),ui_item,0); //This one returns undefined
});
The function addToPlaylist doesn't return anything. It makes an asynchronous request, which eventually executes a callback function, which returns something. The original addToPlaylist function is long done and returned by the time this happens though, and the callback function returns to nobody.
I.e. the success: function(msg) { } code executes in a different context and at a later time than the surrounding addToPlaylist function.
Try this to see it in action:
function addToPlaylist() {
$.ajax({
...
success : function () {
alert('second'); // comes after 'first'
return null; // returns to nobody in particular
}
});
alert('first'); // comes before 'second'
return 'something'; // can only return here to caller
}
You're making your request via AJAX, which by definition is asynchronous. That means you're returning from the function before the AJAX request completes. In fact, your return statement is meaningless as it returns from the callback function, not your addToPlaylist function.
You have a couple of choices. The first one is better.
First, you can work with the asynchronous nature of the AJAX request and pass a callback into your addToPlaylist method (much like you're passing in the anonymous callback to the ajax function) and have the AJAX callback, call that function instead of doing the return. That way your request completes asynchronously and doesn't lock up your browser while it's going on.
function addToPlaylist(component_type, add_to_pl_value, pl_list_no, cb )
{
...yada yada yada...
$.ajax({
...
success: function(data) {
...
if (cb) {
cb.apply(this, rendered_item );
}
}
});
}
Second, you can add the option aSync: false to the ajax call. This will force the AJAX call to run synchronously (essentially it just loops until the call returns then calls your callback). If you do that, you need to capture a local variable in your addToPlaylist function inside the callback and assign the value(s) to it from the callback. At the end of the addToPlaylist function, return this variable as the result.
function addToPlaylist(component_type, add_to_pl_value, pl_list_no )
{
...yada yada yada...
var result = null;
$.ajax({
aSync: false,
...
success: function(data) {
...
result = rendered_item;
}
});
return rendered_item;
}
I agree with deceze. What you need to do is perform the necessary action(s) for rendered_item in the success function rather than relying on getting something back from addToPlayList().