AJAX not working without alert box [duplicate] - javascript

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.

Related

returning data nested inside ajax callback [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
im trying to get data from an ajax function to my actual app but i cant seem to pass the data outside of the function, ive read other questions and tried their recommendation but it doesnt seem to be working because its not waiting for ajax to finish loading before trying to return the data,
im trying to return uid so that i can do something like
user = getUserID('test');
instead of
getUserID('user', function(id){ console.log(id); });
because i am assigning the returned data to a variable
getUserID = function(user, cb) {
var uid;
$.ajax({
type: "GET",
url: "/user_comment.php",
data: {
user: user
},
success: function(result) {
if (result) {
uid = /name="recipient_id" value="(.*)"/g.exec(result)[1];
console.log('1 ' + uid);
if(cb) {
try {
cb(null, uid);
} catch(e) { cb(e); }
}
} else {
console.log("ERROR!! - No data returned !")
}
}
});
console.log('2 ' + uid);
return uid;
},
all it does right now is
2 undefined
1 5511194
2 undefined
1 1462473
2 undefined
1 5469682
so it is not setting the variable
Your code is returning the value of "uid" before any value is applied to it. You can see that your variable is set in "success" callback. This means that this callback will be called only after the asynchronous call is done. Your "getUserID" function will end AND the "return" statement will be executed BEFORE the callback. Play with your code in the debugger, you'll see what's actually going on. So what you should do is use the returned value in the "success" callback instead of the returned value from "getUserID". Like this:
getUserID('test', function(uid){
... do your stuff here => uid is defined and has the value you're looking for
});
But just don't try to do something like:
var uid = getUserID('test');
... things and stuff

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 call does not assign a value in the done promise [duplicate]

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.

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.

Categories