Return False not working inside jQuery.ajax

P.S.: Read "EDITED on 2019-06-29":

I have a webform for updating user information, and when he updates his email a verification is performed via ajax() so that he is warned if the new email address is already in use by another user.

I'm trying to cancel the form submission when the email is in use, but return false; doesn't work.

Any other return false; within if statements are working fine, the problem is only with this one inside the jQuery.ajax() call.

Here's the actual code:

var email = jQuery('#email').val();
jQuery.ajax({
    type : 'GET',
    url : '/ajax/verify-email.php?email=' + email,
    success : function( d ) {
        if( d == '1' ) {
            alert('Another user is using this email');
            jQuery('input[name="email"]').focus();
            return false; // this guy over here is not working!!!!
        }
    }
});

Does anyone have a solution?

EDITED on 2019-06-29

When I asked this question back in 2012 I wasn't aware of Promises in Javascript, neither knew about "$.when" (even though added 3 years later of this question) to handle asynchronous requests alongside $.ajax.

Today, you can handle the same scenario easily, as this:

let email = $('#email').val();
$.when(
  $.ajax({
    type : 'GET',
    url : `/ajax/verify-email.php?email=${email}` 
  })
 .then(function(d) {
   alert('Another user is using this email');
   $('input[name="email"]').focus();
});
// your code continues from here as desired...

The A in AJAX is actually very important. It stands for Asynchronous. This means that you trigger a request to the server which might take some time to process and you get a response later. This response happens inside the success callback. But since this happens much later than the actual form submission, your form has actually been already submitted before the response comes back. So returning false from an AJAX success callback makes no sense whatsoever. What you want to do is to return false from the submit handler of your form. Let's see how we could implement this.

You could subscribe to the .submit handler of the form and send an AJAX request to verify whether the email has already been taken or not and if it is not taken manually trigger the submission of the form inside the success AJAX callback:

$('form').submit(function() {
    // we send an AJAX request to validate the unicity of the email
    $.ajax({
        url: '/ajax/verify-email.php',
        type: 'POST',
        data: { email: $('#email').val() },
        // we set the context to the form so that inside
        // the success callback 'this' points to the form
        context: this,
        success: function(result) {
            if (result != '1') {
                // If the server send something different than 1
                // we know that the email is unique and trigger
                // the submission of the form using the underlying
                // DOM element to avoid calling the .submit handler
                // recusrively
                this.submit();
            } else {
                // The email is not unique => we are informing
                // the user that the email is already in use
                alert('Another user is using this email');
                $('#email').focus();
            } 
        }
    });

    // we cancel the normal submission of the form    
    return false;
});

Also never rely on client side validation. Make sure that you are performing the email is unique check once the form has been successfully submitted to the server. If you are using a SQL database that's easily achieved with a unique constraint on your Email field.

javascript, The A in AJAX is actually very important. It stands for Asynchronous. This means that you trigger a request to the server which might take some time to process  I'm trying to cancel the form submission when the email is in use, but return false; doesn't work. Any other return false; within if statements are working fine, the problem is only with this one inside the jQuery.ajax() call. Here's the actual code:

You should not use .submit() on this situation, use a flag system instead, .submit() should only be used for <form> elements.

var email = jQuery('#email').val();
var flag = 0;
jQuery.ajax({
    type : 'GET',
    url : '/ajax/verify-email.php?email=' + email,
    async: false,
    success : function( d ) {
        if( d == '1' ) {
            alert('Another user is using this email');
            jQuery('input[name="email"]').focus();
            flag = 1;
        }
    }
});
if(flag == 1) return false;

[jQuery] function $.ajax return true/false ?, Maybe there is a logic problem in your jQuery-Ajax.php page where it is returning false. Take a look to make sure..to test that force it to return  Here Mudassar Ahmed Khan has explained with an example, how to render Partial View in jQuery as Html.RenderPartial and Html.Partial helper functions will not work with jQuery Client Side scripting. The Partial View will be returned from Controller using AJAX to jQuery AJAX method and finally it will be rendered as HTML inside DIV using jQuery in ASP.Net MVC Razor. TAGs: ASP.Net, jQuery, jQuery

You run async code here. At the moment you are trying to return false, it is far to late. Your function already returned undefined. You need to provide a callback if you want to process the result of your success.

When to use PreventDefault( ) vs Return false in JavaScript , the code continues..but noting to show The problem is: I see: alert 1 alert 2 alert true but NOT alert 3?? Why? Reply  working - .post inside jQuery.validator.addMethod always returns false jquery.validator.addmethod not working (6) I am very new to jQuery and javascript programming.

you should use event.preventDefault() as shown below.

$('#form').submit(function(event) {
    $.get('/ajax/verify-email.php?email=' + $('#email').val(), function(d) {
        if (d == '1') {
            alert('Another user is using this email');
            $('#email').focus();
            event.preventDefault();
        }
    });   
});

The difference between 'return false;' and 'e.preventDefault();', Any other return false; within if statements are working fine, the problem is only with this one inside the jQuery.ajax() call. Here's the actual code: .then() is a Promise method added in jQuery 1.8, which combines both the .done() and .fail() methods. It's mentioned in the remarks on the .ajax() method you linked to. The remarks also say that the .success() callback is deprecated as of v1.8, and that you should use the Promise methods instead.

<form action="yourpage" method="post" onsubmit="return matchpass();">
  <div>
   <label> Name</label>
   <input type="text" name="name" id="name">
  </div>
  <div>
   <label> Email ID</label>
   <input type="email" name="email" id="email">            
  </div>
  <div>
   <label> Mobile No</label>
   <input type="text" name="mob"  maxlength="10" onkeyup="check_if_exists();" autocomplete="off" id="mob">
  </div>                             
  <div>
   <button type="button" >Send</button>
  </div>
  <span id="err"></span>
  <div>
   <label> OTP</label>
   <input type="password" name="otp" id="otp"  maxlength="6" placeholder="****">
   <span id="err2"></span>
  </div>    
  <div>
   <input type="reset" value="Reset" class="reset-btn">
   <input type="submit" name="submit" id="submit" value="Submit" >              
  </div>
</form>
<input type="hidden"  id="otpcheck"/>



<script>
function matchpass()
{

     $.ajax({   
    type:"post",
    url: "yourpage",
    data:{ mobile:mob,otp:otp},
    success:function(data)
    {
       if(data==1)
       {
           document.getElementById("otpcheck").value=1; //important
       }else{

           document.getElementById("err2").style.color = "red";
           document.getElementById("err2").innerHTML = "invalid OTP Number ";
         document.getElementById("otpcheck").value=0; //important
       }


    }
    });

    if(document.getElementById("otpcheck").value==0){
        return false;
    }

}

Simplest ajax form not working when it should, In Javascript, there are two methods- preventDefault() and Return false, that are used (non-jQuery) event handlers, in which, notably, return false does not stop the script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"​  I have a function that i want to call another function to get a result from the server web page (text format) and return it to the original function this is not working - what am I doing wrong

Return bool value from Ajax, Have you ever seen those two things (in the title) being used in jQuery? as text to the body every time a link was clicked but not actually go to that link. The return false; part of that code prevents the browser from performing the So let's say you have a box inside a box. The correct way return false works is (jQuery):. jQuery handles return false as an internal flag — using it to mean “prevent default and stop propagation”. Vanilla event listeners do not handle it the same way. If you’re not using jQuery then return false in addEventListener is nothing but a legacy hangover — a shorthand for e.returnValue = false, which is deprecated syntax. It won’t behave consistently between browsers, but you never need to use it anyway.

button should not postback if jquery.ajax return false, jQuery('#submitform').submit(ajaxSubmit); function ajaxSubmit(){ var submitform = jQuery(this).serialize(); empty div to show returned data } }); return false; }. Ajax Post on iOS Safari not working? Its the cache! Not sure when this took effect, but a simple public facing web application we wrote using jQuery.ajax for doing our form posts nicely started not working on iOS devices.

Jquery ajax return false not working. Return False not working inside jQuery.ajax, The A in AJAX is actually very important. It stands for Asynchronous. .delete-person is an element that is dynamically added to the DOM after the AJAX call has been made. Since your jQuery script runs upon DOMready (when .delete-person is not present during runtime), the click event would not be bound to the element.

Comments
  • why do you need it to return false? Is this part of a larger code block that could help somebody answer the question?
  • what do would you expect it to do there? Probably it should be somewhere else to block a form submission
  • You can avoid the proceed flag entirely if you call the submit function of the form directly; calling HTMLFormElement#submit doesn't trigger submit handlers. But note that there's a race condition here; the user could change the email while the ajax call is running, resulting in sending in the changed (and unchecked) email. (BTW, you use proceed in one place, process in the other.)
  • @T.J.Crowder, good tip about using the actual DOM element to submit the form. Will update my answer. Also thanks for noticing the proceed vs process data attribute. As far as the race condition is concerned, well, that's why one should absolutely never rely on client side validation and make sure to enforce this validation on the server.
  • Other than the completely unjustified use of "unicity". ;-) Just giving you a hard time, it was always okay. Now it's even better. One nit I might pick is that $(this).get(0).submit(); is an awfully long way to write this.submit(); ;-)
  • @T.J.Crowder, OMG: $(this).get(0).submit(); -> that is a good candidate for thedailywtf.com :-) As far as unicity is concerned, well, Google Chrome underlines, so I know it is wrong but I just dunno the correct word.
  • @Darin: LOL! It's actually a word: dictionary.reference.com/browse/unicity Most people would have said "uniqueness." Here I thought you were showing off your vocabulary. (Great answer, btw, upvoted long ago.)
  • that's not the problem. He tries to return a value in an async function^^
  • I tried async false in jquery ajax, but it didn't work as well4