-2

I have simple registration form. Ajax and form works fine but can't connect them by variable, I mean when ajax check that email is in database register should stop by variable error but it isnt.

Code:

$('.login').submit(function(e) {

        e.preventDefault(); 
        var error = 0;
        var self = $(this);

        var $name = self.find('[type=name]');
        var $email = self.find('[type=email]');
        var $pass = self.find('[type=password]');

        //MY AJAX
        var email = $email.val();


$.ajax({
    url: 'http://localhost/FPD/nowe/inc/rejestracja.php?action=emailcheck',
    data: {
        'email': email
    },
    type: 'POST',
    success: function(odp) {
        if (odp == 1) {
            createErrTult("Błąd! taki email już istnieje w bazie!", $email)

//THAT ERROR VARIABLE DOESNT WORK OUTSIDE AJAX FUNCTION
                error++;
        }
    },
    error: function(xhr, textStatus, error) // THOSE ROWS
    {
       alert(error);
    }
});

        if (error!=0)return;

//THAT STILL WORKS EVEN AJAX ERROR

        self.find('[type=submit]').attr('disabled', 'disabled');

        self.children().fadeOut(300,function(){ $(this).remove() })
        $('<p class="login__title">sign in <br><span class="login-edition">welcome to A.Movie</span></p><p class="success">You have successfully<br> signed in!</p>').appendTo(self)
        .hide().delay(300).fadeIn();


        // var formInput = self.serialize();
        // $.post(self.attr('action'),formInput, function(data){}); // end post
}); // end submit
Michał Lipa
  • 117
  • 8
  • 1
    Check this, this will be your problem: http://stackoverflow.com/questions/5976142/variable-scope-question-in-my-jquery Ajax is asynchronously, so I think, you want to use it later – vaso123 Dec 30 '14 at 12:07
  • you should declare error variable globally. – A.T. Dec 30 '14 at 12:08
  • 1
    AJAX(Asynchronous) will not wait until you recieve something from the server. As it is asynchronous, your `error` variable is zero and the process continues. Use `async: false` in ajax call to make it synchronous. – Karthik Chintala Dec 30 '14 at 12:08

1 Answers1

0

The reason is ajax is called Asynchronously. You have to make async: false in your ajax call. So your code will become :

$.ajax({
    url: 'http://localhost/FPD/nowe/inc/rejestracja.php?action=emailcheck',
    data: {
        'email': email
    },
    async : false,   //<----
    type: 'POST',
    success: function(odp) {
        if (odp == 1) {
            createErrTult("Błąd! taki email już istnieje w bazie!", $email)

//THAT ERROR VARIABLE DOESNT WORK OUTSIDE AJAX FUNCTION
                error++;
        }
    },
    error: function(xhr, textStatus, error) // THOSE ROWS
    {
       alert(error);
    }
});

This will ensure that nothing will executed after ajax call unless you get your response.

Rakesh Shetty
  • 4,548
  • 7
  • 40
  • 79