Search code examples
androidweb-servicescordovavisual-studio-2015apache-cordova

calling a web service in cordova in Visual studio 2015


I am developing an android app using apache cordova tools in visual studio 2015. I want to call a web service from my index page in cordova app, but I somehow can't achieve it.

Here is the HTML

 <div ><input type="button" id="callwebmethod" name="submit" /> <br /> </div>

Here is the JS function

 <script type="text/javascript">
    $('#callwebmethod').click(function () {
        var params = "{'msg':'From Client'}";
        $.ajax({
            type: "POST",
            url: "http://mysite/index.aspx/GetEmployees",
            data: params,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (result) { alert(result.d); }

        });


    })


</script>

Here is the web method

 [WebMethod]
    public static string GetEmployees()
    {
        return "Hello World";
    }

Solution

  • Your var params have to be simular to the Parameters of the WebMethod. Just leave them empty and try it again. They have to be exactly the same.

    If you whant to use web methods with parametes here is a working example:

        $.ajax({
            url: "http://systemservice/systemservice.asmx/App_Test",
            data: "{ par1: '" + xxx + "', par2: '" + xxx + "'}",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                if (data.d) {
                     //Do something
                 }
            },
            error: function (xhr) {
                alert("An error occured: " + xhr.status + " " + xhr.statusText);
            }
        })
    
    
        [WebMethod]
        public string App_Test(string par1, string par2) {
            return "Hello";
        }
    

    With the shown error function you can also find out what is going wrong.

    To do it without the paremeters you just have to leave them empty.

        data: "{}"
    
    
        [WebMethod]
        public string App_Test() {
            return "Hello";
        }