Ajax call does not assign a value in the done promise [duplicate] - javascript

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.

Related

Ajax request return the response after js check [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 7 years ago.
Instead of all sorry for the misleading title, I'll try to explain better. My customer fill a form with personal information, this information are validate from an ajax request that calls a php function. This php function return SUCCESS if the validation it's successfull, instead return the exception. Now when the user click on the next button the javascript code call this function:
if(!FrontendBook.validateCustomerForm())
{
return; //FAIL
} else
{
//do stuff
}
the validateCustomerForm function contain this:
var postUrl = GlobalVariables.baseUrl + 'backend_api/ajax_save_customer';
var postData = { 'customer': JSON.stringify(GlobalVariables.customerData) };
$.post(postUrl, postData, function(response)
{
if(response.status == "SUCCESS")
{
return true;
}
else
{
return false;
}
}, 'json');
Now in the browser console I see correctly the reponse content, and if I put an alert inside response.status == "SUCCESS" the alert is displayed correctly.
Initially I don't understood why in the if(!FrontendBook.validateCustomerForm())
the code enter in the return statement, so in the fail validation. But I ran this test:
Print the result of FrontendBook.validateCustomerForm in console.log()
Check in which statement the condition was
In console.log I get undefined and of course the condition statement fall into the return; //FAIL.
Maybe this is a problem of time? Someone could explain why the function return undefined when I return true or false in the specific contest?
You seem to be misunderstanding promises and the asynchronous nature of this function call. Observe the following way we can accomplish this...
// declaration
function validateCustomerForm() {
var postUrl = GlobalVariables.baseUrl + 'backend_api/ajax_save_customer';
var postData = { 'customer': JSON.stringify(GlobalVariables.customerData) };
return $.post(postUrl, postData); // return promise object
}
// usage
validateCustomerForm().done(function(response) { // resolve promise
if(response.status == "SUCCESS")
/*...*/
});
Check out the jQuery deferred api for more information - since we are returning a promise from your function, then later resolving it.
JSFiddle Link - simplified demo

Ajax response to be a return value of a function [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
In the below piece of code I am not getting the locale in the second alert
if `value==null`
I assign its locale value. but do not get it at the end.
function getLocale(id) {
var locale="";
var value = localStorage.getItem(id);
if (value == null) {
$.ajax({
type: "POST",
url: "myUrl",
data: {"new" : id},
success : function(data) {
data = JSON.parse(data)
var id = data[0]["id"];
delete data[0]["id"];
localStorage.setItem(id, JSON.stringify(data[0]));
locale=JSON.stringify(data[0]);
alert(locale);//corrects value
}// end success
});
}else{
locale= localStorage.getItem(id);
}
alert(locale+"locale");//not have the value
return locale;
}
Its not because of the scope. It is because of the asynchronous behaviour of ajax call. Because the function will not wait for the success event of ajax.
If you want to return, you should use async:false in ajax. But it is not a good method of coding.
Or you should restructure your code with the asynchronous ajax. Instead of returning the value, call a function in the ajax success with desired id.
ajax request is an async process which means it has a different execution timing with your function returning a value.
the trick here is do not assume to have a return value in the scope of the function.
do all the process in the success call back function
success : function(data){
//do everything what you want to do with the response here
}

jquery function always return same [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 8 years ago.
my custom javascript function is working fine. but the problem is it always returning false.
function uniqueChk()
{
var flagV = false;
jQuery.post("<?=base_url()?>index.php/authentication/chksid",
{
sid: jQuery('#sid').val()
},
function( data )
{
if(data == 'ok')
{
jQuery("#sid").removeClass("error");
jQuery("#er_sid").html("");
flagV = true;
}
else
{
jQuery("#sid").addClass("error");
jQuery("#er_sid").html("This Student ID already in the database. Contact Admin if you have not done first time");
}
});
return flagV;
}
If I got value of data "ok" its remove the class error from sid but still return false.
try something like this
function uniqueChk()
{
var flagV = false;
$.ajax({
type: 'POST',
url: "<?=base_url()?>index.php/authentication/chksid",
data: { sid: jQuery('#sid').val() },
success: function(response){
if(data == 'ok'){
jQuery("#sid").removeClass("error");
jQuery("#er_sid").html("");
flagV = true;
} else {
jQuery("#sid").addClass("error");
jQuery("#er_sid").html("This Student ID already in the database. Contact Admin if you have not done first time");
}
},
async:false
});
return flagV;
}
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.
That mean your function doesn't wait for your ajax response to complete.it return it value before your ajax request complete.so make ajax async
REFERENCE
http://api.jquery.com/jquery.ajax/
Because your function returning before ajax gets a chance to come back. This is normal behavior for async functionality. Look into $.deferred when then.

AJAX not working without alert box [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 9 years ago.
I'm trying to use this code:
$('#form1').on('submit', function(){
var txtItemCode = $('#txtItemCode').val();
$.post("userExist.php", {
txtItemCode: txtItemCode,
}, function(data,status){
//alert("Data: " + data + "\nStatus: " + status);
$('#status').html(data);
reply = data;
//alert(reply);
});
alert('');
if (reply=='OK'){
return false;
}
});
I need to check if data=="OK" and return false, but when I remove the alert, it no longer works. Why is this, and how can I make it work?
The reason it works when you introduce the alert is because it stops execution and gives enough time for the asynchronous call to finish.
You're not getting the right value because by the time the post request is finished and the callback is executed your javascript has already finished executing.
You have a few options here:
Declare a global variable and perform a synchronous call, you can either do it with the code ABC posted or call $.ajaxSetup({ async: false }) before your POST call. Assign the return value to the global variable and validate against that.
use jQuery's ajaxStop: $(document).ajaxStop(function() { //check your values here, still need to declare a global });
Write the value to a hidden div/as an attribute anywhere in the DOM and have a timer that periodically checks it until there's a value.
in your code the ajax call is working asynchronous, so no matter you are responded or not your next lines will be executed. In sync call your next lines will not be executed untill you get response.
you could turn into $.ajax from $.post and make async property false. Then you will be able to get and then you can get the value of "reply" after the ajax call is responded.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType,
async:false
});
A new thought came to my mind, please check this.
/**
* form submit
*/
$('#form1').on('submit', function() {
if (checkExistence()) {
return false;
}
});
/**
* check existence in db
* #returns {Boolean}
*/
function checkExistence() {
var txtItemCode = $('#txtItemCode').val();
var result = true;
$.post("http://localhost/test.php", {
txtItemCode: txtItemCode,
}, function(data, status) {
//alert("Data: " + data + "\nStatus: " + status);
if (data == 'OK') {
$('#status').html(data);
result = true;
} else {
$('#txtItemCode').val('').focus();
$('#status').html("Code is already existing, please provide another one:)")
result = false;
}
});
return result;
}
Note: You can swap the value of result and check.

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