0

I have a bug where my code won't exit my routine. I'm using a return statement... but it doesn't seem to be working.
I have the following code inside a click event:

    $.getJSON(      

          url = 'myserver/controller/checkforduplicate',
          parameters,
          function(data)  {
                        if (data=='true') {
                            alert(data);
                            $('#verror').html("A duplicate entry exists");      
                            return false;
                        }
                }
            );  
        console.log($('#myform').serialize() );

When I input data the should be considered a duplicate and trigger this click event, the system doesn't exit but still gets to the console.log statement.

EDIT 1

I've reviewed the answers found at: How do I return the response from an asynchronous call? But from what I'm reading, haven't I already defined a callback function? I thought that's what I was doing with the "function(data) {}" code... In addition to stackoverflow, I've been using:

http://www.tutorialspoint.com/jquery/ajax-jquery-getjson.htm

It seems that in the above example, they are referring to their function(jd) as the callback. According to the above article, the syntax is:

$.getJSON( url, [data], [callback] )

Perhaps I'm still missing something... Thanks for your patience.

Community
  • 1
  • 1
mark li
  • 347
  • 1
  • 7
  • 22
  • 1
    That's ASYNC my friend :D. – tymeJV Jul 23 '13 at 18:10
  • 1
    Yes, `getJSON` takes a callback, but that's not what people are talking about when they say "you need to use a callback". I assume your `getJSON` call is inside of a function, right? (Otherwise, why are you trying to `return false`?) You need your *outer* function -- the one that *uses* `$.getJSON` -- to take a callback. Think of your outer function (which you haven't supplied here) as the `foo` function in [How to return the response from an AJAX call?](http://stackoverflow.com/a/14220323/710446). Search for "`filtered_response`" on that question and you'll see what you should be doing. – apsillers Jul 23 '13 at 20:25
  • apsillers - got it. Yes, getJSON is being called inside of a function. i'll give your suggestion a try. thanks for the clarification – mark li Jul 23 '13 at 20:52

1 Answers1

4

You cannot return from an asynchronous function.

You need to use a callback.

Community
  • 1
  • 1
Naftali
  • 144,921
  • 39
  • 244
  • 303
  • thanks for the article. i understand the concept. but i don't understand the sample code for creating a callback function. I've edited my post to include a sample callback – mark li Jul 23 '13 at 18:59
  • Neal, I was under the impression that my "function(data)" was the callback method. No? – mark li Jul 23 '13 at 19:08
  • I see. i think apsillers answered my question above... i'll give it a try anyways. – mark li Jul 23 '13 at 20:51