Types of Ajax in ASP.Net, How to call server side method using javascript


AJAX in ASP.Net

JQuery is a JavaScript library which is going to be popular day by day because of its large number of built-in functions and events which are used to make the light weight web applications with minimum amount of effort and time. The JQuery is simple and easy of use and provide the great compatibility of web programming languages. JQuery goint to be popular because of its provide the simplest and fastest way of using AJAX with web applications. The ASP.Net supports the various ways to use the AJAX like with Ajax.dll, with ScriptManager, with JavaScript and with JQuery.

Ajax with JQuery is the most quickest way to use ajax. In this tutorial i will teach you how to implement these all techniques with Ajax.

Ajax with Ajax.dll:- This technique was introduce in .net framework 1.0 and was depricated in 3.0 because microsoft introduce Ajax controls in the asp.net. This is a technique which was popular in 1.0,2.0 versions of .net framework and you can able to call server side methods into javascript code and pass and retrieve the value from the server side methods.
To do this you need to add the Ajax.dll file into your project like this 
step 1- Download Ajax.dll and save it anywhere into your hard drive.
step 2- right click on your project from solution explorer and click on add reference and browse the Ajax.dll file from your hard drive.
step 3- now go to web.config file and add this line into the <httpHandler> tag.
<add verb="POST,GET" path="ajax/*.ashx" type="Ajax.PageHandlerFactory, Ajax"/>
step 4- now register your class for ajax like this .
     protected void Page_Load(object sender, EventArgs e)
    {
        Ajax.Utility.RegisterTypeForAjax(typeof(Ajax1));
    }


step 5- now create your method which you want to call into javascript like this.

   [Ajax.AjaxMethod()]
    public int sum(int x, int y)
    {
        return x + y;
    }
the [Ajax.AjaxMethod()] is compulsory for every method which you want to call using javascript.

step 7- now design your asp page drag and drop two textboxes and a button.
step 6- now you are ready to call the server side method from javascript.
function sum() {

        var a = document.getElementById("TextBox1").value;
        var b = document.getElementById("TextBox2").value;
      Ajax1.sum(a,b,gresult,gerror);         
        return false;
    }
    function gresult(res) {
            alert(res.value);
        }
        function gerror(er,text,status) {
            alert(er.value);
        }

the gresult is a function which handles the response and the gerror is a function which handles the error.
the gresult and gerror are not compulsory you can rename the name of these two according to your need.
call the javascript's sum function OnClientClick of button.

Ajax with SriptManager:- The script manager is another technique to call the server side methods into javascript. It was introduce in .net framework 3.0. To do this you need to use the System.Web.Services into your project and whenever you want to call the server side method into javascript you need to tell the compiler that the perticular method is of Ajax method like this.
step 1- use the webservices 
using System.Web.Services;

[WebMethod]
public static int sum(int a, int b)
    {
        return a + b;
    }

the static keyword is compulsory for this with methods definition.

step 2- now drag and drop two textboxes and a button into your aspx page.
step3- now write the following code into your javascript block.
function sum() {
            var a = $get("TextBox1").value;
            var b = $get("TextBox2").value;
            PageMethods.sum(a, b, gsuccess, gerror);
            return false;
        }

        function gsuccess(a)
        {
            alert("res="+a);
        }

        function gerror(er) {
            alert("error="+er.get_message());
        }

the $get() is same as the document.getElementById() methods and the gsuccess and gerror are doing same thing as above technique we have discussed.

Ajax with javascript:- This technique is quite simple and more fast then the above methods but it seems lengthy then above methods. If you want to do this you need to create a separate aspx  page which handles your server side code and you can call it from javascript and pass and retrieve values into it like this.

step 1- create an aspx page and write your server side code 

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Ajax1 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int x=Int32.Parse(Request["a"].ToString());

        int b=Int32.Parse(Request["b"].ToString());
        Response.Write((a+b));
      }

}

step 2. Now create your javascript code. The javascript code is divided into three parts first for get browser object, second one is a request block and third one is handling response from the server, now we are discuss on among three in details.
getting browser object:-

function getObj()
{
var http;
if(window.XmlHttpRequest)
    http=new XmlHttpRequest();
else
    http=new ActiveXObject("Microsoft.XMLHTTP");
return http;
}

creating a request block:-

var https=getObj();

function sum()
{
 var a = document.getElementById("TextBox1").value;
 var b = document.getElementById("TextBox2").value;

var url="Ajax1.aspx?a="+a+"&b="+b;
https.open("GET",url);
https.onreadystatechange=HandleResponse;
https.send(null);
}

creating a response handling block:-

function HandleResponse()
{
if(https.readyState==4&&https.status==200)
{
  alert("sum="+https.responseText);
}
}

Ajax with JQuery:- This is the fastest and simplest way to use Ajax with JQuery API. To do this you need to create a server side method into any page of your website and you are able to call that method using JQuery. 

Step 1- Create a Method into any aspx.cs page like this

[System.Web.Services.WebMethod]
    public static int sum(int a, int b)
    {
        return a + b;
    }

Step 2- now drag and drop two textboxes and a button into your aspx page.
Step 2- Now write your JQuery code to call this method like this.

$("#Button1").click(function (e) {

                var a = $("#<%=TextBox1.ClientID%>").val();
                var b = $("#<%=TextBox2.ClientID%>").val();
               
                $.ajax({
                    type: "POST",
                    url: "ajaxwithscript.aspx/sum",
                    data: "{'a':'"+a+"','b':'"+b+"'}",
                    contentType: "application/json",
                    success: function (data) {
                    alert("ans=" + data.d);
                                                           
                     },
                 failure: function (data, b, c) { alert("error=" + b.responseText); }
                });

               return false;                

});


{ 0 comments... read them below or add one }

Post a Comment