Tuesday, 31 December 2013

Quick Example of calling a web service with JQuery

Quick Example of calling a web service with JQuery where Web Service method and JavaScript/ JQuery script are in same WebForm i.e. in a single aspx and its associated c# file.


I am not going to explain. Just check the code below

Note:- Please download and Import latest JQuery file. Just Google it or go to the link
https://developers.google.com/speed/libraries/devguide
and find & click on JQuery

JavaScript Code

<script src="Your_JQuery_File_Path_Along_With_Extension.JS" type="text/javascript"></script>
//Can be like this<script src="jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
    function search() {
    $.ajax({
        type: "POST",
        url: "Your-Web-Form-Name.aspx/search",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            alert(msg);
        },
        error:function (a,b,c) {
             alert(a+", "+b+", "+c);
        }
    });
    }
    search();
</script>

Note:- Please replace Your-Web-Form-Name.aspx with your web form name with extension .aspx.

C# Code

[System.Web.Services.WebMethod]
public static string search()
{
    return "worked";
}

No comments:

Post a Comment