Saturday, December 8, 2012

Simple Ajax Jquery Call example in ASP.NET

Read the post Simple Ajax Call example in ASP.NET to get an idea about making an asynchronous ajax call to the server. Below code will make an asynchronous call to the server using ajax and Jquery.

<html xmlns="">

<head runat="server">
<script src="jquery-1.8.3.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnchange").click(function () {
                $.get("GetData.aspx", function (response) {
                   document.getElementById("myDiv").innerHTML = response;
    <form id="form1" runat="server">
   <div id="myDiv"><h2>Let AJAX change this text</h2></div>
  <button type="button" id="btnchange">Change Content</button>

$.get() or $.ajax()
Uses the XMLHttpRequest from JavaScript behind the scenes.

Create a new page called GetData.aspx and add the below code in page load event.


 protected void Page_Load(object sender, EventArgs e)
        Response.Expires = -1;
        //required to keep the page from being cached on the client's browser
        Response.ContentType = "text/plain";

Response.Expires = -1;
Will keep the page from being cached in the browser.

The response of a "GET" request is cached by default, so to make sure that our example brings back the current time each time it is clicked, this line is crucial. The next few lines change the content type to plain text, get the current time, and writes the output:

Response.ContentType = "text/plain"; 

No comments:
Write comments
Recommended Posts × +