viviosoft Posted July 15, 2012 Share Posted July 15, 2012 Hi guys! Passing values within a function or outside a function has always been a problem for me (to understand). Here's what I need help with. I have the following function that should return a value. Just as an fyi... I'm creating a jQuery mobile application (not that it matters for this problem). So I would like to use the value that is returned in another function but can't seem to get at it. If I alert the value inside the for loop it's fine and I get a value. So I know the value does exist. So somewhere else on the page I'm calling alert(getSaleman()); ... the alert returns undefined? Thanks for any help you can provide me. function getSalesman() { var sId; var salesman; sId = urlParam('sId', window.location.href); AVDB.readTransaction(function (tx) { tx.executeSql("SELECT * FROM stores WHERE id = ?;", [ sId ], function (tx, results) { for (var i = 0; i < results.rows.length; i++) { var row = results.rows.item(i); salesman = row.sSalesman } // for i }) }); return salesman; } Quote Link to comment https://forums.phpfreaks.com/topic/265704-returning-a-value/ Share on other sites More sharing options...
viviosoft Posted July 15, 2012 Author Share Posted July 15, 2012 Well - I guess I should have done a bit more research. It turns out that you have return values on an asynchronous functions. You have to create a callback function. I've done that and this is what I've come up with which works. If there's a better approach please, by all means, reply. The new callback function: function getSaleman(callback) { var sId; sId = urlParam('sId', window.location.href); var salesmanID = AVDB.readTransaction(function (tx) { tx.executeSql('SELECT * FROM stores WHERE id = ? ', [sId], function (tx, results) { var len = results.rows.length; if(len > 0) { var row = results.rows.item(0); var temp = row.sSalesman; callback(salesmanID); } }); }); } How to call this function and return it's value: getSaleman(function(value){ alert(value); }); Quote Link to comment https://forums.phpfreaks.com/topic/265704-returning-a-value/#findComment-1361687 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.