简体   繁体   中英

Javascript Returns Incorrect Value

I have a function which returns data from an AJAX call to determine if a user has any credits remaining and then displays the data accordingly. The strange thing is that the function does not return the expected result. Here is the code:

function setupBuildInputs() {
    noCreditsError = '<div class="alert alert-danger">You have no build credits remaining, please contact a representative to purchase more.</div>';

    if ( $('#newWebsiteBuildForm #user_id').length ) { 
        $('#newWebsiteBuildForm #user_id').change(function () {
            userID = $(this).val();
            jQuery.get(SITE_URL + '/ajax.php?action=getBuildCreditsRemaining&id=' + userID, function(numOfCredits) {
                if ( numOfCredits > 0 ) {
                    // Get latest website URL and show it on the page
                    $('#websiteURLHolder').html('Updating...');
                    jQuery.get(SITE_URL + '/ajax.php?action=getNextWebsiteUsername&id=' + userID, function(data) {
                        $('#websiteURLHolder').html(data + '.checkoutyournewsite.com');
                    });
                } else {
                    $('#quickBuildTagsHolder').html( noCreditsError );
                }
            });
        }); 
    }
    $('#newWebsiteBuildForm #template').change(function () {
        // Show the build form items
        numOfRemainingCredits = checkBuildCredits( $('#newWebsiteBuildForm #user_id').val() );
        alert(numOfRemainingCredits);

        if ( numOfRemainingCredits > 0 ) {
            $('#quickBuildTagsHolder').html('Updating...');
            jQuery.get(SITE_URL + '/ajax.php?action=returnQuickBuildTags&template=' + $(this).val(), function(data) {
                $('#quickBuildTagsHolder').html(data);
            });
        } else {
            $('#quickBuildTagsHolder').html( noCreditsError );
        }
    });
}
function checkBuildCredits( userID ) {
    buildCredits = 0;

    jQuery.get(SITE_URL + '/ajax.php?action=getBuildCreditsRemaining&id=' + userID, function(data) {
        buildCredits = data;
    });

    return buildCredits;
}

setupBuildInputs();

Using firebug I cans see that the call to ajax.php?action=getBuildCreditsRemaining pulls the correct id from the page and returns the correct value (9999). To debug further I added the alert on the second change event handler and the result is coming back as 0 instead of 9999.

Next I added 2 alerts to the even added an checkBuildCredits function. The first verified that the ajax call works and that data is set as 9999. The second strangely shows that buildCredits is still set to 0 right before the function returns.

In the setupBuildInputs function, the first change handler uses the same ajax call and it works fine, the second change handler which uses the functions of course fails since it doesn't get 9999 and instead sees 0.

Any ideas what is happening here?

jquery.get is defaultly Asynchronous. so before your fetch the data,the function return the 0 value in your function checkBuildCredits

Instead of $.get() try using the following:

$.ajax({
    url: SITE_URL + '/ajax.php?action=getBuildCreditsRemaining&id=' + userID,
    success: function(data) {
        buildCredits = data;
    },
    asynch: false
});

This will wait for the ajax call to complete before continuing script execution.

replace checkBuildCredits with this

function checkBuildCredits( userID, successFn ) {


jQuery.get(SITE_URL + '/ajax.php?action=getBuildCreditsRemaining&id=' + userID, function(data) {
    successFn(data);
});

}

Then when you call checkBuildCredits, do it like this

checkBuildCredits( $('#newWebsiteBuildForm #user_id').val(), function(numOfRemainingCredits )
{
 if ( numOfRemainingCredits > 0 ) {
        $('#quickBuildTagsHolder').html('Updating...');
        jQuery.get(SITE_URL + '/ajax.php?action=returnQuickBuildTags&template=' +   $(this).val(), function(data) {
            $('#quickBuildTagsHolder').html(data);
        });
    } else {
        $('#quickBuildTagsHolder').html( noCreditsError );
    }

});

As the others have explained it, jquery.get is Asynchronous. And based on your design, you are treating jquery.get as a Synchronous call.

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