GET Method
<script
src="_scripts/jQuery-1.2.6.js"
type="text/javascript"></script>
<script
language="javascript">
$(document).ready(function() {
$("#txtNoOfTicketsByGet").change(function() {
$("#Error1").html("");
var ticketsReq =
$("#txtNoOfTicketsByGet").val();
$.get("GetAvailableTickets.aspx", function(result) {
var
ticketsavailable = parseInt(result);
if (ticketsReq
> ticketsavailable) {
$("#Error1").html("Only " +
ticketsavailable + " tickets are available!");
}
});
});
});
</script>
<div>
<div
id="TicketsByGET">
No of Tickets:<asp:TextBox
ID="txtNoOfTicketsByGet" runat="server"></asp:TextBox>
<div id="Error1"
style="color:Red;"></div>
</div>
</div>
CodeBehind
public partial class GetAvailableTickets :
System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
//Hardcoded no of tickets
available
int NoOfTicketsAvailable =
5;
Response.Write(NoOfTicketsAvailable.ToString());
Response.End();
}
}
In the above code, we are sending GET
request to the page GetAvailableTickets.aspx to get the available number
of tickets. The call-back function in $.get() statement will be executed once
the server execution is complete and displays an error message if the number
of tickets entered is more than the available number of tickets.
In the next section we will implement
the same feature but with post method[$.Post()]. We will also send the entered
number of tickets as a input data in a JSON notation to check the available number of tickets in
server side. Refer the below code,
POST Method
<script
src="_scripts/jQuery-1.2.6.js"
type="text/javascript"></script>
<script
language="javascript">
$(document).ready(function() {
$("#txtNoOfTicketsByPOST").change(function() {
$("#Error2").html("");
var ticketsReq =
$("#txtNoOfTicketsByPOST").val();
$.post("GetAvailableTicketsByPOST.aspx", { TicReq: ticketsReq },
function(result) {
if (result !=
"") {
$("#Error2").html(result);
}
});
});
});
</script>
<div>
<div id="TicketsByPOST
">
No of Tickets:<asp:TextBox ID="
txtNoOfTicketsByPOST" runat="server"></asp:TextBox>
<div id="Error2"
style="color:Red;"></div>
</div>
</div>
GetAvailableTicketsByPOST.aspx.cs
public partial class
GetAvailableTicketsByPOST : System.Web.UI.Page
{
protected void Page_Load(object
sender, EventArgs e)
{
string ticReq =
Request["TicReq"];
int tics =
int.Parse(ticReq);
int NoOfTicketsAvailable =
5;
if (tics >
NoOfTicketsAvailable)
{
Response.Write("Only " +
NoOfTicketsAvailable.ToString()+" are available!");
Response.End();
}
}
}
Thus, we have seen the implementation of
AJAX request through jQuery. Refer the below figure for the output when we enter
more number of tickets than available.
Download the code attached with article
and see it in action!
|