0

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

3 Answers 3

2

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

                }
            }
        );
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

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.