Pages

Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Monday, October 19, 2009

AJAX implementation using POST method in .NET

Here is where the real Ajax is implementation happens. In fact the .Net framework itself supports the partial page posting using Update Panel and etc. But what actually happens here is, the whole contents of the page goes to the server and comes back. Which is again a similar to a page postback. The only difference is the page events doesn't gets loaded again since its not a post back, but all the contents of the page goes to the server and then returns back.

The real implementation of the AJAX happens only with the JavaScript functions. Here you can really send the partial contents to the server and get back the desired results. There were two ways for the AJAX form posting.
1. GET method and
2. POST method.

Most people tend to go for the GET method since its easier to implement.(Particularly beginners). As you grow you have to be able to identify the instance where you are going to use(GET or POST method). In a simple way,

GET - should be used when a minimum amount of data is going to be passed to the server and collect all the information in a single AJAX call.

POST - when the request is going to be updated frequently and also the server data is going to be changed with the AJAX call then you have to go for POST. Also POST is secured compared to GET method since it doesn't expose the parameters(Query String values).

Here is the example where the POST implementation for simple Login.
EG:

Java script Function


function ajaxPOSTFunction(email,password)
{
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState==4)
{
if (xmlhttp.status == 200)
{
if(xmlhttp.responseText.match("success"))
{
window.location = '<%= ResolveClientUrl("../profile.aspx") %>';
}
else
{
document.getElementById("validateTips").innerHTML = xmlhttp.responseText;
}
}
}
}

//GET METHOD IMPLEMENTATION - Same implementation using GET - commented
//xmlhttp.open("GET","login.aspx?email=" + email + "&password=" + password,true);
//xmlhttp.send(null);


//POST METHOD IMPLEMENTATION
var params = "email="+email+"&password="+password;
xmlhttp.open("POST",'<%= ResolveClientUrl("../login.aspx") %>',true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
}

And here is the code for the login.aspx page - PageLoad() and Private method

Login.aspx

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim email As String = Request.Form("email")
Dim password As String = Request.Form("password")
AuthenticateUser(email, password)
Catch ex As Exception
Response.Write(ex.ToString())
End Try

End Sub

Public Sub AuthenticateUser(ByVal userName As String, ByVal password As String)
Dim ErrorBuilder As New StringBuilder
Dim responseStatus As Integer
Dim responseText As String = String.Empty

responseStatus = Me.Controller.AuthenticateUser(userName, password)
If responseStatus = Constants.ServiceResponseStatus.Success Then
responseText = "success"
End If

Select Case responseStatus

Case Constants.ServiceResponseStatus.Success

Response.Write(responseText)
Response.End()

Case Constants.ServiceResponseStatus.Failure
Response.Write("failure")
Response.End()

Case Constants.ServiceResponseStatus.Exception
Response.Write("There has been an internal error. Please try to login again!")
Response.End()

Case Else
Response.Write("The username or the password you provided was not a valid. Please login with valid username and password.")
Response.End()

End Select

End Sub

Wednesday, October 14, 2009

Printer Friendly Button in JS

I was so pleased with Javascript. In an printer friendly version page if you wanna a Print button which will direct you for printing, then this is the simplest way.

Here we go.

EG: In the anchor tag just call the javascript function window.print().

javascript:window.print();

Click on the Print this page link to check out.

Print this Page

Really small piece of code right..

Thursday, August 27, 2009

Change Focus for TextBoxes using Javascript

In most of the real time project there will be requirement to change focus of the TextBox from one to another dynamically, instead of clicking the TextBoxes. The ideal example in this case would be Phone Number Text Boxes in the US format(000-000-0000). Consider there were three TextBoxes. It wil be irritating for the end user to click each text box and then type numbers.

So here, on every keyboard press event ("onkeypress") we capture the event and check for the length of the TextBox in the changeFocus() Javascript function. Again the browser compatibility issue raises its head and its handled in its own way. This is so simple to implement. Here is the code snippet.

Javascript Function:

//Change Focus for the Phone TextBox

function changeFocus(textbox1,textbox2)
{
var browserName=navigator.appName;
if (browserName=="Netscape")
{
if(textbox1.value.length >= 2)
{
textbox2.focus();
}
}
else if(browserName=="Microsoft Internet Explorer")
{
if(textbox1.value.length == 3)
{
textbox2.focus();
}
}
else
{
if(textbox1.value.length == 3)
{
textbox2.focus();
}
}
return true;
}

//End of Change Focus for the Phone TextBox


The ASP.NET(Vb) File Code:-

You can add this code in the Load Event of the Page.

Me.TxtCellPhone1.Attributes.Add("onkeypress", String.Format("javascript:return changeFocus({0},{1});", Me.TxtCellPhone1.ClientID, Me.TxtCellPhone2.ClientID))
Me.TxtCellPhone2.Attributes.Add("onkeypress", String.Format("javascript:return changeFocus({0},{1});", Me.TxtCellPhone2.ClientID, Me.TxtCellPhone3.ClientID))

Here no need to add an event for TxtCellPhone3 TextBox.

Let me know your Thoughts. Happy Coding.

Tuesday, August 25, 2009

Diable Browser Back Button

I have gone mad for getting my browser back button disabled in one of my projects. And at last arrived at this solution:

function disableBrowserBackBtn() { window.history.go(1) }
disableBrowserBackBtn();
window.onload = disableBrowserBackBtn();
window.onpageshow = function(evt) { if (evt.persisted) disableBrowserBackBtn() }
window.onunload = function() { void (0); disableBrowserBackBtn(); }

You have to just add the Script in the pages you want to disable the browser back button.

But this is just bluffing the user, using the the javascript code window.hsitory.go(-1) ->Redirecting to previous page.

For the perfect solution you have to open a new pop-up window with no navigation toolbar.

Please let me know your comments....Have a good day.