1

Possible Duplicate:
Why is this function returning “undefined”?

Why in following code return is undefined in case return should is true? what do i do?

<input type="text" value="" class="ticket_code">

function ticket_check() {
    var val = 'ticket_code=' + $('.ticket_code').val();
    var input_val = $('.ticket_code').val();
    $.ajax({
        type: "POST",
        url: 'get_ticket_code',
        data: val,
        cache: false,
        success: function (data) {
            var result = true;
            if (data != 0) {
                $('div').empty().hide().fadeIn('slow').append(data + '<input name="name_ticket_code" value="' + data + '" style="display: none;">');
            } else {
                if (input_val) {
                    $('div').fadeOut('slow', function () {
                        $(this).empty();
                    })
                    result = false;
                }
            }
            return result
        }
    });
}

alert(ticket_check());
Community
  • 1
  • 1
Jennifer Anthony
  • 2,227
  • 10
  • 37
  • 56

4 Answers4

2

Because You are making an asynchronous call and so when the alert is executed nothing has been returned yet.

You could set async to false

   $.ajax({
        type: "POST",
        url: 'get_ticket_code',
        data: val,
        async: false,
        cache: false,
        success: function (data) {
            var result = true;
            if (data != 0) {
                $('div').empty().hide().fadeIn('slow').append(data + '<input name="name_ticket_code" value="' + data + '" style="display: none;">');
            } else {
                if (input_val) {
                    $('div').fadeOut('slow', function () {
                        $(this).empty();
                    })
                    result = false;
                }
            }
            return result
        }
    });

but this would lock the browser.

A better approach is to continue the flow from the "success" function according to the esit of the ajax call

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
2

$.ajax call is asynchronous, you can't call and get a return value from it. The code return result doesn't get executed when you first call ticket_check.

Your function is already manipulating the DOM, what are you trying to achieve?

stivlo
  • 83,644
  • 31
  • 142
  • 199
  • I put `async: false,` in the code, but still is same `undefined` in output. – Jennifer Anthony Oct 14 '11 at 16:43
  • @AliciaCibrian don't do that. just do your actions within success and error handler as Jared Farrish said. Event programming is a bit of paradigm change, is not like calling a function and getting a result. You ask for an action, you book for it, you have immediately the control back to do something else if needed, several milliseconds later, your ajax will come back and fire an event. – stivlo Oct 14 '11 at 16:48
1

Here's a common way to achieve what you're after: create some sort of "promise" object, which will be returned by ticket_check():

function Promise() {
    var callback = function() {};

    this.onResult = function(result) {
        callback(result);
    }

    this.complete = function(handler) {
        callback = handler;
        return this;
    }
}

function ticket_check() {
    var promise = new Promise();

    // ...
    $.ajax({
        // ...
        success: function (data) {
            var result = true;
            // ...
            promise.onResult(result);
        }
    });

    return promise;
}

This allows you to call code like this:

ticket_check()
    .complete(window.alert);
Dan Tao
  • 125,917
  • 54
  • 300
  • 447
  • 1
    Nice. jQuery does have a [`.promise()`](http://api.jquery.com/promise/) built-in (not sure what version it was introduced). – Jared Farrish Oct 14 '11 at 16:21
  • Perhaps I'm misreading it, buy you named it `complete` but used `success`. – pimvdb Oct 14 '11 at 16:46
  • @Jared: Ha, that's pretty funny. I just honestly didn't know (my best guess is that we hand-rolled our own on my current project before it was introduced and have just been using that ever since). Yet another case of [jQuery doing absolutely everything!](http://philosopherdeveloper.wordpress.com/2011/07/29/does-jquery-turn-programmers-into-babies/) ;) – Dan Tao Oct 15 '11 at 01:42
  • @pimvdb: No, you didn't miss anything... I just typed too fast. Thanks for spotting that! – Dan Tao Oct 15 '11 at 01:42
0

Because you are returning true (or false) in $.ajax.success event, which is running in a difference thread (not really a tread, but like it) asynchronously. And when you end the main method (as main thread), there is nothing to return. by setting async:false attr in ajax call, you can resolve the problem. The better way is to create a delegate for handling the result.

amiry jd
  • 27,021
  • 30
  • 116
  • 215