Getting AJAX value from another Javascript function

For this simplified example of a larger web application, consider a simplified registration form with username, firstname, lastname, and a Register button fields type="button"

.

<form action="" method="post" id="cns_form">
    <table id="companyTable"><tr>
        <td width="200">
            First name*:<br />
            <input type="text" id="first_name" name="first_name">
        </td>
        <td width="200">
            Last name*:<br />
            <input type="text" id="last_name" name="last_name">
        </td>
    </tr></table>
    <input type="button" value="Register" id="register" >
</form>
<div id="alert" title="Alert"></div>

      


When the username field is complete, jQuery triggers an ajax database lookup to see if that username exists. This same search is also triggered when clicked Register(for reasons removed from this simplified example).

PROBLEM: Everything works fine when exiting the username field. However, after clicking, RegisterI don't know how to get the AJAX search result and stop the form from submitting if the username already exists. I've tried all sorts of things, but set the code back to this state, so it's the easiest for the reader to make it easier.

For example, I tried to integrate the suggested solution from this question , but I was unable to apply it to my situation ... I tried setting async:false

inside ajax ... I also tried to call checkUsername (uname) from the checkForm function, but that didn't work either. A little help?

jQuery document.ready:

$(function(){
    $('#username').blur(function() {
        var uname = $.trim($(this).val());
        checkUsername(uname);
    }); //END BLUR username

    $('#register').click(function() {
        var uname = $.trim($( '#username').val());
        checkUsername(uname);
        checkForm();
    });
}); //END document.ready

      


AJAX Call:

function checkUsername(uname) {
        if (uname != '') {
            $.ajax({
                type: "POST",
                url: 'ajax/ax_all_ajax_fns.php',
                data: 'request=does_this_username_already_exist&username=' + uname,
                async: false,
                success:function(data){
//alert('Returned AJAX data: '+data);
                    if (data != 0) {
                        var existing_user = data.split('|');
                        var fn = existing_user[0];
                        var ln = existing_user[1];
                        focus_control = 'username';
                        $( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
                        $( '#alert' ).dialog( 'open' );
                    } //EndIf data<>0
                } //End success
            }); //End $.ajax
        } //End If this.val <> ""
}

      


CheckForm function:

function checkForm() {
    var un = $.trim($( '#username').val());
    var fn = $( '#first_name').val();
    var ln = $( '#last_name').val()

    if (un=='' || fn=='' || ln=='') {
        $( '#alert' ).dialog({
            height: 200,
            width: 300,
        });
        $( '#alert' ).html( 'Fields marked with an asterisk are required.' );
        $( '#alert' ).dialog( 'open' );
    } else {
        $("#cns_form").submit();
    }
}

      

+3


source to share


3 answers


One is both happy and crying when he answers his own question, but here he goes. The solution was to send the checkUsername () function as an input parameter to the checkForm () function and make the checkUserName () function return a value that we could check inside checkForm ().

Therefore, we must change the function $('#register').click

as follows:

$('#register').click(function() {
    var uname = $.trim($( '#username').val());
    checkForm(checkUsername(uname)); //<===========================
});

      


THEN the checkUsername () function, thus:



function checkUsername(uname) {
        var returnVal = 0; //<=================================
        if (uname != '') {
            $.ajax({
                type: "POST",
                url: 'ajax/ax_all_ajax_fns.php',
                data: 'request=does_this_username_already_exist&username=' + uname,
                async: false,
                success:function(data){
//alert('Returned AJAX data: '+data);
                    if (data != 0) {
                        var existing_user = data.split('|');
                        var fn = existing_user[0];
                        var ln = existing_user[1];
                        focus_control = 'username';
                        $( '#alert' ).html( 'That username is already in use by ' + fn +' '+ ln +'. Please choose another.' );
                        $( '#alert' ).dialog( 'open' );
                        returnVal = 0; //<============================
                    } //EndIf data<>0
                } //End success
            }); //End $.ajax
        } //End If this.val <> ""
    return returnVal; //<==============================
}

      


And the checkform () function:

function checkForm(exists) { //<============================
alert('sub checkForm(). value of exists: ' + exists);
    if (exists==9) { //<================================
        $( '#alert' ).html( 'That username is already in use' + existing +'. Please choose another.' );
        $( '#alert' ).dialog( 'open' );
    }else{ //<==========================================
        var un = $.trim($( '#username').val());
        var fn = $( '#first_name').val();
        var ln = $( '#last_name').val()

        if (un=='' || fn=='' || ln=='') {
            $( '#alert' ).dialog({
                height: 200,
                width: 300,
            });
            $( '#alert' ).html( 'Fields marked with an asterisk are required.' );
            $( '#alert' ).dialog( 'open' );
        } else {
            $("#cns_form").submit();
        }
    } //<===================================================
}

      

Thanks and hope Felix Kling for this helpful post .

+4


source


Can be placed return false

in a function call in HTML form markup.

<form>
    <bunchOfElements />
    <button onclick="checkUserName(); return false">Check Name </button>
</form>

      



Alternatively, you can bind a function to the button click event using

$(document).ready(function(){
    $("#buttonID").bind('click', function(){ 
        //do your thing
        checkForm();
    });
});

      

+2


source


Place a return false

at the end of the click function of the #register button below checkForm()

. The button continues to fire the form submit. when you have what your javascript function is handling.

+1


source







All Articles