Jump to content

returning a value


viviosoft

Recommended Posts

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;

}

Link to comment
Share on other sites

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);
        });

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.