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
  • 18,108
  • 26
  • 79
  • 131
  • 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
  • 56,214
  • 69
  • 228
  • 381
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
  • 52,579
  • 61
  • 190
  • 278