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?

2
  • 1
    yes, you are going about this completely wrong. you should have your callback handling the response Commented Sep 26, 2011 at 1:40
  • You have to use a callback handler. This question has been answered before, take a look: link Commented Sep 26, 2011 at 1:50

2 Answers 2

1
  1. I think you go the wrong way, JS is event driven, mostly
  2. The $.POST has a sync/async flag, check here
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.