This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference
(7 answers)
Closed 5 years ago.
I have an Jquery Ajax call like so:
$('body').on('click', '#btnPopulate', function() {
alert(getTree());
});
function getTree() {
var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewModel";
$.ajax({
type: "POST",
cache: false,
url: url,
success: function (result) {
if (result.success === true) {
var data = result.data;
return data;
} else {
return null;
}
},
error: function (responseText, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
}
When I click the button, the alert box just says 'undefined', as if there is no data being returned But in the ajax call, the "var data = result.data" has loads of data in it when I breakpoint it. So why is this not being returned to the alert box? The data being returned is an array of objects, with each object further containing an array of objects. But the data is definitely being returned from the controller to "var data".
There first call to alert, tires to alert the value returned by getTree. Since getTree has no defined returned value, it returns undefined to the first alert call.
This is why you see 'undefined' in the alert box initially.
Try calling alert from within your Ajax call success callback instead of on the click handler:
$('body').on('click', '#btnPopulate', function() {
getTree();
});
function getTree() {
var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewModel";
$.ajax({
type: "POST",
cache: false,
url: url,
success: function (result) {
if (result.success === true) {
var data = result.data;
alert(data);
} else {
return null;
}
},
error: function (responseText, textStatus, errorThrown) {
alert('Error - ' + errorThrown);
}
});
}
It sounds like you're having trouble understanding AJAX in general, when you call alert(getTree()) it's returning what getTree() returns... not the AJAX call.
Your return data; is actually a return for the success handler in your AJAX call itself. So if you were to place the alert(data); there, when the AJAX call is finished then the alert will show with the correct data.
Related
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
i'm having a problem here, in the success method of AJAX i have a if to see if the Streamer is live or not, if is live it returns "online.png" and if is not it returns "offline.png", my problem is that the returns give "undefined" but if i uncomment the console.log in console i can see "offline.png" or "online.png" on console (but the returns still giving undefined).
Someone already pass this problem?? Thanks
function checkOnline(nombre){
try {
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/streams/' + nombre,
headers: {
'Client-ID': '
},
success: function(data) {
// console.log(data["stream"]);
if (data["stream"] == null) {
return "offline.png";
break;
// console.log("offline.png");
}else {
return "online.png";
break;
//console.log("online.png");
}
},
error: function(data){
alert("Stream not found!");
}
});
} catch (e) {
alert("Conection error, try later... Monkeys are fixing it");
}
}
There is no need for return or break in this context. Nothing can be returned in an asynchronous request and you are not in an iteration, so there is nothing to break out of.
The function checkOnline is always going to return undefined, because it is an asynchronous call, it can not break out and return the result of the request.
If you want to do something with the data, you can do it directly within the callback method.
You can make something like that:
function checkOnline(nombre, callback){
try {
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/kraken/streams/' + nombre,
headers: {
'Client-ID': ''
},
success: function(data) {
// console.log(data["stream"]);
if (data["stream"] == null) {
callback("offline.png");
break;
// console.log("offline.png");
}else {
callback("online.png");
break;
//console.log("online.png");
}
},
error: function(data){
alert("Stream not found!");
}
});
} catch (e) {
alert("Conection error, try later... Monkeys are fixing it");
}
return result;
}
Actually now you return value from success function, not from checkOnline function. You can provide a callback for process result of async call of ajax function.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have an AJAX function that is called from a javascript function.
Something like this:
(CODE1)
//javascript function calling AJAX.
var function check(){
var status = chkHoliday(date,'Date Chosen');
alert('called');
return status;
}
//AJAX function
function chkHoliday(date,str){
var flag = true;
$.ajax({
type: "GET",
url: someurl,
async: false, //if commented, the alert() from the caller function is called before completion of this function.
dataType: "json",
success: {
flag = false;
}
});
return flag;
}
It works well. The only problem is that since async it is set to false, the web page sort of hangs for a while but then continues to proceed further.
To avoid this I read something about callback functions so i tried this out:
(CODE 2)
//javascript function calling AJAX.
var function check(){
var status;
chkHoliday(date,'Date Chosen',function(retVal){
status = retVal;
});
if(status != null){
alert(status);
return status;
}
else{
alert(true);
return true;
}
}
//AJAX function
function chkHoliday(date,str,callback){
var flag = true;
$.ajax({
type: "GET",
url: someurl,
//async: false, //if commented, the alert() from the caller function is called before completion of this function.
dataType: "json",
success: {
flag = false;
callback(flag);
}
});
//return flag;
}
this worked but the alert was called again before the AJAX function could complete stating "undefined". I don't know what I'm doing wrong.
I want, that the AJAX function should wait till it executes completely and then return to the calling function and run the next statements in the caller function with halting the process (i.e with the use of async). Also i want that the value returned by AJAX should be easily accessible to my caller function.
Put the alert inside the callback function:
chkHoliday(date,'Date Chosen',function(retVal){
status = retVal;
if(status != null){
alert(status);
}
else{
alert(true);
}
});
But note you cannot use the return statement anymore as what you have expected because it is asynchronous.
Since AJAX works asynchronous, it is a problem to place it in a function and return a value. To solve this use deferred with a promise. This will promise the ajax result to the caller. It is slightly different. Here is an example. Works like a charm for me.
Of course you will need to adapt it to your needs, but all you really have to do is create your data object.
var data = {}
function chkHoliday(data) {
var deferred = $.ajax({
method: "post",
url: ajaxURL,
dataType: "json",
data: data
});
return deferred.promise();
}
chkHoliday(data).done(function (response) {
console.log(response);
}
return from your php file with a
echo json_encode(array("success"=>"hello"));
Put the alert inside the callback
functions. or else alerts will work simultaneously inspite of success or error.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I have a function which returns data:
function getData(){
return {result:[{},{},{}...]};
}
This function worked perfectly. Now I want to generate the data dynamically. I use the following method to generate the data, however it does not work out then:
function getData(){
$.ajax({
//...
async: false,
success: function(data, textStatus, jqXHR){
return {result:[{},{},{}...]};
}
});
}
Can some provide me some hints for this or point me to the right direction to do it? thank you.
You have to return the data from your outer function:
function getData () {
var data;
$.ajax({
//...
async: false,
success: function(data, textStatus, jqXHR){
data = {result:[{},{},{}...]};
}
});
return data;
}
However, you shouldn't be using synchronous AJAX requests. That'll freeze all execution until the request has completed.
Instead, return the promise returned by the $.ajax call, and use that in your calling code:
function getData () {
return $.get('/path/to/recourse');
}
getData().then(function (results) {
// use results here...
});
Never DO this(using async : false), it will block the browser thread till the response comes from the server which will freeze the user experience till the response comes back.
you are only returning from the inner function, not from getData
function getData(){
var result;
$.ajax({
//...
async: false,
success: function(data, textStatus, jqXHR){
result = {result:[{},{},{}...]};
}
});
return result
}
Then how to do it correctly... There are literally thousands of threads regarding this in SO itself... A famous one is How to return the response from an AJAX call
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 1 year ago.
function ajax_test(str1){
var url = "None"
jq.ajax({
type:'post',
cache: false,
url: 'http://....' + str1,
success: function(data, status, xhr){
url=data;
},
error: function (xhr, status, e) {
},
async: true,
dataType: 'json'
});
return url
}
How can I set the global variable url to be the returned success ajax data?
In Javascript, it is impossible for a function to return an asynchronous result. The function will usually return before the AJAX request is even made.
You can always force your request to be syncronous with async: false, but that's usually not a good idea because it will cause the browser to lock up while it waits for the results.
The standard way to get around this is by using a callback function.
function ajax_test(str1, callback){
jq.ajax({
//... your options
success: function(data, status, xhr){
callback(data);
}
});
}
and then you can call it like this:
ajax_test("str", function(url) {
//do something with url
});
Here is my example code for retrieving data from php, and then pass the value to a javascript global variable within ajax success function. It works for me!
var retVal = null;
function ajaxCallBack(retString){
retVal = retString;
}
function readString(filename){
$.ajax({
type: "POST",
url: "readString.php",
data: { 'fn': filename },
success: function(response){
ajaxCallBack(response);
}
});
}
PHP code (readString.php):
<?php
$fn = $_POST['fn'];
$file = fopen("path/".$fn.".record","r");
$string = fread($file,filesize("path/".$fn.".record"));
fclose($file);
echo $string;
?>
However, as $.ajax() sent requests asynchronously, which means it may return before the success callback runs, you should not rely on it runs sequentially and return the value by itself. Therefore, here we assign php response value to global value in callback function.
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().