简体   繁体   中英

Retrieving AJAX value from a different Javascript function

In this simplified example of a larger web app, consider a simplistic registration form with fields: username, firstname, lastname and a Register button 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 completed, jQuery fires an ajax search of a database to see if that username already exists. This same search is also triggered when one clicks Register (for reasons removed from this simplified example).

PROBLEM: Everything works great when leaving the username field. However, after clicking Register , I don't know how to retrieve the result of the AJAX search and stop the form from submitting if the username already exists. I've tried all kinds of different things, but have returned the code to this state so it is easiest for the reader to assist.

For example, I tried integrating the suggested solution from this question , but I was unsuccessful applying it to my situation... I tried setting async:false inside the ajax function... I also tried calling the checkUsername(uname) from inside 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();
    }
}

One both rejoices and weeps when answering his own question, but here goes. The solution was to send the checkUsername() function as an input param to the checkForm() function, and to make the checkUserName() function return a value that we could check inside checkForm().

Therefore, we must modify the $('#register').click function thusly:

$('#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 thus:

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 kudos to Felix Kling for this helpful post .

Might put return false in the function call in the HTML form markup.

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

Also, you might bind the function to the button's click event using

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

Put a return false at the end of your #register button click function, right below checkForm() . The button is continuing to fire the form submit. when you have that handled by your javascript function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM