ASP.net JQuery Ajax call to set session for Login Page.
ASP.net JQuery Ajax call to set session. Problem: Session lost on ajax call. Solution: Please check any resource image/js etc missing or not through browsers developer tool > Console.
Step1: Create vinservice.asmx page with following line:
<%@ WebService Language="VB" CodeBehind="~/App_Code/vinservice.vb" Class="vinservice" %>
Step2: Create corresponding vb file under App_Code folder as vinservice.vb
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports System.Data
Imports System.Data.SqlClient
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
_
_
_
_
Public Class vinservice
Inherits System.Web.Services.WebService
Public Function checkSession() As Boolean
If HttpContext.Current.Session("eid") Is Nothing Then
Return False
Else
Return True
End If
' DateTime.Now.ToString()
End Function
Public Function setSession(ByVal type As String, ByVal pro As String) As Boolean
HttpContext.Current.Session("type") = type
HttpContext.Current.Session("pro") = pro
Return True
End Function
Public Function displaySession() As String
Return HttpContext.Current.Session("eid") & HttpContext.Current.Session("ename")
End Function
Public Function setUserSession(ByVal eid As String, ByVal name As String) As String
Try
If Not String.IsNullOrEmpty(eid) And Not String.IsNullOrEmpty(name) Then
' HttpContext.Current.Session.Clear()
' System.Threading.Thread.Sleep(1000)
HttpContext.Current.Session.Add("eid", eid)
HttpContext.Current.Session.Add("ename", name)
'HttpContext.Current.Session("eid") = eid
'HttpContext.Current.Session("ename") = name
Return "success"
Else
Return "Empty" & eid & name
End If
Catch e As Exception
Return "Error in webservice:" + e.Message
End Try
End Function
Public Function clearSession() As String
Try
HttpContext.Current.Session.Abandon()
HttpContext.Current.Session.Clear()
Return "success"
Catch e As Exception
Return "Error in webservice:" + e.Message
End Try
End Function
Public Function authenticateuserAjax(ByVal name As String, ByVal pwd As String) As String
'' Return "ID is " + name + " pwd is " + pwd
Dim mysql = "SELECT distinct first_name FROM users u,groups g,group_users gu WHERE u.userid = gu.userid and g.gid = gu.gid and username='" & name.Trim & "' and password=md5('" & pwd.Trim & "') and g.name like ('%')"
Using connection As New MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("vinConn").ConnectionString)
connection.Open()
Dim result As String
Dim sqlComm As MySqlCommand
Dim sqlReader As MySqlDataReader
Dim dt As New DataTable()
Dim dataTableRowCount As Integer
Try
sqlComm = New MySqlCommand(mysql, connection)
sqlReader = sqlComm.ExecuteReader()
dt.Load(sqlReader)
dataTableRowCount = dt.Rows.Count
sqlReader.Close()
sqlComm.Dispose()
If dataTableRowCount = 1 Then
result = dt.Rows(0).Item(0).ToString()
connection.Close()
Return result
Else
connection.Close()
Return "Error: Username/Password not valid."
End If
Catch exp As Exception
connection.Close()
Return "Error inside web service: " + exp.Message
End Try
'Close Database connection
'and Dispose Database objects
End Using
End Function
End Class
Step3: Add following Jquery script in your html under head tag.
<%-- PURE AJAX LOGIN By VINOD KOTIYA--%>
<script type="text/javascript">
$(document).ready(function () {
//check module upload or suggestion
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
}
else {
return results[1] || 0;
}
}
if ($.urlParam('sug') == 1)
return 1; //dont execute below code.
//check session exist or not
$.ajax({
type: "POST",
url: "vinservice.asmx/checkSession",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (!response.d) { // alert('do popup' + response.d);
var s1 = '<label class=label1>Emp No:</label><input type=text name=eid id=txtEid class=textbox1><br /> <br/><label class=label1> Password</label><input type=password name=password id=txtPassword class=textbox1><br /> <label> </label><input value=Login name=Login id=btnLogin class=submit1 type=submit onclick="checkLogin();" />';
var s2 = ' <br/><br/><br/><br/><a href=profile.aspx?cp=1&ref=upload.aspx class=label1><img src=images/changepassword.gif border=0 />Change Password</a> <a href=profile.aspx?fp=1&ref=upload.aspx class=label1><img src=images/forgotpassword.gif border=0 />Forgot Password</a>';
var s3 = '<br/> <br/><br/> <br/><div style=align:center; class=label1> <a href=Default.aspx><<--Back to Home</a></div>'
$("#dynamicControl1").html(s1 + s2 + s3);
$('#login_pop_up').bPopup({
// content: 'iframe', //'ajax', 'iframe' or 'image'
// contentContainer: '.content',
//loadUrl: 'test.html' //Uses jQuery.load() vin.jpg
modalClose: false,
position: [350, 150], //x, y,
positionStyle: 'fixed', //'fixed' or 'absolute' dont close
fadeSpeed: 'slow', //can be a string ('slow'/'fast') or int
followSpeed: 1500, //can be a string ('slow'/'fast') or int
modalColor: 'black',
easing: 'easeOutBack', //uses jQuery easing plugin
speed: 450,
transition: 'slideDown'
// onClose: function () { $('#element_to_pop_up').bPopup(); }
// onOpen: function () { alert('onOpen fired:' + i + j); },
// onClose: function () { alert('onClose fired'); }
// autoClose: 1000 //Auto closes after 1000ms/1sec
});
}
// else
// alert('session'+response.d);
}
});
return false;
});
function checkLogin() {
var myUser = {};
myUser.name = $("[id*=txtEid]").val();
myUser.pwd = $("[id*=txtPassword]").val();
$.ajax({
type: "POST",
url: "vinservice.asmx/authenticateuserAjax",
data: JSON.stringify(myUser),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// var v = response.d
if (response.d.indexOf("Error") > -1) alert(response.d);
else {
// alert('success' + response.d + myUser.name ); //set session
setTimeout(setSession(myUser.name, response.d),2000);
}
},
error: function (response) {
alert(user+pwd+response.d);
}
});
return false;
}
function setSession(user, name)
{
// setSession1(user, name);
var obj = {};
obj.eid = user;
obj.name = name;
$.ajax({
type: "POST",
url: "vinservice.asmx/setUserSession",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// displaySession();
// alert(user + response.d);
//reload the page as session created
location.reload();
},
error: function (response) {
alert('unable to set session ' + user + response.d);
}
});
}
function displaySession() {
$.ajax({
type: "POST",
url: "vinservice.asmx/displaySession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('unable to get session ' );
}
});
}
function clearSession() {
$.ajax({
type: "POST",
url: "vinservice.asmx/clearSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// alert( response.d);
//reload the page as session created
location.reload();
},
error: function (response) {
alert('unable to clear session ' + user + response.d);
}
});
}
</script>
<%-- End of PURE AJAX LOGIN By VINOD KOTIYA--%>
Step4: Create following div for login controls in your page:
<div id="login_pop_up">
<div id="dynamicControl1" runat="server" style="margin-top: -13px;" >
<img id="loading-image1" src="images/loading.gif" />
</div>
</div>
Output:
Step1: Create vinservice.asmx page with following line:
<%@ WebService Language="VB" CodeBehind="~/App_Code/vinservice.vb" Class="vinservice" %>
Step2: Create corresponding vb file under App_Code folder as vinservice.vb
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services
Imports System.Web.Script.Serialization
Imports MySql.Data
Imports MySql.Data.MySqlClient
Imports System.Data
Imports System.Data.SqlClient
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
Public Class vinservice
Inherits System.Web.Services.WebService
Public Function checkSession() As Boolean
If HttpContext.Current.Session("eid") Is Nothing Then
Return False
Else
Return True
End If
' DateTime.Now.ToString()
End Function
Public Function setSession(ByVal type As String, ByVal pro As String) As Boolean
HttpContext.Current.Session("type") = type
HttpContext.Current.Session("pro") = pro
Return True
End Function
Public Function displaySession() As String
Return HttpContext.Current.Session("eid") & HttpContext.Current.Session("ename")
End Function
Public Function setUserSession(ByVal eid As String, ByVal name As String) As String
Try
If Not String.IsNullOrEmpty(eid) And Not String.IsNullOrEmpty(name) Then
' HttpContext.Current.Session.Clear()
' System.Threading.Thread.Sleep(1000)
HttpContext.Current.Session.Add("eid", eid)
HttpContext.Current.Session.Add("ename", name)
'HttpContext.Current.Session("eid") = eid
'HttpContext.Current.Session("ename") = name
Return "success"
Else
Return "Empty" & eid & name
End If
Catch e As Exception
Return "Error in webservice:" + e.Message
End Try
End Function
Public Function clearSession() As String
Try
HttpContext.Current.Session.Abandon()
HttpContext.Current.Session.Clear()
Return "success"
Catch e As Exception
Return "Error in webservice:" + e.Message
End Try
End Function
Public Function authenticateuserAjax(ByVal name As String, ByVal pwd As String) As String
'' Return "ID is " + name + " pwd is " + pwd
Dim mysql = "SELECT distinct first_name FROM users u,groups g,group_users gu WHERE u.userid = gu.userid and g.gid = gu.gid and username='" & name.Trim & "' and password=md5('" & pwd.Trim & "') and g.name like ('%')"
Using connection As New MySqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("vinConn").ConnectionString)
connection.Open()
Dim result As String
Dim sqlComm As MySqlCommand
Dim sqlReader As MySqlDataReader
Dim dt As New DataTable()
Dim dataTableRowCount As Integer
Try
sqlComm = New MySqlCommand(mysql, connection)
sqlReader = sqlComm.ExecuteReader()
dt.Load(sqlReader)
dataTableRowCount = dt.Rows.Count
sqlReader.Close()
sqlComm.Dispose()
If dataTableRowCount = 1 Then
result = dt.Rows(0).Item(0).ToString()
connection.Close()
Return result
Else
connection.Close()
Return "Error: Username/Password not valid."
End If
Catch exp As Exception
connection.Close()
Return "Error inside web service: " + exp.Message
End Try
'Close Database connection
'and Dispose Database objects
End Using
End Function
End Class
Step3: Add following Jquery script in your html under head tag.
<%-- PURE AJAX LOGIN By VINOD KOTIYA--%>
<script type="text/javascript">
$(document).ready(function () {
//check module upload or suggestion
$.urlParam = function (name) {
var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
if (results == null) {
return null;
}
else {
return results[1] || 0;
}
}
if ($.urlParam('sug') == 1)
return 1; //dont execute below code.
//check session exist or not
$.ajax({
type: "POST",
url: "vinservice.asmx/checkSession",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (!response.d) { // alert('do popup' + response.d);
var s1 = '<label class=label1>Emp No:</label><input type=text name=eid id=txtEid class=textbox1><br /> <br/><label class=label1> Password</label><input type=password name=password id=txtPassword class=textbox1><br /> <label> </label><input value=Login name=Login id=btnLogin class=submit1 type=submit onclick="checkLogin();" />';
var s2 = ' <br/><br/><br/><br/><a href=profile.aspx?cp=1&ref=upload.aspx class=label1><img src=images/changepassword.gif border=0 />Change Password</a> <a href=profile.aspx?fp=1&ref=upload.aspx class=label1><img src=images/forgotpassword.gif border=0 />Forgot Password</a>';
var s3 = '<br/> <br/><br/> <br/><div style=align:center; class=label1> <a href=Default.aspx><<--Back to Home</a></div>'
$("#dynamicControl1").html(s1 + s2 + s3);
$('#login_pop_up').bPopup({
// content: 'iframe', //'ajax', 'iframe' or 'image'
// contentContainer: '.content',
//loadUrl: 'test.html' //Uses jQuery.load() vin.jpg
modalClose: false,
position: [350, 150], //x, y,
positionStyle: 'fixed', //'fixed' or 'absolute' dont close
fadeSpeed: 'slow', //can be a string ('slow'/'fast') or int
followSpeed: 1500, //can be a string ('slow'/'fast') or int
modalColor: 'black',
easing: 'easeOutBack', //uses jQuery easing plugin
speed: 450,
transition: 'slideDown'
// onClose: function () { $('#element_to_pop_up').bPopup(); }
// onOpen: function () { alert('onOpen fired:' + i + j); },
// onClose: function () { alert('onClose fired'); }
// autoClose: 1000 //Auto closes after 1000ms/1sec
});
}
// else
// alert('session'+response.d);
}
});
return false;
});
function checkLogin() {
var myUser = {};
myUser.name = $("[id*=txtEid]").val();
myUser.pwd = $("[id*=txtPassword]").val();
$.ajax({
type: "POST",
url: "vinservice.asmx/authenticateuserAjax",
data: JSON.stringify(myUser),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// var v = response.d
if (response.d.indexOf("Error") > -1) alert(response.d);
else {
// alert('success' + response.d + myUser.name ); //set session
setTimeout(setSession(myUser.name, response.d),2000);
}
},
error: function (response) {
alert(user+pwd+response.d);
}
});
return false;
}
function setSession(user, name)
{
// setSession1(user, name);
var obj = {};
obj.eid = user;
obj.name = name;
$.ajax({
type: "POST",
url: "vinservice.asmx/setUserSession",
data: JSON.stringify(obj),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// displaySession();
// alert(user + response.d);
//reload the page as session created
location.reload();
},
error: function (response) {
alert('unable to set session ' + user + response.d);
}
});
}
function displaySession() {
$.ajax({
type: "POST",
url: "vinservice.asmx/displaySession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.d);
},
error: function (response) {
alert('unable to get session ' );
}
});
}
function clearSession() {
$.ajax({
type: "POST",
url: "vinservice.asmx/clearSession",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
// alert( response.d);
//reload the page as session created
location.reload();
},
error: function (response) {
alert('unable to clear session ' + user + response.d);
}
});
}
</script>
<%-- End of PURE AJAX LOGIN By VINOD KOTIYA--%>
Step4: Create following div for login controls in your page:
<div id="login_pop_up">
<div id="dynamicControl1" runat="server" style="margin-top: -13px;" >
<img id="loading-image1" src="images/loading.gif" />
</div>
</div>
Output:
Comments