Tutorial :Why does this JQuery call to asp.net pagemethod load the whole page?



Question:

Here is a snippet of my html:

<input id="btnGetDate" type="submit" value="Get Date" />      <div id="Result"></div>    <script type="text/javascript">        $(document).ready(function() {            $("#btnGetDate").click(function() {              $.ajax({                  type: "POST",                  url: "Date.aspx/GetDate",                  data: "{}",                  contentType: "application/json; charset=utf-8",                  dataType: "json",                  success: function(msg) {                      $("#Result").text(msg.d);                  }              });          });      });    </script>  

My Page Method id defined as follows:

    [System.Web.Services.WebMethod]      public static string GetDate()      {          return DateTime.Now.ToString();      }  

When I click the Get Date button, I saw the date flash on the screen for a second, but since the whole page is loading, it disappears and when I view it in firebug, I see it is doing the POST, but quickly disappearing. Any ideas on how to resolve this?


Solution:1

Try returning false from your $("#btnGetDate").click() event handler:

    $("#btnGetDate").click(function() {          $.ajax({              type: "POST",              url: "Date.aspx/GetDate",              data: "{}",              contentType: "application/json; charset=utf-8",              dataType: "json",              success: function(msg) {                  $("#Result").text(msg.d);              }          });          return false;      });  


Solution:2

karim79's solution will do the job in Internet Explorer - but to make sure that it works in Firefox and other browsers as well, you probably want to add an input argument to the click handler that will take the click event, and stop the event.

$("#btnGetDate").click(function(ev) {      ev.stopPropagation();      $.ajax({          type: "POST",          url: "Date.aspx/GetDate",          data: "{}",          contentType: "application/json; charset=utf-8",          dataType: "json",          success: function(msg) {              $("#Result").text(msg.d);          }      });      return false;  });  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »