Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Ajax Call in ASP.NET

    • 0
    • 1
    • 0
    • 0
    • 1
    • 0
    • 0
    • 0
    • 1.04k
    Comment on it

    Ajax Call (Asynchronous JavaScript and XML Call) In Asp.Net

    1. Ajax Call is used to refresh portion of a webpage without reloading whole page.
    2. Ajax Calls are used to create fast web pages as they refreshes only a portion of web page instead of reloading a whole page.

    Example of Ajax Call in ASP.NET-:

    Step 1-: Create an ASP.NET web page and name it as AjaxCallExample.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AjaxCallExample.aspx.cs" Inherits="AjaxCall.AjaxCallExample" %>
    
    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head runat="server">
    <title></title>
    <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script> 
    <script type="text/javascript">
    
    function GetTime() {       
    try
    {
    $.ajax({
    
    type: "POST",
    url: "AjaxCallExample.aspx/GetTime", 
    data: '{name:"' + $("[id$='txtName']").val() + '"}',                 
    //Or for data you may use               
    data: '{name:"' + $("#<%=txtName.ClientID%>").val() + '"}',
    
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {                  
    
    $("#divForAjaxCallResponse").html(response.d);
    return false;
    
    },
    failure: function (response) {
    alert("some error occourred...");
    }
    });
    
    
    $("form").submit(function (e) {
    e.preventDefault();
    });
    }
    catch(e)
    {
    alert(e.message);
    } 
    }
    </script>
    </head>
    <body>    
    <form id="form1" runat="server" method="post">
    <div>
    
    Enter Name`<asp:TextBox ID="txtName" runat="server" />`
    
    <asp:Button ID="btnGetTime" runat="server" OnClientClick="return  GetTime();" Text="GetTime"     OnClick="btnGetTime&#95;Click" style="height: 26px" />
    
    <div id="divForAjaxCallResponse"></div>
    
    </div>
    </form>  
    </body>
    </html>
    

    Explanation

     <script src="scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
    

    Under head section we have to include script for allowing Jquery's syntax.

    <script type="text/javascript">
    

    Under script tag we have defined a javascript function GetTime() to implement ajax call. Inside this function there is a ajaxcall to funtion of codebehind.

    AjaxCall

    $.ajax({
    type: "POST",
    url: "AjaxCallExample.aspx/GetTime", 
    data: '{name:"' + $("[id$='txtName']").val() + '"}',   
    //Or for data you may use               
    // data: '{name:"' + $("#<%=txtName.ClientID%>").val() + '"}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (response) {                  
    $("#divForAjaxCallResponse").html(response.d);
    return false;
    },
    failure: function (response) {
    alert("some error occourred...");
    }
    });
    

    ATTRIBUTES OF AJAX CALL

    type: "POST" 
    

    Attribute type of ajax call defines the type of ajax call. It can be either Post or Get.

    url: "AjaxCallExample.aspx/GetTime" 
    

    Attribute "url" of ajax call defines the name of Web Method to which we have to send data as parameter. Here, we have to send data to GetTime method of code behind of AjaxCallExample.aspx page so, syntax is-: AjaxCallExample.aspx/GetTime.

    `data: '{name:"' + $("[id$='txtName']").val()  + '"}'` 
    

    Attribute "data" defines the data which we have to send to defined url. Here, we have send the name entered in a textbox as string to defined url(WebMethod) so we can use the value of textbox in Web Method and can manipulate accordingly.

    $("#<%=txtName.ClientID%>").val() - To get the value entered in the textbox.
    $("[id$='txtName']").val() - To get the value entered in the textbox.
    

    Note-: Please use same name for parameter in "data" field and parameter in Web Method.

    Example

     data: '{name:"' + $("#<%=txtName.ClientID%>").val() + '"}'
    Or you may use - data: '{name:"' + $("[id$='txtName']").val() + '"}',
    
    [WebMethod]
    public static string GetTime(string name)
    {
    return "Hello " + name + Environment.NewLine + "Current Time is" +DateTime.Now.ToString();            
    }
    
    `contentType: "application/json; charset=utf-8" 
    

    Attribute "contentType"` is the header for your request & utf-8 defines the encoding.

    dataType: "json"
    

    Attribute "datatype" defines the type of data here we are sending data as "json" object. Here, we can also use text as data type. But when we have to send multiple values we have to wrap values in object and send it as json object.

    success: function (response) {             
    $("#divForAjaxCallResponse").html(response.d);
    return false;                       
    }
    

    If ajax call is successful then we will be inside on success function and parameter "response" contains the result returned from the Web Method.

    failure: function (response) {
    alert("some error occurred...");
    } 
    

    If ajax call fails then message inside alert will be prompted.

    On clicking button it will make a call to method called from "OnClientClick" attribute of button. Here, javascript's GetTime() function will be called which in turn calls GetTime() function of the code behind file.

    This is Code Behind file "AjaxCallExample.aspx.cs"

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.Services;
    
    namespace AjaxCall
    {
    public partial class AjaxCallExample : System.Web.UI.Page
    {
    protected void PageLoad(object sender, EventArgs e)
    {             
    }
    [WebMethod]        
    public static string GetTime(string name)
    {
    
       return "Hello " + name + Environment.NewLine + "Current Time is" + DateTime.Now.ToString();
    
    }        
    }
    }
    

    [WebMethod] is written over GetTime(string name) to indicate it as a web method and differentiating it from other method used for operations.

    Ajax call from function defined in javascript will take the value(data) passed from ajax call to the parameter name and we can use value accordingly. Here, we have concatenated the name with hello and current time of system". Web Method must be declared as static so as to call function without creating an instance.

    Key Note -
    If your script is in separate "js" file instead of same file then you must use-:
    data: '{name:"' + $("[id$='txtName']").val()  + '"}'
    
    data: '{name:"' + $("#<%=txtName.ClientID%>").val() + '"}'
    This will work only if your textbox  and script are on same document/page.
    

 1 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: