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
Related
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.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
Is this possible to return value from function which includes an ajax call after the call is executed? For example, in the example here, function1 and function2 both have ajax calls. I'm forced to specify async as false for both the requests as the value that is returned from the functions is setup in the success callback. Is there anyway to overcome this issue so that calls can still be asynchronous but the return values are fine?
$(document).ready(function(){
var abc = function1();
var xyz = function2();
});
function1()
{
var value = "";
$.ajax({
url: url,
async: false,
success: function(data) {
value = "value1";
}})
return value;
}
function2()
{
var value = "";
$.ajax({
url: url,
async: false,
success: function(data) {
value = "value2";
}})
return value;
}
You should process the asynchronously received data within the callback. Doing this synchronously is the bad way.
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 method like this:
var isNameUnique = false;
function ValidateName() {
var url = "/SomeRules/CheckIfNameExists/";
var request = $.ajax({
url: url,
method: "GET",
data: { sName: name},
dataType: "JSON"
});
request.done(function (result) {
if (result.doesNameExists) {
alert("Name Already Exists!");
console.log("Name Already Exists!");
}
else {
isNameUnique = true;
console.log("Name is unique!");
}
});
request.fail(function (jqXHR, textStatus) {
console.log(textStatus);
alert("Request failed.");
});
console.log("Exiting ValidateName()");
}
This is called like so:
function CreateNewUser() {
ValidateName();
console.log(isNameUnique);
if(isNameUnique){
// do stuff
}
}
When I run the application I have these in the console in this order:
Exiting ValidateName()
false
Name is unique!
When it's printing the 3rd console I expect 'isNameUnique' to be set to true.
But that's not happening!!!
What am I doing wrong?
Thanks in advance.
By default every Ajax request is asynchronous, means code next to Ajax call will not wait for the completion of Ajax call.
So what you need to do is, make your Ajax call synchronous, so that next lines of code will execute only after completion of ajax call.
To make your ajax call synchronous add following option in ajax Setting:
async : false
For more info check this documentation and read about async setting.
That happens when you start using async. Your variable isNameUnique gets assign the value but long after you call console.log(isNameUnique);. The best way to tackle that is to make the function ValidateName returning a promise and chain on it.
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 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.