jQuery(document).ready(function(jQuery) {
function checkEmail(email){
jQuery.post('someroute.php',
{email:eamil},
function(data){
if(data==error){
return false;
}
);
return true;
}
jQuery('#myform').submit(function(){
// como code and at the momment this
var result true;
//then I check email
var email = ('#myemail').val();
result = checkEmail(email);
return result;
});
The problem is this, a checkEmail function, first return true, and then return value jQuery.post function. Why?
I checked and in submit, first return true, and if you stop submit then you release that post return the value. Post works fine, but I don't understand why function checkEmail does not wait until post returns the value and goes on until the end to return true.
Because the jQuery.post() function is an AJAX request, and the first A in AJAX stands for asynchronous. That's exactly what asynchronous is, it doesn't stop code execution while it waits for a response. It fires the request and then immediately moves on to any code after the line making the request, in this case your return true statement.
Like Anthony Grist said. .post is an asynchronous call which means it doesn't wait to finish.
I've looked up the .post method (http://api.jquery.com/jQuery.post/).
It's basicly a shortcut for .ajax. You're missing the fail method in here so I would say use the .ajax call.
var value = 1;
var handlerUrl = "someroute.php";
//Do the Ajax Call
jQuery.ajax(
{
url: handlerUrl,
data: { email:eamil },
type: 'POST',
success: function (data)
{
return true;
},
error: function (jxhr, msg, err)
{
return false;
}
});
#user1727336 : Hi! You might want to edit your code and add the missing } and });. Here's a fix:
// enter code here
jQuery(document).ready(function(jQuery) {
function checkEmail(email){
jQuery.post('someroute.php', {email:eamil},
function(data){
if(data==error){
return false;
}
});
return true;
}
});
Related
i have a custom jQuery function with callbacks, in one of them i want to do a server-side check before some event is triggered.
Something like this:
var object = $('#object').customFunction({
onSomeEvent: function (someData) {
$.ajax({
...
...
success: function(data) {
if (data == ok) {
return true;
} else {
return false; *****
}
}
})
},
})
**** I want this "return false;" to be the return of "onSomeEvent".
I know i can make the ajax call async false, save the response data in a variable, check it after the ajax and return the false then, but i really would like to avoid the async false.
I really dont know what to try, everything i google is putting the ajax async on false.
Thanks in advance for your help!
to avoid setting async to false, im using this..
my_request = $.ajax({
...
...
})
my_request.done(function(data)){
//you can set the data to global
});
I got following code :
$.ajax({
type: "POST",
async: false,
url: "CheckIdExist",
data: param,
success: function(result) {
if (result == true){
return false;
}
},
error: function(error) {
alert(error);
return false;
}
});
if ajax return value is true, form needs to stop submit.
but it does not stopping submit form.
any help please.
I assume you have something like:
form.submit(function(event) {
$.ajax(...);
});
You want to return false (or call event.preventDefault()) in the event handling function itself, and not in the AJAX call, such as:
form.submit(function(event) {
event.preventDefault();
$.ajax(...);
});
A slight variation of this question is:
I want to use jquery and ajax to present an error message to a user,
but then to do normal processing if there is no error.
Suppose method "check" returns a response that is empty if there is no error, and has the error(s) in it if there are any.
Then you can do something like this in your ready function:
$("#theform").submit(function() {
var data = { ... }
$.get('/check', data,
function(resp) {
if (resp.length > 0) {
$("#error").html(resp);
} else {
$("#theform").unbind('submit');
$("#theform").submit();
}
});
event.preventDefault();
});
So, how does it work? When the outer submit function is triggered, it builds the data needed for the AJAX call (here the higher level function get). The call is scheduled, and the main thread of operation immediately continues, but the submit is unconditionally stopped, so nothing apparent happens.
Some time passes, and the AJAX call returns the result of the request. If non-empty, the result is shown to the user.
If the response is empty, however, the submit function is unbound. This prevents the ssytem from making an extra call through the outer submit function. The inner submit function is called. This triggers an actual form submission to the form's target, and life goes on as expected.
You need to do a callback.
This entry in the FAQ helped me a lot when I had this exact problem.
getUrlStatus('getStatus.php', function(status) {
alert(status);
});
function getUrlStatus(url, callback) {
$.ajax({
url: url,
complete: function(xhr) {
callback(xhr.status);
}
});
}
The reason for that is that you can not return in an AJAX function.
The code above does not work as desired due to the nature of asynchronous programming. The provided success handler is not invoked immediately, but rather at some time in the future when the response is received from the server. So when we use the 'status' variable immediately after the $.ajax call, its value is still undefined.
You can't put this code in a function or in the onsubmit of a form, the success function returns it's result returning to the jQuery ajax context, NOT the form submit context.
In this case you need to perform a synchronous http request, i.e. you have to set the async option to false.
In your version the httpxmlrequest is asynchronous. It might be finished long after your onsubmit handler has returned and the onsuccess callback is invoked out of context of the onsubmit handler.
The "return false" will be the return value of the anonymous function function(result) {... } and not the return value of the onsubmit handler.
I had this problem also but solved it by changing the input type="submit" to type="button" and then just do your ajax request
$("input#submitbutton")
{
$.ajax(
{ type: "POST",
async: false,
url: "CheckIdExist",
data: param,
success: function(result) {
if (result == true){
//TODO: do you magic
}
else
$("form").submit();
},
error: function(error) {
alert(error);
return false;
}
});
});
I have been trying to wrap my head around AJAX requests, and currently implementing some server-side validation for a twitter-bootstrap wizard in Javascript. I am experiencing some bizarre behavior where the function fails the first time its executed, but works as intended the second time. I have simplified my code into this structure:
function do_ajax_validate($user,$email) {
$.ajax({url: "checkuser.php?field=username&query=" + $user, success: function(result){
if (result != 'Valid')
{
$("#userlabel").html(result);
$("#userdiv").addClass("has-error");
$("#userdiv").removeClass("has-success");
$("#username").focus();
is_good[0] = false;
} else {
$("#userlabel").html($user + " is available!");
$("#userdiv").removeClass("has-error");
$("#userdiv").addClass("has-success");
is_good[0] = true;
console.log(is_good[0]);
}
}});
console.log(is_good[0]);
$.ajax({url: "checkuser.php?field=email&query=" + $email, success: function(result){
if (result != 'Valid')
{
$("#emaillabel").html(result);
$("#emaildiv").addClass("has-error");
$("#emaildiv").removeClass("has-success")
$("#email").focus()
is_good[1] = false;
} else {
$("#emaillabel").html('Looks good!');
$("#emaildiv").removeClass("has-error");
$("#emaildiv").addClass("has-success")
is_good[1] = true;
}
}});
console.log(is_good[0]);
console.log(is_good[1]);
if ((is_good[0])&&(is_good[1])) {
return true;
} else {
return false;
}
}
Whenever I go into the console and try to run the function, I call it with a user/email that I know is available and get this output:
do_ajax_validate('available_username', 'available#email.address');
false
false
false
Whenever I run the exact same line, I get this output:
do_ajax_validate('available_username', 'available#email.address');
true
true
true
Then checking on a username/email that I know is taken, it returns the last values:
do_ajax_validate('taken_username', 'taken#email.address');
true
true
true
And (you guessed it) - executing the function again returns the expected results:
do_ajax_validate('available_username', 'available#email.address');
false
false
false
I've been trying different methods for hours now and getting these same bizarre results. What am I doing wrong?
Ajax calls run asynchronously in javascript. Your success callback will only be executed once the Ajax call returns, thus your console.log()s can be called before the success functions executes.
You can have a two solutions for this problem:
Work with result inside the callback you assign to success property. Try to console result under the success property
use async: false under AJAX call like:
$.ajax({
url: "checkuser.php?field=username&query=" + $user,
async: false,
success: function(result){
console.log("result")
} });
I execute an ajax request using $.post, this is my code:
$.post(postUrl, postData, function(response)
{
if(response.status == "SUCCESS")
{
updateConfirmFrame();
}
else
{
return false;
}
}, 'json');
now if the response return SUCCESS the code continue calling a function that unlock some control, but if an exception is handled, so the code should blocked. Now I've put an alert in return false; condition and the alert is printed correctly but, the return false doesn't stop the code. I don't want that the code continue the execution. I also tried with throw Exception but doesn't working. What am I doing wrong?
UPDATE
$.post(postUrl, postData)
.done(function(response)
{
if(response.status == "SUCCESS")
{
updateConfirmFrame();
}
else
{
alert("error"); //The problem is here
return false;
}
})
.fail(function(err)
{
return false;
});
alert("hi wor")
Use that:
$.post(url, postdata)
.done(function(response) {
})
.fail(function(err) {
// error
});
The syntax you used is $.post(postUrl, postData, success_callback, fail_callback);
return statements only return the function they are within, stopping further code execution in that function. They do not stop JS code execution in general.
The alert statement you are saying shouldn't run because you've done return false; is not in the function returning false. It would not be affected by the fact that some other function returned false. It absolutely should run.
On top of that, the success function for your post call is an event callback. It is created, but does not run until the actual loading of the file happens, which is gonna be long after other code outside your ajax stuff finishes. So the code in that function isn't even gonna be executing before that alert takes place.
I am using the below json call in my javascript method
function go123(){
var cityName = "";
var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) {
if (data.properties.city != null){
cityName = data.properties.city;
check = true;
} else {
cityName = "NaN"
}
}); // end of my Json Call.
// my validation is done below
if(cityName != "NaN"){
return false;
} else {
// here I except the cityName to not be "" but be some value which is set as :cityName = data.properties.city;
return true;
}
} // end of my function
Now what problem I am facing is that before my Json call is compelete the next set of statements ( in the code below the line "// my validation is done below " ) is already executed.
I want to get the values set in my json call (cityName) and only once when the call is completed then only I want the next set of statements to be executed.
Please help me on this. Any advice/ideas/suggestions will be highly appreciated ! Thanks.
The function you passed into $.getJSON() is the callback run when the function completes successfully. All else being equal, stick the "rest of it" inside that method. If you can't do so, what you're after is called a jQuery Deferred. See http://www.erichynds.com/jquery/using-deferreds-in-jquery/ and http://joseoncode.com/2011/09/26/a-walkthrough-jquery-deferred-and-promise/ for code that looks like so:
var req = $.getJSON('blah', 'de', 'blah');
req.success(function(response){
// The request is done, and we can do something else
});
AJAX calls are asyncrhonous. They don't wait for the reply. They operate in the background and execute the code that follows it immediately after the call. Therefore, the data received in getJSON is not yet there when the operations below it are executed.
You can put the operations you want in the callback so that they get executed when the data is revceived:
function go123(callback){
var temp = $.getJSON("https://abc.in/api/city?callback=?", args,function (data) {
//execute the callback, passing it the data
callback(data);
});
}
//when you call go123, it get's back the result:
function goBefore123(){
//get our JSON
go123(function(data){
//when we get our data, evaluate
if (data.properties.city != null){
cityName = data.properties.city;
check = true;
alert('executed after returned');
afterCall();
} else {
cityName = "NaN"
}
});
alert('i am executed before anything else');
}
function afterCall(){
alert('im also executed after');
}
Calling an external url will take too much time, wait for the result
Check below
var jqxhr = $.getJSON("example.json", function() {
alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });
http://api.jquery.com/jQuery.getJSON/
.success
http://api.jquery.com/jQuery.getJSON/