Jens Törnell
Jens Törnell

Reputation: 24748

jQuery callback from another function

I have a function that looks like this. It works.

Problem

This function myFunction is called by many other functions and depending on which one it should do something different on success.

Question

How is this solved? Some kind of callback? or do I have to send an extra parameter for the function to know?

Code

function myfunction()
{
    var value = "myvalue";
    var post_url = "ajax.php";

    $.post(  
        post_url,
        {
             value: value,
        },
            function(responseText){  
                var json = JSON.parse(responseText);
                if(json.success)
                {
                    console.log('success'); 
                }
            }
        );
    }
}

Upvotes: 0

Views: 144

Answers (3)

ATOzTOA
ATOzTOA

Reputation: 35950

Yes, you will either need to have a parameter to identify the caller, like

function myfunction(caller) {
    if (caller == "Foo") {
        // some code
    }
}

myFunction("Foo");

Or use a global variable

function myFunction() {
    if (caller == "Foo") {
        // some code
    }
}

caller = "Foo";
myFunction();

Upvotes: 0

Ulises
Ulises

Reputation: 13419

Add a function parameter and call it on success:

function myfunction(callback)
{
    var value = "myvalue";
    var post_url = "ajax.php";

    $.post(  
        post_url,
        {
             value: value,
        },
            function(responseText){  
                var json = JSON.parse(responseText);
                if(json.success)
                {
                    console.log('success'); 
                    //call callback 
                    callback();

                }
            }
        );
    }
}

Upvotes: 2

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

Have myfunction accept a callback:

function myfunction(callback)
{
    var value = "myvalue";
    var post_url = "ajax.php";

    $.post(post_url, { value: value }, callback);
}

And then you can pass in any function to be executed when the POST comes back:

myfunction(function(responseText){  
    var json = JSON.parse(responseText);
    if (json.success)
    {
        console.log('success'); 
    }
});

Upvotes: 1

Related Questions