How to call function/method in code behind file from .js file?

I have a Ajax method which check some condition, if the condition fails, then i'm showing a message through alert box. But i need to call function on the aspx page to do some other part.

My Sample Code:

function myWebService(param1, param2, param3) {
    $.ajax({
        type: "POST",
        url: "/WebServices/WebServiceMethod",
        data: JSON.stringify({ param1: param1, param2: param2, param3: param3 }),
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        async: true,
        success: function (msg) {
            if (msg.d) {
                var obj = function callbackfunction() {
                    myWebService(param1, param2, param3);
                }

                window.setTimeout(obj, 10000);
            }
        else {
                    alert("WebMethod checked the condition and it was failed.");
                  // I need to call method in code behind file from here. 
                }
            }
        }

        },
        error: function (xhr, ajaxOptions, thrownError) {
            alert("error");
        }
    });
}

I tried to implement through another WebMethod and Ajax Call, but the problem is i'm calling above myWebService method from 5 different pages and i need to call code-behind function for all the pages in else block.(all aspx pages has the function with SAME name, but the inside code is differs from each page). I don't know how to set-up URL in this case.

is there any preferable way to call method in code-behind file from the above function ???

Answers 1

  • You can use System.Web.Services.WebMethod to allow jQuery to call server side ASP.NET methods (without the use of PostBack). This article has a good step-through guide.

    Basically you need to add an attribute to your static code-behind method:

    [WebMethod]
    public static String MyMethod()
    {
        return "My Method from code-behind"
    }
    

    And in you javascript:

    function myWebService(param1, param2, param3) {
        $.ajax({
            type: "POST",
            url: "Default.aspx/MyMethod", // will make AJAX call to your code-behind code
            // rest of you code...
        });
    }
    

Related Articles