0

I'll say right off the bat that this question seems to address the same situation, but for the life of me I'm not seeing what the solution/answer is there. Perhaps someone just needs to "spell it out" more clearly for me!

I have the following function:

function CheckIfUrlExists(checkUrl) {
    var exists = '';
    $.ajax({
        type: 'POST',
        url: '../scripts/branchAdmin.php',
        data: {checkUrl: checkUrl},
        cache: false,
        success: function(response) {
            console.log('response: ' + response);
            if (response === 'true') {
                exists = 'true';
            } else if (response === 'false') {
                exists = 'false';
            }
        },
        error: function(response) {
            // return false and display error(s) from server
            exists = 'false';
        }
    });

    console.log('exists: ' + exists); // always displays empty string, regardless of what the php script returns

    return exists;
}

And I'm calling it with this:

var exists = CheckIfUrlExists($tr.find('input.editUrl').val());

if (exists === 'false') {
    //if (!CheckIfUrlExists($tr.find('input.editUrl').val())) {
    // New URL entered, verify user want to save it
    $('#confirmAddNewUrlDialog').data('row', $tr).dialog('open');
    ... // code to handle result
}

How can I get the "CheckIfUrlExist() function to return a true or false (or any value for that matter) so I can use it in the above code?

Community
  • 1
  • 1
marky
  • 4,878
  • 17
  • 59
  • 103
  • The point of the answers there is that you shouldn't return the result from this function. AJAX is _asynchronous_, so the function returns before the call completes. Whatever you want to do should be done in the callback. – Barmar Feb 14 '13 at 16:43
  • Got it, Barmar. Thanks - functionality works as needed now. – marky Feb 14 '13 at 17:20

1 Answers1

0

Make the ajax call async option to false. then you'll get the result. see the link https://stackoverflow.com/a/1531710/399414

$.ajax({
        type: 'POST',
        async: false,
        url: '../scripts/branchAdmin.php',
...
Community
  • 1
  • 1
Sen Jacob
  • 3,384
  • 3
  • 35
  • 61