Marcolac
Marcolac

Reputation: 931

Condition in a get() request

I would like to put a condition on a jQuery get request depending on the data I get.

Here is my function:

function validateForm() {
    var username = $('#username').val()
    var result = ''

    $.get(
        '/auth_validate_username/', 
        { 'result': result }, 
        function(data) {
            $.post(
                '/auth_validate_username/', 
                { 'username': username }, 
                function(data) { 
                    $('.error_message').html(data); 
                }
            );
        }
    );
    return false;
};

HTML:

<form  method="post" onsubmit="return validateForm();">
    <input id='username' type="text" name="username"/>
    <div class='error_message'></div>
    <button type="submit">Valider</button>
</form> 

I would like to put a condition so that if the result I get with my get function is not empty, then the form is not submitted. But if result != '', then I want the form to be submitted.

Any idea on how I could put a condition on the form inside my get request?

Upvotes: 0

Views: 1026

Answers (1)

Florian Margaine
Florian Margaine

Reputation: 60817

In the function executed after the get request, you can execute any javascript statement. Including if.

function validateForm() {
    var username = $('#username').val()
    var result=''

    $.get(
        '/auth_validate_username/', 
        { 'result': result }, 
        function(data) {

            // Magical line there
            if (data !== '') {

                $.post(
                    '/auth_validate_username/', 
                    { 'username': username }, 
                    function(data) { 
                        $('.error_message').html(data);
                    }
                );
            }
        }
    );
    return false;
};

Upvotes: 3

Related Questions