0

I'm using javascript in aspx page to log-out inactive user. But also i need to change user status "0" when logged-out automatically. How can i send the value user status "0" when inactive user will logged-out automatically?

public void ValidateUser_LOGSTS_Update(object sender, EventArgs e)
    {
        int userId = 0;

        string Cur_user = Session["Userid"].ToString();
        String constr = ConfigurationManager.ConnectionStrings["abcd"].ConnectionString;
        using (SqlConnection con = new SqlConnection(constr))
        {
            using (SqlCommand cmd = new SqlCommand("sp_tbl_LogCheck_update"))
            {
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@userID", Cur_user);
                cmd.Parameters.Add("@msg", SqlDbType.Int, 20).Direction = ParameterDirection.Output;
                cmd.Connection = con;
                con.Open();
                cmd.ExecuteNonQuery();

                // read output value from @NewId
                string msg_sts = Convert.ToString(cmd.Parameters["@msg"].Value);

                con.Close();
                if (msg_sts == "0")
                {
                    Session.Clear();
                    Session.Abandon();
                    //Response.Redirect(FormsAuthentication.LoginUrl);
                    FormsAuthentication.RedirectToLoginPage();
                }


            }

        }

    }
<script type="text/javascript">

    var t;
    window.onload=resetTimer;
    document.onkeypress=resetTimer;

    function logout()
    {
        alert("You are now logged out.")
        location.href = 'Login.aspx'
    }
    function resetTimer()
    {
        clearTimeout(t);
        t=setTimeout(logout,60000) //logs out in 10 min
    }

    </script>
Chris Catignani
  • 5,040
  • 16
  • 42
  • 49
Faisal
  • 3
  • 2
  • You can create [WebMethod] in your .cs file and call that method from your javascript function with ajax call. – Kalpesh Bhadra Oct 16 '19 at 12:22
  • Can you post what solutions you have tried and the error message(s) you received? – JohnPete22 Oct 16 '19 at 12:22
  • To be honest if the user just turns of the browser and the mechanism for the login expires the status will be hang. But if it is not the case you can create method and call it from your view side as @KalpeshBhadra suggested. – Dahico Oct 16 '19 at 12:25
  • Can you please give me example code to call the method from javascript function with ajax call ? @KalpeshBhadra – Faisal Oct 16 '19 at 12:27
  • I'm very new. Please give me some example code so i can follow. @Dahico – Faisal Oct 16 '19 at 12:29
  • You can find an example here under another question @Faisal https://stackoverflow.com/questions/18236634/asp-net-jquery-ajax-calling-code-behind-method – Dahico Oct 16 '19 at 12:33
  • Try this https://stackoverflow.com/a/7089932/2206420 – Kalpesh Bhadra Oct 16 '19 at 12:35
  • What is this "status" you talk about? Is it a database column? You then probably need to extend your stored procedure. Anyway, don't use the "sp" prefix. And don't use `AddWithValue()`. And ... don't expect logout calls to always succeed. What does this status 0 mean to your application? Can users only log in when their status is 0? Because what if someone is logged in, and their machine or browser crashes? Or your JavaScript call times out for whatever reason? Then their status won't become 0, and they won't be able to log in again... – CodeCaster Oct 17 '19 at 09:52
  • Yes, if the value is "0" then only user can login or else if the value is "1" that means user is already in , so, another user can not log in at that moment. Now the problem is when system will logout inactive use it should also update the status "0" by itself automatically. @CodeCaster – Faisal Oct 17 '19 at 10:59
  • Please read my comment again. You do not want this, it is going to cause more problems than it solves. If you want your users to be able to log in to one system at the same time, you'll have to solve that in another way. – CodeCaster Oct 17 '19 at 11:04
  • Yes that belongs to database column. And only one user can use the system at a time. How can i solve the whole concept ? @CodeCaster – Faisal Oct 17 '19 at 11:26
  • Then you invalidate all other sessions for a given user when they log in in a new session. Because, again, there are tons of reasons why the logout call won't succeed. If their browser or machine crashes, or they delete all their cookies, or they forget to log out on a public machine they can't access anymore, and so on. Setting a column to 0 on logout to enable them to log in again is broken by design. – CodeCaster Oct 17 '19 at 11:28
  • Is it possible to fix this by ajax ? @CodeCaster – Faisal Oct 17 '19 at 11:33

2 Answers2

0

Well you can send an ajax request to your server while logging out the user. For this you have to send the id parameter regard to current user u want to logout , On success response you can perform any task .

var t;
window.onload=resetTimer;
document.onkeypress=resetTimer;

function logout()
{
    alert("You are now logged out.");
    location.href = 'Login.aspx';
$.ajax({
url:"",
type:"post",
data:`id=${id}`,
success:function(response){
}
})
}
function resetTimer()
{
    clearTimeout(t);
    t=setTimeout(logout,60000) //logs out in 10 min
}
  • In url should i put like "control.aspx/ValidateUser_LOGSTS_Update" and in id parameter "Userid" or username ? Please let me know about this. @Shivam Trivedi – Faisal Oct 16 '19 at 12:55
  • This is not working. I'm unable to figure-out the issue... @Shivam Trivedi – Faisal Oct 17 '19 at 05:04
  • `` – Faisal Oct 17 '19 at 05:08
  • seems like you are sending only msg status , well i think you don't need to send this. instead u should send user's id to server where you can get the id , then using that id fetch the record from database and update its value. – Shivam Trivedi Oct 17 '19 at 11:27
  • if still things are not clear , please provide server side code too for this url . i ll suggest you something else. – Shivam Trivedi Oct 17 '19 at 11:27
  • Server side code is already in the question. Please suggest me how can i solve this. – Faisal Oct 17 '19 at 11:45
0

@Faisal please add code to original question for easier reading. Please use this syntax for posting. also make sure to use url correctly. Also check your console for error messages and post it here to make progress in case of errors.

$.ajax({
            type: "post",
            url: "url",
            data: {},
            dataType: "json",
            success: function (response) {
                console.log('yey');
            },
            error: function (xhr, ajaxOptions, thrownError) {
                console.log(xhr.status);
                console.log(thrownError);
            }

        });
Dahico
  • 66
  • 2
  • 12
  • Here is the error message - "Error: no root element found". Updated code is in original ques. @Dahico – Faisal Oct 17 '19 at 11:09
  • ```function logout() {alert("You are now logged out.") location.href = 'redirect.aspx/ValidateUser_LOGSTS_Update'; $.ajax({ type: "post", url: "url", data: "{ msg_sts: 0 }", dataType: "json", success: function (response) { console.log('yey'); },error: function (xhr, ajaxOptions, thrownError) { console.log(xhr.status); console.log(thrownError); } }); ``` – Faisal Oct 17 '19 at 11:47