Call Web Service using jquery and json

Akiii
Posted by Akiii under jQuery category on | Points: 40 | Views : 1642
First create a default page. Create and button and a textbox.


Enter Name: <input type="text" id="txtName" />
<asp:Button ID="btnGetMsg" runat="server" Text="Click Me" OnClientClick="DisplayMessageCall();return false;" /><br />
<asp:Label ID="lblOutput" runat="server" Text=""></asp:Label>


Add an asmx file that is the web service file. When you add the asmx file, then it will automatically add app_code folder and in it a .cs file will be added.
Open the .cs file now and add this code :

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

public WebService () {

//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public string HelloWorld(string name)
{
return "Welcome " + name;
}

}


Now add a jquery script reference and add the follwing code to call a webservice file from jquery.

<script type="text/javascript" language="Javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type = "text/javascript">
function DisplayMessageCall() {
var pageUrl = '<%=ResolveUrl("~/WebService/WebService.asmx")%>'

$.ajax({
type: "POST",
url: pageUrl + "/HelloWorld",
data: "{'name':'" + $("#txtName").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccessCall,
error: OnErrorCall
});
}

function OnSuccessCall(response) {
$('#<%=lblOutput.ClientID%>').html(response.d);
}

function OnErrorCall(response) {
alert(response.status + " " + response.statusText);
}
</script>


Now, build the project and run the default page. In that you will see a textbox and button. Write anything in the textbox and click the button. You will see the output !


Thanks and Regards
Akiii

Comments or Responses

Login to post response