Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

jquery ajax load aspx page

Suggested Videos
Part 51 - Increase decrease font size using jquery
Part 52 - jquery floating div
Part 53 - jquery ajax load



In this video we will discuss how to load HTML data from the server from an aspx page using load function. This is continuation to Part 53. Please watch Part 53 from jQuery tutorial before proceeding.



When a text box receives focus, the help text associated with that field should be loaded from the server and displayed. When the focus is lost the help text disappears. The help text is stored in the database.
jquery ajax load aspx page

We will be using the jquery ajax load function to achieve this. Here is how this is going to work
1. The ASPX page loads data from the SQL Server database using ADO.NET and C#
2. The HTML page loads HTML data from the ASPX page using jQuery AJAX load function
jquery ajax load html from asp.net page

Step 1 : Create SQL Server table and insert helptext data

Create table tblHelpText
(
     HelpTextKey nvarchar(50) primary key,
     HelpText nvarchar(250)
)
GO

Insert into tblHelpText values
('firstName','Your fisrt name as it appears in passport')
Insert into tblHelpText values
('lastName','Your last name as it appears in passport')
Insert into tblHelpText values
('email','Your email address for communication')
Insert into tblHelpText values
('income','Your annual income')

Step 2 : Create stored procedure that the ASPX page will call to get helptext data from the database

Create procedure spGetHelpTextByKey
@HelpTextKey nvarchar(50)
as
Begin
     Select HelpText from tblHelpText where HelpTextKey=@HelpTextKey
End

Step 3 : Create new asp.net web application project. Name it Demo. 

Step 4 : Include a connection string in the web.config file to your database.
<add name="DBCS"
      connectionString="server=.;database=SampleDB;integrated security=SSPI" />

Step 5 : Add a new WebForm. Name it GetHelpText.aspx. Copy and paste the following HTML in the WebForm.

<%@ Page Language="C#" AutoEventWireup="true"
         CodeBehind="GetHelpText.aspx.cs" Inherits="Demo.GetHelpText" %>
<div id="divResult" runat="server"></div>

Step 6 : Copy and paste the followng code in the code-behind file

using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace Demo
{
    public partial class GetHelpText : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string helpTextKey = Request["HelpTextKey"];
            divResult.InnerText = GetHelpTextByKey(helpTextKey);
        }

        private string GetHelpTextByKey(string key)
        {
            string helpText = string.Empty;

            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spGetHelpTextByKey", con);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlParameter parameter = new SqlParameter("@HelpTextKey", key);
                cmd.Parameters.Add(parameter);
                con.Open();
                helpText = cmd.ExecuteScalar().ToString();
            }

            return helpText;
        }
    }
}

Step 7 : Add an HTML page to the ASP.NET project. Copy and paste the following HTML and jQuery code
<html>
<head>
    <script src="jquery-1.11.2.js"></script>
    <script type="text/javascript">

        $(document).ready(function () {
            var textBoxes = $('input[type="text"]');
            textBoxes.focus(function () {
                var helpDiv = $(this).attr('id');
                $('#' + helpDiv + 'HelpDiv').load('GetHelpText.aspx', { HelpTextKey: helpDiv });
            });

            textBoxes.blur(function () {
                var helpDiv = $(this).attr('id') + 'HelpDiv';
                $('#' + helpDiv).html('');
            });
        });
    </script>
</head>
<body style="font-family:Arial">
    <table>
        <tr>
            <td>First Name</td>
            <td><input id="firstName" type="text" /></td>
            <td><div id="firstNameHelpDiv"></div></td>
        </tr>
        <tr>
            <td>Last Name</td>
            <td><input id="lastName" type="text" /></td>
            <td><div id="lastNameHelpDiv"></div></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><input id="email" type="text" /></td>
            <td><div id="emailHelpDiv"></div></td>
        </tr>
        <tr>
            <td>Income</td>
            <td><input id="income" type="text" /></td>
            <td><div id="incomeHelpDiv"></div></td>
        </tr>
    </table>
</body>
</html>

jQuery tutorial for beginners

7 comments:

  1. Hi,

    What i dont understand here is that you assign the value from database t div in aspx page in codebehind,but then how its reflecting in html page div?

    ReplyDelete
  2. In load function, the first parameter is URL and we are specifying the URL of aspx page.The second parameter is data and supplying key Value by using JSON object.

    ReplyDelete
  3. creating table throws this error.

    "Only one statement is allowed per batch. A batch separator, such as 'GO', might be required between statements."

    ReplyDelete
  4. I am Browsing Same Example in IE and i attached debugger in html page .
    "its showing error JavaScript critical error at line 1, column 1 in about:jquery-2.2.2.js

    SCRIPT1002: Syntax error"
    mean while its working in chrome. could u give me explanation ???

    ReplyDelete
  5. My Observation is gien below
    As per the code given in the link

    http://csharp-video-tutorials.blogspot.in/2015/05/jquery-ajax-load-aspx-page.html

    It will work sucessfully.
    protected void Page_Load(object sender, EventArgs e)
    {
    string helpTextKey = Request["HelpTextKey"];
    divResult.InnerText = GetHelpTextByKey(helpTextKey);
    }




    But in vedio it is telling to use

    protected void Page_Load(object sender, EventArgs e)
    {
    divResult.InnerText = GetHelpTextByKey("HelpTextKey");
    }


    in this case Object reference not set to an instance of an object will occur since HelpTextKey is getting assigned as null, but in first case since it is
    taking from Request , getting assigned to correct value.

    ReplyDelete
  6. If you can build in visual basics
    Imports System.Web.Services
    Imports System.Web.Services.Protocols
    Imports System.ComponentModel
    Imports System.Data.SqlClient
    Imports System.Web.Script.Services
    Public Class HelpDiv
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Dim HelpTextKey As String = Request("HelpTextKey")
    resultdiv.InnerHtml = GetHelpTextByKey(HelpTextKey)
    End Sub
    Dim dbconn As New SqlConnection(ConfigurationSettings.AppSettings("Emp_Connection"))
    Private Function GetHelpTextByKey(ByVal key As String) As String
    Dim helptext As String = String.Empty
    dbconn.Open()
    Dim cmd As SqlCommand = New SqlCommand("spGetHelpTextByKey", dbconn)
    cmd.CommandType = CommandType.StoredProcedure
    Dim parameter As SqlParameter = New SqlParameter("@HelpTextKey", key)
    cmd.Parameters.Add(parameter)
    helptext = cmd.ExecuteScalar().ToString()
    Return helptext
    End Function
    End Class

    ReplyDelete
  7. I am getting null value here
    string helpTextKey = Request["HelpTextKey"];

    But Ajax send data correctly. "helpTextKey" receiving null value in

    ReplyDelete

It would be great if you can help share these free resources