0

I have some code like:

function duplicatecheck(value, colname) {
                var invoiceLineId = $('tr[editable="1"]').attr('id');

                var invoiceLine = {
                    InvoiceLineId: invoiceLineId,
                    InvoiceId: invoiceId,
                    ActivityId: value
                };
                $.post('/Invoice/InvoiceLineExistsForThisActivity/', invoiceLine, function (data) {
                    if(data == true) {
                        return[ false, "An invoice line already exists with this activity"]
                    }
                    else {
                        return[ true, ""];
                    }
                });
            }

The problem is that duplicatecheck is supposed to return a value. The value is inside the post callback function. So duplicatecheck runs and doesn't return anything because post is asynchronous and duplicatecheck finishes before the callback has even run.

Is there a way to make duplicatecheck wait until the callback has finished and return what the callback returns.

Am I going about this completely the wrong way and should be doing something else?

AnonyMouse
  • 17,278
  • 24
  • 77
  • 130
  • 1
    yes, you are going about this completely wrong. you should have your callback handling the response – galchen Sep 26 '11 at 01:40
  • You have to use a callback handler. This question has been answered before, take a look: [link](http://stackoverflow.com/questions/5168739/trouble-using-jquery-post-inside-non-jquery-function) – David Morabito Sep 26 '11 at 01:50

2 Answers2

1

If you use jQuery.ajax you have the power to set async to false. That being said, preferably your web application should be structured in such a way that asynchronism is possible.

You should look into callbacks. If you run a function you know might take a while, provide it with a function that it will call when it's done. Useful links:

Understanding callback functions in Javascript
Getting a better understanding of callback functions in JavaScript

Community
  • 1
  • 1
Hubro
  • 52,462
  • 63
  • 210
  • 362
1
  1. I think you go the wrong way, JS is event driven, mostly
  2. The $.POST has a sync/async flag, check here
Itay Moav -Malimovka
  • 50,983
  • 60
  • 187
  • 270