Return undefined in ajax success method [duplicate] - javascript

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.

Related

Jquery Ajax function returning no data [duplicate]

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.

how to stop function processing until the ajax call complete? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
see I have code like this
function validate(){
if (document.getElementById('<%=txtSeqNo.ClientId %>').value.trim() == "") {
alert('Please enter Seuenceqnumer.');
return false;
}
var result = checkduplicateseq();
if (result) {
return true;
}
else {
return false;
}
}
and definitation for checkduplicateseq is
function checkduplicateseq() {
var result = true;
if ($('[id*=ctl00_CPHMainPageLambda_chkoperationlist] input[type="checkbox"]:checked').length > 0) {
var seqNo = $("#ctl00_CPHMainPageLambda_txtSeqNo").val();
var chkvalue = $('[id*=ctl00_CPHMainPageLambda_chkoperationlist] input[type="checkbox"]:checked').parent().parent().find("span").attr("datavalue");
var hfmode = $("#ctl00_CPHMainPageLambda_hd_SequenceNo").val();
var oldoperationid = $("#ctl00_CPHMainPageLambda_hd_operationo").val();
if (seqNo == "") {
}
else {
$.ajax({
type: "POST",
url: "frmFAQMst.aspx/GetSequenceNoforOperation",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
data: '{"OptionaId":"' + chkvalue + '","oldoperationid":"' + oldoperationid + '","seqNo":"' + seqNo + '","hfmode":"' + hfmode + '"}',
error: function (ex) {
console.log(ex);
},
success: function (response) {
if (response.d == "1") {
alert("Sequence Number already exist!");
$("#ctl00_CPHMainPageLambda_txtSeqNo").attr('value', '')
$("#ctl00_CPHMainPageLambda_txtSeqNo").focus();
result = false;
}
else {
result = true;
}
}
});
}
}
return result;
}
now if i call checkduplicateseq from validation function at the last
and store return value of checkduplicateseq fucntion in variable like
var result = checkduplicateseq();
in browser i can see the value of result = undefine
so it goes to else part of that function
if (result) {
return true;
}
else {
return false;
}
and in it return false so further execution not work
i want to go further after finishing checkduplicateseq (ajax call)
use a callback in your success function. you can pass the callback into your checkduplicateseq function, or just leave it in the global namespace and call it directly from your success function, or you can just inline that function altogether (defined inside success function)
checkduplicateseq(someCallback);
function someCallback () {
return !!result
}
and your success function
success: function(response) {
if (response.d == "1") {
alert("Sequence Number already exist!");
$("#ctl00_CPHMainPageLambda_txtSeqNo").attr('value', '')
$("#ctl00_CPHMainPageLambda_txtSeqNo").focus();
result = false;
} else {
result = true;
}
someCallback();
}
The best way, if you're chaining lots of callbacks, is to research Promises, which allow you to write in a sequential fashion, rather than passing things to be invoked later
You can add the option of async: false to the $.ajax() function which will cause the process to wait. This is generally considered bad practice though.
e.g.
$.ajax({
async: false,
type: "POST",
url: "frmFAQMst.aspx/GetSequenceNoforOperation",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
.... etc
I was checking on this issue i just found a similar question in stack overflow. Please check this link
How to do sequential asynchronous ajax requests with given number of streams

JQUERY AJAX WITH CALLBACK [duplicate]

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.

Why isn't this function returning anything? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
I'm trying to debug some tests - I have the following code:
test('Can get the test Side',
function () {
stop();
debugger;
var result = getTestSide();
debugger;
changeTestSide(result);
}
);
// Step 1: Get test side
function getTestSide() {
$.ajax({
type: 'GET',
url: urlWithId,
success: function (result) {
return "test success";
debugger;
ok(true, "GET succeeded.");
if (!result.SideId === testSideId) {
throw "GET result does not equal testSideId";
} else {
ok(true, "Returned key matches testSide Id.");
return result;
}
},
error: function (result) {
return "test failure";
debugger;
throw "Error";
}
});
};
No matter what, "result" in the top method is always undefined. Why is this? Whether getTestSide succeeds or fails, I'm returning a string.
Using return inside a nested function returns only from that function. Your code must be structured quite differently to get the effect you want. One way to do this is to pass a callback function into getTestSide that will handle the response, like this:
test('Can get the test Side',
function () {
stop();
debugger;
getTestSide(function (result) {
changeTestSide(result);
});
}
);
// Step 1: Get test side
function getTestSide(cb) {
$.ajax({
type: 'GET',
url: urlWithId,
success: function (result) {
// removed this because it stops the rest from running
// return "test success";
ok(true, "GET succeeded.");
if (!result.SideId === testSideId) {
throw "GET result does not equal testSideId";
} else {
ok(true, "Returned key matches testSide Id.");
// Call the callback instead of returning.
cb(result);
}
},
error: function (result) {
// removed this because it stops the rest from running
// return "test failure";
debugger;
throw "Error";
}
});
};
You've also used throw inside your success and error callbacks; these will also not do what I think you expect them to do, since by the time these functions are running your test function has already returned and so there is no way for you to catch those exceptions. Your code didn't show any attempt to catch the exceptions anyway so I didn't attempt to address this, but you can address it by following a similar pattern to the $.ajax function and providing both success and error callbacks that the caller can then implement.
You should invoke changeTestSide method from the success and error handlers
You need to fix a few things here:
success: function (result) {
return "test success";
debugger;
ok(true, "GET succeeded.");
if (!result.SideId === testSideId) {
throw "GET result does not equal testSideId";
} else {
ok(true, "Returned key matches testSide Id.");
return result;
}
},
First off, you need to call changeTestSide(result); from the success function in your AJAX. This is because AJAX is by default an asynchronous call, meaning that your javascript doesn't wait for getTestSide() to finish executing before continuing in your test function. Second, in your success function, the first thing that you're doing is return "test success"; which will make the function return, and none of the code below that is ever actually running. Here is a better example of what your code needs to be like:
success: function (result) {
debugger;
ok(true, "GET succeeded.");
if (!result.SideId === testSideId) {
throw "GET result does not equal testSideId";
} else {
ok(true, "Returned key matches testSide Id.");
changeTestSide(result);
}
},

Function inside jquery 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.
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().

Categories