jQuery AJAX Introduction

This article provides a quick overview of how to use jQuery with Ajax in ASP. Net. We often see in a project that we do not want to reload the page. For example when you select an item from a DropDownList or other control on the same page then that can cause a loss of data. This article will be very helpful for those who are looking for a solution for that type of problem. You can do it many ways such as using Generic Handlers, page methods and using a web service.

Ajax

The Ajax is used to update the part of the web page without reloading the page. For example, if you create a search functionality in your website like Google Searching. When you enter text into the Search TextBox then without reloading the page you see the related text. You can do it easily using Ajax Methods.

Other examples of applications using AJAX are Gmail, Youtube and Facebook tabs.

jQuery with Ajax

All jQuery AJAX methods use the ajax() method. The ajax() method performs an AJAX (Asynchronous HTTP) request.

Syntax
 

$.ajax({ Parameter1, parameter2..........})

 

or
 

$.ajax({

    type: ,

    contentType: ,

    url:, data:,   

    async:,......

});

 

The following is the description of some important parameters used by the "$.ajax" method:

 

Type: The default value of type is GET. A string defining the HTTP method to use for the request (GET or POST).

  • GET: Requests data from a specified resource
  • POST: Submits data to be processed to a specified resource

ContentType: When sending data to the server, use this content type. The default is "application/x-www-form-urlencoded;

 

URL: A string containing the URL to which the request is sent. The default is the current page.

 

Data: Data defines the data to be sent to the server.

 

async: The default is true. A Boolean value indicating whether the request should be handled asynchronously or not.

 

Success: A callback function that is executed if the request succeeds.

Now, let's see how to do that.

Example 1

My database table

CREATE TABLE [dbo].[Slider_Table](

      [Id] [int] IDENTITY(1,1) NOT NULL,

      [Title] [varchar](100) NULL,

      [Description] [varchar](200) NULL,

      [ImageName] [varchar](100) NULL,

      [IsActive] [bit] NULL,

 CONSTRAINT [PK_Slider_Table] PRIMARY KEY CLUSTERED

 (

      [Id] ASC

)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]

) ON [PRIMARY]

 

My table structure looks like:

Table 

Stored Procedure for insert and Update

You now need to create a Stored Procedure in a SQL Server Database for inserting records into the table. Later in the article we use it to update records in the database table.

Create procedure [dbo].[SliderInsertImage1]

(

@Id int,

@Title varchar(100),

@Description varchar(200),

@ImageName varchar(100),

@IsActive bit

)

AS

begin

insert into Slider_Table values(@Title, @Description, @ImageName, @IsActive)

end


The back-end database work is now done. Now again move to the front-end to make a connection with the database. We store only the name of the image in the database table, the column called ImageName.

Now, add the following code to the .cs file.

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;

using System.IO;

using System.Data;

using System.Data.SqlClient;

 

public partial class Insert : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

    } 

    [WebMethod]

    public static void InsertMethod(string title, string description, string image_name, bool is_active)

    {              

        int ID=0;

        SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");

        con.Open();

        SqlCommand cmd = new SqlCommand("SliderInsertImage1", con);

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@Id", ID);

        cmd.Parameters.AddWithValue("@Title", title);

        cmd.Parameters.AddWithValue("@Description", description);

        cmd.Parameters.AddWithValue("@ImageName", image_name);

        cmd.Parameters.AddWithValue("@IsActive", is_active);      

        cmd.ExecuteNonQuery();             

        con.Close();       

    }  

}
 

So you can drag and drop controls onto the form. The form has the following code:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Insert.aspx.cs" Inherits="Insert" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title></title>

    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    <style type="text/css">

        .style1

        {

            color: #FFFFFF;

        }

    </style>

    <script type="text/javascript">

        $(document).ready(function () {

            $('#Button1').click(function () {

                debugger;

                var Title = $('#TextBox1').val();

                var Description = $('#TextBox2').val();

                var UploadImage = $('#FileUpload1').val();

                var Isactive = $('#CheckBox1').attr('checked');

                $.ajax({

                    type: 'POST',

                    contentType: "application/json; charset=utf-8",

                    url: '<%=ResolveUrl("~/Insert.aspx/InsertMethod") %>',

                    data: JSON.stringify({title: Title, description: Description, image_name: UploadImage, is_active: Isactive }),

                    success: function (response) {

                    alert("Record Has been Saved in Database. Status code: " + response);

                    }

                });

            });

        });       

    </script>

</head>

<body style="color: #FF66FF; background-color: #99FFCC">

    <form id="form1" runat="server">

    <div style="color: #FF33CC; background-color: #00CCFF">

        &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

        <span class="style1">Title: </span>

        <asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static"></asp:TextBox>

        <br class="style1" />

        <br class="style1" />

        <span class="style1">&nbsp;&nbsp; Description: </span>

        <asp:TextBox ID="TextBox2" runat="server" ClientIDMode="Static"></asp:TextBox>

        <br class="style1" />

        <br class="style1" />

        <span class="style1">Upload Image: </span>

        <asp:FileUpload ID="FileUpload1" runat="server" ClientIDMode="Static" />

        <br class="style1" />

        <br class="style1" />

        <span class="style1">IsActive: </span>

        <asp:CheckBox ID="CheckBox1" runat="server" Style="color: #FFFFFF" ClientIDMode="Static" />

        <br class="style1" />

        <br />

        <input id="Button1" type="button" value="Submit" />

        <asp:Label ID="Label1" runat="server" Text="Label" Style="color: #FFFFFF"></asp:Label>

    </div>   

    </form>

</body>

</html>

<style>

 

Now run the application and test it.

 

run the application

 

Now enter the title, description, Imagename and ischecked.

 

Fill the form

 

Now check it in the database table.

 

Database Table
 

Similarly, you can upload more images onto the server and save the name in the database table.


Example 2

 

In the example1 you have inserted a value into the database table. Now in example2 you will see how to bind a DropDownList with an ImageName. Suppose you want to update the inserted data from the front end or ASP.Net application. To do that you need a table name. Depending on the table name you can update the table data. 

 

Now, you need to create a Stored Procedure in the SQL Server Database to select the image name with id.
 

USE [PersionalSite]

GO

/****** Object:  StoredProcedure [dbo].[GetImageID]    Script Date: 12/13/2013 16:45:25 ******/

SET ANSI_NULLS ON

GO

SET QUOTED_IDENTIFIER ON

GO

Create procedure [dbo].[GetImageID]

AS

begin

select Id, ImageName  from Slider_Table

end

Now again move to the front end to make a connection with the database. That means we need a DropDownList control to show the image name. So you can drag and drop a DropDownList control onto the form. The following example shows the use of the above parameter that is used by "$.ajax" method. The form has the following code:

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="BindDropDownList.aspx.cs"

    Inherits="BindDropDownList" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

    <title></title>

    <style type="text/css">

        .style1

        {

            color: #FFFFFF;

        }

    </style>

    <script type="text/javascript">

        $(document).ready(function () {

            Getimageid();

        });

        function Getimageid() {

            var strMethod = "SAVE";

            var StrUrl = 'Handler.ashx?StrMethod=' + strMethod;

            $.ajax({

                type: "POST",

                contentType: "application/json; charset=utf-8",

                url: StrUrl,

                dataType: "json",

                async: false,

                success: function (response) {

                    debugger;

                    $.each(response, function (key, value) {

                        $("#DropDownList1").append($("<option></option>").val(value.Id).html(value.ImageName));

                    });

                }

            });

        }

    </script>

</head>

<body style="color: #FF66FF; background-color: #99FFCC">

    <form id="form1" runat="server">

    <div style="color: #FF33CC; background-color: #00CCFF">

        <span class="style1">Select Image:</span>

        <asp:DropDownList ID="DropDownList1" runat="server" Height="22px" Width="140px" AutoPostBack="True">

        </asp:DropDownList>

    </div>

    </form>

</body>

</html>

 

Now, add the following code to the .cs file. Now add a handler to your application.


Add handler in application

 

Now add the following code with the handler.ashx page.

 

<%@ WebHandler Language="C#" Class="Handler" %>

 

using System;

using System.Web;

using System.Data.SqlClient;

using System.Web.Services;

using System.Data;

 

public class Handler : IHttpHandler

{

 

    public void ProcessRequest(HttpContext context)

    {

        String Response = "";

        switch (HttpContext.Current.Request.QueryString["StrMethod"].ToUpper())

        {

            case "SAVE":

                Response = GetImagename();

                break;

            default:

                break;

        }

        HttpContext.Current.Response.Write(Response);

    }

    public bool IsReusable

    {

        get

        {

            return false;

        }

    }

    private string GetImagename()

    {

        SqlConnection con = new SqlConnection("data source=.;uid=sa; pwd=Micr0s0ft;database=PersionalSite;");

        con.Open();

        SqlCommand cmd = new SqlCommand("GetImageID", con);

        cmd.CommandType = CommandType.StoredProcedure;

        DataTable dt = new DataTable();

        SqlDataAdapter sdp = new SqlDataAdapter(cmd);

        sdp.Fill(dt);

        return Newtonsoft.Json.JsonConvert.SerializeObject(dt);

    }

}

Now run the application and test it.

 

/Bind DropDownList

Up Next
    Ebook Download
    View all
    Learn
    View all