Wait AJAX before proceeding through a separate function

Okay ... at 2am, this is where I draw the line. Help ... before my laptop comes out of the window. :)

I tried using setTimer, callbacks and everything else I can think of (along with a few other Stackoverflow tips, of course). I removed everything, so I leave only the basic code.

What I want to do is call parseRow () and before it saves the entry at the end, I need to grab the related category (via AJAX); however, it breaks right past him, so the category is always "undefined".

function parseRow(row){ var rowArray = row.trim().split(","); var date = rowArray[0]; var checknum = rowArray[1]; var payee = rowArray[2]; var memo = rowArray[3]; var amount = rowArray[4]; //ERROR: blows right past this one and sets the category variable BEFORE ajax returns var category = autoSelectCategory(payee); saveRecord(date, checkNum, payee, memo, category, payment, deposit); } function autoSelectCategory(payee) { var data; $.ajax({ async: false, url: "autoselectcategory", dataType: "json", data: { string: payee }, success: function (returnedData) { data = returnedData; } }); return data; } 
+7
source share
2 answers

AJAX means asynchrony. This means that in your source code saveRecord will be executed before , the client will receive a response from the server (and, depending on the implementation of $.ajax , it may be before the client sends a request to the server).

Also, you seem to misunderstand how functions work in JS. var category = autoSelectCategory(payee); sets the category to the return value autoSelectCategory ; but the autoSelectCategory function in your code returns nothing.

On the other hand, the data return value of your anonymous function can only be used by the $.ajax function (and $.ajax most likely ignores the return value of the success parameter).

Here is the code that should work:

 function parseRow(row){ var rowArray = row.trim().split(","); var date = rowArray[0]; var checknum = rowArray[1]; var payee = rowArray[2]; var memo = rowArray[3]; var amount = rowArray[4]; autoSelectCategory(payee, function (category) { saveRecord(date, checkNum, payee, memo, category, payment, deposit); }); } function autoSelectCategory(payee, callback) { $.ajax({ async: false, url: "autoselectcategory", dataType: "json", data: { string: payee }, success: callback }); } 
+12
source

Do not use the async: false parameter. This is pure evil (blocks all scripts in the browser and even other tabs!), And it is not recommended with jQuery 1.8. You should use callbacks, as it always should have been.

 function parseRow(row) { /* the other code */ autoSelectCategory(payee, function() { saveRecord(date, checkNum, payee, memo, category, payment, deposit); }); } function autoSelectCategory(payee, callback) { // <---- note the additional arg $.ajax({ url: "autoselectcategory", dataType: "json", data: { string: payee }, success: function(res) { /* the other code */ callback(); } }); } 
+9
source

All Articles