Ajax is not an Technology in itself. It is a term used for representing the technique used for updating the webpage content asynchronously without affecting existing content of the webpage.
Ajax was made popular by Google by using it in the Google Suggest.
So, basically below steps are involved in using ajax for webdevelopment.
- Creating client side code which will call a javascript function on some events such as onChange.
- Creating a XMLHttpRequest which will be used for sending request to web server from javascript itself and used for receiving response from the webserver.
- A place such as div in the client side code for placing the server response got from the ajax call.
We will see the above steps in detail using below sample code.
Consider below HTML code which will be placed within a Form.
|
The above code will call a javascript function showUser() when changing the drop-down list value in the Select tag.
The selected value (i-e name in this example) will be passed as argument to the showUser.
The showUser javascript function will look like below mentioned code.
function showUser(str)
{
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url="getuser.php";
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("POST",url,true);
xmlHttp.send(null);
}
This function creates xmlHttp object by calling a function GetXmlHttpObject()
You can refer the GetXmlHttpObject() below.
function GetXmlHttpObject()
{
var xmlHttp=null;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}The url to be sent as server request is created by specifying the server-side webpage (e.g getuser.php), the function argument "name", and a random number to avoid cache problem.
A function stateChanged is called on onreadystatechange event for getting the response from the webserver for the request of this created url.
You can refer the sample state Changed function below.
Find below the sample server side code (e.g getuser.php) which will be used for sending response according to the value selected in the drop-down list.
<?php
$link=project1_db_connect1();
//for connecting database.
function project1_db_connect1()
{
$link=@mysql_connect("localhost","root","") or exit ();
mysql_select_db ("my_db1") or exit ();
return $link;
}
?>
<table border="1" width="100%">
<tr>
<td>First name</td>
<td>last name</td>
<td>age</td>
</tr>
<?php
$q=$_GET["q"];
$sqluser="select * from persons where id=".$q;
$result=mysql_query($sqluser);
while($userrow=mysql_fetch_assoc($result))
{
$firstname=$userrow['FirstName'];
$lastname=$userrow['LastName'];
$age=$userrow['Age'];
?>
<tr>
<td><?php echo $firstname;?></td>
<td><?php echo $lastname;?></td>
<td><?php echo $age;?></td>
</tr>
<?php
}
?>
</table>The above code is receiving the selected drop-down value as "q" querystring parameter in the url. sql query will be used for fetching details such as firstname, lastname age for the corresponding "q" value.The xmlhttp object is receiving the output of this php page.
If you have better solution, just tell me !
AJAX Login System - AJAX Script
This is an example of a login system that does not require page refreshes, but is still very secure. Valid usernames and passwords for this demo are user1/pass1 and user2/pass2. Try these, and also incorrect passwords to see the results.
Please note that this is not a functional form, your input will not go anywhere.It is solely for demonstrating an XMLHttpRequest login system in javascript.
AdvantagesUser does not need to refresh the page to login.
User is notified instantly on incorrect username/password combination.
Overall user experience is more seamless.
Password is not sent in plain text ever (more secure than traditional system).
Javascript convenience with server-side security (uses PHP/MySQL).
Uses one-time use random seed to hash the password before sending (making interceptions useless).
DisadvantagesSystem is more prone to brute force attacks.
Can be minimized by adding a delay after a certain number of attempts per username or per client.
User may expect a login button.
One could still be added without reloading the page.
Older versions of Safari cannot disable a password field.
This code uses the MD5 encryption algorithm, which has since been proven to be less secure than previously thought. If you use this code, I strongly recommend you switch to a more secure encryption algorithm, such as SHA-1. For sites were security is not crucial, MD5 should suffice.
Source Download
If you have better solution, just tell me !
User validation across pages using session after login in ASP.NET using C sharp
In this example i m showing how to validate a user across different pages whether user is logged in or not using session variables in Global.asax through Session_Start event and Application_OnPostRequestHandlerExecute event which checks for the login validation which occurs when ant asp.net event handler finish execution
Here is my login page , i've used hard coded values to login.
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Login.aspx.cs" Inherits="_Default" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div style="text-align:left" >
<table width="40%" style="text-align: center">
<tr><td style="width: 20%">
<asp:Label ID="lblUserName"
runat="server" Text="Enter UserName:">
</asp:Label></td>
<td style="width: 20%">
<asp:TextBox ID="txtUserName"
runat="server">
</asp:TextBox></td>
</tr>
<tr>
<td style="width: 20%">
<asp:Label ID="lblPassword" runat="server"
Text="Enter Password:">
</asp:Label></td>
<td style="width: 20%" >
<asp:TextBox ID="txtPassword" runat="server"
TextMode="Password">
</asp:TextBox></td>
</tr><tr><td colspan="2" align="right">
<asp:Button ID="btnLogin" runat="server"
Text="Sign in" OnClick="btnLogin_Click" />
</td></tr>
</table>
<asp:Label ID="Label1" runat="server"
Text="Label">
</asp:Label><br />
</div>
</form>
</body>
</html>
After checking the username and password i m creating a new Session variable and setting the flag kindaa value in it , which is "Yes" in this example, this session value will be checked when ever user go to other pages and if it's null than user in not logged in.
protected void btnLogin_Click(object sender, EventArgs e)
{
if (txtUserName.Text == "amit" && txtPassword.Text == "amit")
{
Session["Authenticate"] = "Yes";
Response.Redirect("Default2.aspx");
}
else
Label1.Text = " login failed";
}In Global.asax, in Session_Start event i m assigning null value to the session variable created at the time of Login and than calling the method to check the login, same is in Application_OnPostRequestHandlerExecute event as well.
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["Authenticate"] = "";
CheckLogin();
}void Application_OnPostRequestHandlerExecute()
{
CheckLogin();
}
void CheckLogin()
{
string Url = Request.RawUrl;
int count = Url.Length - 10 ;
string TestUrl = Url.Substring(count);
string SessionData = Session["Authenticate"].ToString();
if (SessionData == "" && TestUrl != "Login.aspx")
{
Response.Redirect("~/Login.aspx");
}
}If you have better solution, just tell me !ASP.NET Ajax CalendarExtender and Validation
ASP.NET Ajax toolkit has a CalendarExtender control which is very cool as you can associate the CalendarExtender to a a TextBox and also to a Button/ImageButton so that you can popup the calendar.
Below is the code to get started with CalendarExtender:
<asp:TextBox ID="TextBox1" runat="server"width="200pt" /><asp:ImageButton ID="btnCalenderPopup"
Width="16" Height="16" runat="server"
ImageUrl="~/images/calender.bmp" CausesValidation="False" />
<ajaxToolkit:CalendarExtender
ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1"
PopupButtonID="btnCalenderPopup"
Format="dd/MM/yyyy" />and,
Wait! What’s that grayed text in the textbox that says – Enter the Date of Birth (dd/mm/yyyy)
Certainly that’s not the part of CalendarExtender, but part of ASP.NET Ajax Toolkit. We can use the TextBoxWatermarkExtender which can display watermarked (grayed) texts on controls. Below is the code for our CalendarExtender :
class="csharpcode"><ajaxToolkit:TextBoxWatermarkExtender
ID="WatermarkExtender1"
runat="server"
TargetControlID="TextBox1"
WatermarkCssClass="watermarked"
WatermarkText="Enter the Date of Birth (dd/mm/yyyy)" />And below is the CSS style that’s used with this watermark extender :
.watermarked
{
color: #C0C0C0;
font-style: italic;
}All looks good now and the user is happy the way Calendar pops up, choosing the date and also the fact that he can type in the date in the textbox in the desired format. Now comes the problem – Date Validation! – How are we going to validate the entered date? – I had to validate that the date entered is not more than today’s date.
There are two ways to do it :
1) Using Javascript (with our CalendarExtender)
2) Using RangeValidators for our textboxUsing Javascript:
The CalendarExtender has a property called OnClientDateSelectionChanged which can be set to a piece of javascript which can do the job for us. Below is the code:
<ajaxToolkit:CalendarExtender ID="CalendarExtender1" runat="server"
TargetControlID="TextBox1" PopupButtonID="btnCalenderPopup"
OnClientDateSelectionChanged="checkMyDate"
Format="dd/MM/yyyy" />and below is the javascript:
<script type="text/javascript">
function checkDate(sender,args)
{
var dt = new Date();
if(sender._selectedDate > dt)
{
sender
._textbox
.set_Value(dt.format(sender._format));
}
}
</script>Using RangeValidator: Since we use a TextBox control to display our date once we choose from the calendar or to manually input the date, RangeValidators can be used to check whether the date is within a given range (minimum & maximum). Below is the code for RangeValidator :
<asp:RangeValidator
ID="RangeValidator1"
runat="server"
ControlToValidate="TextBox1"
ErrorMessage="*Please enter proper date"
Type="Date" Display="Dynamic" />And in your page load event we can set our maximum and minimum date values :
RangeValidator1.MinimumValue
= new DateTime(1600, 01, 01).ToString("dd/MM/yyyy");
RangeValidator1.MaximumValue
= DateTime.Now.ToString("dd/MM/yyyy");With these two methods you can easily validate the date. And yes, using both would sometimes lead you to race conditions where choosing a date from the calendar might be an invalid date and the RangeValidators would immediately come to the focus.
If you have better solution, just tell me !
Console application
Below is my little console application that ask for name and display it in the message dialog box. Unfortunately there is a problem when I try to iimports System.Windows.Forms The error message is Warning 1 Namespace or type specified in the Imports 'System.Windows.Forms' doesn't contain any public member or cannot be found. Make sure the namespace or the type is defined and contains at least one public member. Make sure the imported element name doesn't use any aliases. I'm using Visual Basic 2008 express edition. any help would be appreciated.
Public Class Form1
Dim number(10) As String
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
TextBox1.Text = number(ComboBox1.Items.IndexOf(ComboBox1.Text))
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
ComboBox1.Items.Add(ComboBox1.Text)
number(ComboBox1.Items.IndexOf(ComboBox1.Text)) = TextBox1.Text
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add("") : number(0) = ""
End Sub
End ClassPlease refer to MSDN.microsoft.com/en-us/library/system.windows.forms.aspx
Ajax CalendarExtender - Date Validation
I've just been asked to find a solution to stop users choosing dates in the past in a calendarextender control. After using a little google-phoo, I found a couple of solutions which involved extending the extender itself. Altering the calendar.js then recompiling it and putting it back into your solution. That just seems a bit excessive to me. So I got to thinking couldn't I just use some in page JavaScript to trap the date entered.
First we add a text box and a calendarextender:
<asp:TextBox ID="txtDate" MaxLength="10" runat="server"
ReadOnly="True"></asp:TextBox>
<cc1:CalendarExtender ID="CalendarExtender1" runat="server"
Format="dd/MM/yyyy" TargetControlID="txtDate"
OnClientDateSelectionChanged="checkDate"> </cc1:CalendarExtender>you may notice that the CalendarExtender has an event attached (checkDate) - this is the JavaScript function you want it to call when ever you select a new date, add this function the top of your aspx page:
<script type="text/javascript">
function checkDate(sender,args)
{
//create a new date var and set it to the
//value of the senders selected date
var selectedDate = new Date();
selectedDate = sender._selectedDate;
//create a date var and set it's value to today
var todayDate = new Date();
var mssge = "";if(selectedDate < todayDate)
{
//set the senders selected date to today
sender._selectedDate = todayDate;
//set the textbox assigned to the cal-ex to today
sender._textbox.set_Value(sender._selectedDate.format(sender._format));
//alert the user what we just did and why
alert("Warning! - Date Cannot be in the past");
}
}
</script>Simple and the nice thing is it's reusable for all the calendarextenders on your page, just add the checkDate function to your other extenders.
Happy Coding
Using Ajax to Validate Forms
Forms are such a common element on the Internet we tend to blunder through them without too much thought. However, if the web site has added a few nice touches that make the process easier, it tends to speed up the process and reduce any frustration in finding our preferred username (i.e. try getting your name under Hotmail!).
HowtoAs with all these tutorials, I expect that you have built your solution to the point where it works, but now we want to add our splash of JavaScript magic.In our baseline example, my requirements are:Username validation
Username validation kept in separate function Server side does the it’s normal job I can detect an Ajax request and return something differentOur PHP function to validate the username reads:
function check_username($username) {
$username = trim($username); // strip any white space
$response = array(); // our response
// if the username is blank
if (!$username) {
$response = array(
'ok' => false,
'msg' => "Please specify a username");
// if the username does not match a-z or '.', '-', '_' then// it's not valid
} else if (!preg_match('/^[a-z0-9\.\-_]+$/', $username)) {
$response = array(
'ok' => false,
'msg' => "Your username can only contain alphanumerics and period,dash and underscore (.-_)");
// this would live in an external library just to check if the username is taken
} else if (username_taken($username)) {
$response = array(
'ok' => false,
'msg' => "The selected username is not available");
// it's all good
} else {
$response = array(
'ok' => true,
'msg' => "This username is free");
}
return $response;
}
This format for a response is good, because we are using it to display error messages on the page, but we can also convert it to JSON and use it in our Ajax response later on.
MarkupAgain, it’s assumed your markup is already designed to show error messages.
For this example the following markup is being used within a fieldset.
<div>
<label for="username">Username, valid: a-z.-_</label>
<input type="text" name="username" value="<?=@$_REQUEST['username']?>" id="username" />
<span id="validateUsername"><?php if ($error) { echo $error['msg']; }?></span>
</div>jQuery
Our client side check will perform the following:
- Only if the value has changed run the check, i.e. ignore meta keys
- Use a nice ajax spinner to indicate activity
- Make an Ajax request and show the response
$(document).ready(function () {
var validateUsername = $('#validateUsername');
$('#username').keyup(function () {
var t = this;
if (this.value != this.lastValue) {
if (this.timer) clearTimeout(this.timer);
validateUsername.removeClass('error').html('<img src="images/ajax-loader.gif"height="16" width="16" /> checking availability...');
this.timer = setTimeout(function () {
$.ajax({
url: 'ajax-validation.php',
data: 'action=check_username&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.html(j.msg);
}
});
}, 200);
this.lastValue = this.value;
}
});
});Fire an ajax request in 1/5 of a second.
$.ajax({
url: 'ajax-validation.php',
data: 'action=check_username&username=' + t.value,
dataType: 'json',
type: 'post',
success: function (j) {
validateUsername.html(j.msg);
}
});The actual Ajax request. If the script ajax-validation.php returns any response, convert it to JSON and put the ‘msg’ field in to the validation message.
Ajax Validation code : Download
If you have better solution, just tell me !