I am learning JQuery and today I did a small program with JQuery Ajax
I am using JQuery 1.6.1
The application is very simple. It has a TextBox, a Button and a Label control. Once the user enters something in the textbox control and click on the Button control, then the request will go to the server and it will respond to it which will be displayed in the Label control
For this, I have two pages viz, Default.aspx and ServerResponse.aspx pages
The Default.aspx is as under
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Test JQuery - Ajax</title>
<script type="text/javascript" src="JQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function() {
$.ajax(
{
url: "ServerResponse.aspx",
data: "Name =" + $("#txtName").val(),
success: function(data) {
$('#lblServerResponse').html(data);
},
error: function() { alert(arguments[2]); }
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<table>
<tr>
<td>
Enter your name:
</td>
<td>
<asp:TextBox ID="txtName" runat="server" ></asp:TextBox>
</td>
<td>
<input type="button" id="btnSubmit" value="Click Me" />
</td>
</tr>
<tr>
<td>
Server Response:
</td>
<td>
<asp:Label ID="lblServerResponse" runat="server"></asp:Label>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
On the Submit button click event, I am calling the Jquery’s ajax method where I have mentioned the page where the server response will come in (ServerResponse.aspx), how the query string (Name here) will be formed and from where (textbox control) the client data will be taken. Once, the server is giving the proper response, then it will be displayed in the label control else an error message will be thrown.
Now let us look into the ServerResponse.aspx.cs file
using System;
public partial class ServerResponse : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["Name"] != null)
{
Response.Clear();
Response.ContentType = "text/plain";
Response.Write("Server Said: Hello, " + Request.QueryString["Name"]);
Response.End();
}
}
}
As can be make out that, the server first checks if the query string is available or not and if available it response to the
client in plain text.
Hence, if the user types the name as Beyond Relational in the textbox and clicks on the button, the output will be
Server Said: Hello, Beyond Relational
Hope this will help for beginners in Jquery like me