How to check JSESSION in javascript











up vote
3
down vote

favorite












I am developing a component and I use ajax calls to do some tasks in the frontend.
I have come to a problem when the session is expires and I don't want to use keepalive to solve it.



In the frontend I have a list view. And there there are some buttons that perform tasks using ajax requests.



For example :



$('#resetData').on('click', function (e) {
e.preventDefault();
var token = jQuery("#token").attr("name");
var itemId = $(this).attr('data-id');
$.ajax({
method: 'POST',
cache: false,
dataType: "json",
data: { [token]: "1", id: itemId},
url: 'index.php?option=com_contract&task=contract.resetData'
}).success(function (r) {
console.log('Response :');
console.log(r);
if (r.responseText) {
UIkit.modal.alert(r.responseText).then(function () {
window.location.reload();
});
}
if (r.message) {
UIkit.modal.alert(r.message).then(function () {
window.location.reload();
});
}
}).error(function (err) {
console.log(err);
UIkit.modal.alert('<div class="alert alert-error">' + err + '</div>').then(function () {
return;
});
}).complete(function (r) {
console.log(r.responseText);
});


When the session has expired, in my main controller I redirect to login page.
JFactory::getApplication()->redirect(JURI::base() . 'index.php?option=com_users&view=login', $error, 'error'); //redirect to login page



This means that the hole html is returned in the Ajax response and when I popup the response I get an [object object] instead of a human readable error.



I guess I need to find a way to check if the session has expired when click event fires and alert an error, before I make the Ajax call.



Is it possible to check the JSESSION in javascript or any other way to solve it ?










share|improve this question


























    up vote
    3
    down vote

    favorite












    I am developing a component and I use ajax calls to do some tasks in the frontend.
    I have come to a problem when the session is expires and I don't want to use keepalive to solve it.



    In the frontend I have a list view. And there there are some buttons that perform tasks using ajax requests.



    For example :



    $('#resetData').on('click', function (e) {
    e.preventDefault();
    var token = jQuery("#token").attr("name");
    var itemId = $(this).attr('data-id');
    $.ajax({
    method: 'POST',
    cache: false,
    dataType: "json",
    data: { [token]: "1", id: itemId},
    url: 'index.php?option=com_contract&task=contract.resetData'
    }).success(function (r) {
    console.log('Response :');
    console.log(r);
    if (r.responseText) {
    UIkit.modal.alert(r.responseText).then(function () {
    window.location.reload();
    });
    }
    if (r.message) {
    UIkit.modal.alert(r.message).then(function () {
    window.location.reload();
    });
    }
    }).error(function (err) {
    console.log(err);
    UIkit.modal.alert('<div class="alert alert-error">' + err + '</div>').then(function () {
    return;
    });
    }).complete(function (r) {
    console.log(r.responseText);
    });


    When the session has expired, in my main controller I redirect to login page.
    JFactory::getApplication()->redirect(JURI::base() . 'index.php?option=com_users&view=login', $error, 'error'); //redirect to login page



    This means that the hole html is returned in the Ajax response and when I popup the response I get an [object object] instead of a human readable error.



    I guess I need to find a way to check if the session has expired when click event fires and alert an error, before I make the Ajax call.



    Is it possible to check the JSESSION in javascript or any other way to solve it ?










    share|improve this question
























      up vote
      3
      down vote

      favorite









      up vote
      3
      down vote

      favorite











      I am developing a component and I use ajax calls to do some tasks in the frontend.
      I have come to a problem when the session is expires and I don't want to use keepalive to solve it.



      In the frontend I have a list view. And there there are some buttons that perform tasks using ajax requests.



      For example :



      $('#resetData').on('click', function (e) {
      e.preventDefault();
      var token = jQuery("#token").attr("name");
      var itemId = $(this).attr('data-id');
      $.ajax({
      method: 'POST',
      cache: false,
      dataType: "json",
      data: { [token]: "1", id: itemId},
      url: 'index.php?option=com_contract&task=contract.resetData'
      }).success(function (r) {
      console.log('Response :');
      console.log(r);
      if (r.responseText) {
      UIkit.modal.alert(r.responseText).then(function () {
      window.location.reload();
      });
      }
      if (r.message) {
      UIkit.modal.alert(r.message).then(function () {
      window.location.reload();
      });
      }
      }).error(function (err) {
      console.log(err);
      UIkit.modal.alert('<div class="alert alert-error">' + err + '</div>').then(function () {
      return;
      });
      }).complete(function (r) {
      console.log(r.responseText);
      });


      When the session has expired, in my main controller I redirect to login page.
      JFactory::getApplication()->redirect(JURI::base() . 'index.php?option=com_users&view=login', $error, 'error'); //redirect to login page



      This means that the hole html is returned in the Ajax response and when I popup the response I get an [object object] instead of a human readable error.



      I guess I need to find a way to check if the session has expired when click event fires and alert an error, before I make the Ajax call.



      Is it possible to check the JSESSION in javascript or any other way to solve it ?










      share|improve this question













      I am developing a component and I use ajax calls to do some tasks in the frontend.
      I have come to a problem when the session is expires and I don't want to use keepalive to solve it.



      In the frontend I have a list view. And there there are some buttons that perform tasks using ajax requests.



      For example :



      $('#resetData').on('click', function (e) {
      e.preventDefault();
      var token = jQuery("#token").attr("name");
      var itemId = $(this).attr('data-id');
      $.ajax({
      method: 'POST',
      cache: false,
      dataType: "json",
      data: { [token]: "1", id: itemId},
      url: 'index.php?option=com_contract&task=contract.resetData'
      }).success(function (r) {
      console.log('Response :');
      console.log(r);
      if (r.responseText) {
      UIkit.modal.alert(r.responseText).then(function () {
      window.location.reload();
      });
      }
      if (r.message) {
      UIkit.modal.alert(r.message).then(function () {
      window.location.reload();
      });
      }
      }).error(function (err) {
      console.log(err);
      UIkit.modal.alert('<div class="alert alert-error">' + err + '</div>').then(function () {
      return;
      });
      }).complete(function (r) {
      console.log(r.responseText);
      });


      When the session has expired, in my main controller I redirect to login page.
      JFactory::getApplication()->redirect(JURI::base() . 'index.php?option=com_users&view=login', $error, 'error'); //redirect to login page



      This means that the hole html is returned in the Ajax response and when I popup the response I get an [object object] instead of a human readable error.



      I guess I need to find a way to check if the session has expired when click event fires and alert an error, before I make the Ajax call.



      Is it possible to check the JSESSION in javascript or any other way to solve it ?







      joomla-3.x javascript ajax jsession






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked yesterday









      mixahlos

      1298




      1298






















          2 Answers
          2






          active

          oldest

          votes

















          up vote
          3
          down vote













          One way I can imagine to check the session is before you ignite the above ajax call, you make a previous ajax call to another function in com_contract/controller(task = your new session checking function. so: url:...com_contract/task=checkSession) where you create a function, something like:



          public function checkSession() 
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }


          I just created this function here fast, so mistakes might be in it and also can be improved with anything more but this is how I would start to check the session via ajax.



          The other implication would be according to me, that if a session is expired then the token might be invalid during this call. I did not try that, so it has to be tested, whether the ajax call can be sent with the token (from an expired session. it does not sound too logical).



          Exactly because of this reason (expired tokens) I suggested earlier to keep the session alive, instead of other solutions on sessions.



          FEW ADDITIONAL THOUGHTS ON THIS SUBJECT (since this subject will come up many times here)



          If you try to make an ajax call with an expired session token, then you will always get an 'invalid token' response, thus the ajax call will fail anyway, so it is better to do a redirect in javascript if the response is 'invalid token' because of expired session or because of the invalid response (simply a failed ajax call). Then the check session function could be extended with few lines, as an example, but probably it does not have valid purpose in this case:



          public function checkSession() 
          {
          if (! JSession::checkToken())
          {
          echo new JResponseJson('invalid token');
          // jexit( 'Invalid Token' );
          }
          else
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }
          }


          This I wanted to add to this subject. But without this relatively redundant function, simply any invalid token response should ignite redirect in the javascript, so checking session state is not really needed here. At least I at the moment do not see the reason for that.






          share|improve this answer























          • Thank you for your time @Zollie. I tested your function and it works with a small addition. After the echo new JResponseJson must call die() or JFactory::getApplication()->close(); because it will return html instead of the JSON response. As you already said, only the first if is enough, if the session has expired then since the function is not called at all. I will post a new answer with the complete working code and comments for future searches if is ok with you.
            – mixahlos
            16 hours ago










          • I'm happy that it helped you in solving the problem. I also used jexit() after the invalid token jsonresponse (I just put it as a comment in the code), so I agree with you on this too, it should be closed this way or that way with a required response. :)
            – Zollie
            16 hours ago










          • After a lot of testing it is not working properly. This is because of the asynchronous nature of ajax. When making the ajax call to check the session, the rest of the code is still running. So the next ajax call is also being called and returns before the checkSession. This is happening in most of the times, this results the error message from the next ajax call (the original one) to be displayed before the alert or (reload in my case) if the session has expired, so this takes us back to the original problem.
            – mixahlos
            9 hours ago










          • I see your point and I do not want to start a long session here in comments :) , but you should restructure your javascript/jQuery script because of the nature of javascript. There are at least 3 different solutions on that problem in javascript. The second function should only be ignited if we get the first function' response.
            – Zollie
            5 hours ago


















          up vote
          2
          down vote













          To get the session state, you can use the following:



          JFactory::getSession()->getState();


          I'm not sure if this script is inline or a separate file. If it's inline then you can simply add the following to your Javascript:



          var sessionState = '<?php echo JFactory::getSession()->getState(); ?>';
          if (sessionState === 'expired') {
          // redirect to login page
          }


          On a side note, the use of .success() and .error() are deprecated in jQuery. Please use .done() and .fail(). Also, just so you know, .then() will not work in IE11.






          share|improve this answer





















          • This looks like a more workable solution to this question, simpler and better than what I wrote few minutes after this... :) upvoted
            – Zollie
            yesterday










          • Actually this isnt a good solution as it doesnt check when the button is clicked. It checks on page load. Your anawer does the trick properly so I'll delete this
            – Lodder
            yesterday










          • From this approach you are right. But I don't know why, I just liked the simple approach of your answer. I would leave that here any way, it's still very good for reference in other session checking cases for later researchers.
            – Zollie
            yesterday










          • It would be great if it was working. Really clean simple with just a few lines of code. Unfortunately as already said is not working in the click listener. Thank you
            – mixahlos
            16 hours ago











          Your Answer








          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "555"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: false,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: null,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          noCode: true, onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














           

          draft saved


          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fjoomla.stackexchange.com%2fquestions%2f23792%2fhow-to-check-jsession-in-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          2 Answers
          2






          active

          oldest

          votes








          2 Answers
          2






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          3
          down vote













          One way I can imagine to check the session is before you ignite the above ajax call, you make a previous ajax call to another function in com_contract/controller(task = your new session checking function. so: url:...com_contract/task=checkSession) where you create a function, something like:



          public function checkSession() 
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }


          I just created this function here fast, so mistakes might be in it and also can be improved with anything more but this is how I would start to check the session via ajax.



          The other implication would be according to me, that if a session is expired then the token might be invalid during this call. I did not try that, so it has to be tested, whether the ajax call can be sent with the token (from an expired session. it does not sound too logical).



          Exactly because of this reason (expired tokens) I suggested earlier to keep the session alive, instead of other solutions on sessions.



          FEW ADDITIONAL THOUGHTS ON THIS SUBJECT (since this subject will come up many times here)



          If you try to make an ajax call with an expired session token, then you will always get an 'invalid token' response, thus the ajax call will fail anyway, so it is better to do a redirect in javascript if the response is 'invalid token' because of expired session or because of the invalid response (simply a failed ajax call). Then the check session function could be extended with few lines, as an example, but probably it does not have valid purpose in this case:



          public function checkSession() 
          {
          if (! JSession::checkToken())
          {
          echo new JResponseJson('invalid token');
          // jexit( 'Invalid Token' );
          }
          else
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }
          }


          This I wanted to add to this subject. But without this relatively redundant function, simply any invalid token response should ignite redirect in the javascript, so checking session state is not really needed here. At least I at the moment do not see the reason for that.






          share|improve this answer























          • Thank you for your time @Zollie. I tested your function and it works with a small addition. After the echo new JResponseJson must call die() or JFactory::getApplication()->close(); because it will return html instead of the JSON response. As you already said, only the first if is enough, if the session has expired then since the function is not called at all. I will post a new answer with the complete working code and comments for future searches if is ok with you.
            – mixahlos
            16 hours ago










          • I'm happy that it helped you in solving the problem. I also used jexit() after the invalid token jsonresponse (I just put it as a comment in the code), so I agree with you on this too, it should be closed this way or that way with a required response. :)
            – Zollie
            16 hours ago










          • After a lot of testing it is not working properly. This is because of the asynchronous nature of ajax. When making the ajax call to check the session, the rest of the code is still running. So the next ajax call is also being called and returns before the checkSession. This is happening in most of the times, this results the error message from the next ajax call (the original one) to be displayed before the alert or (reload in my case) if the session has expired, so this takes us back to the original problem.
            – mixahlos
            9 hours ago










          • I see your point and I do not want to start a long session here in comments :) , but you should restructure your javascript/jQuery script because of the nature of javascript. There are at least 3 different solutions on that problem in javascript. The second function should only be ignited if we get the first function' response.
            – Zollie
            5 hours ago















          up vote
          3
          down vote













          One way I can imagine to check the session is before you ignite the above ajax call, you make a previous ajax call to another function in com_contract/controller(task = your new session checking function. so: url:...com_contract/task=checkSession) where you create a function, something like:



          public function checkSession() 
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }


          I just created this function here fast, so mistakes might be in it and also can be improved with anything more but this is how I would start to check the session via ajax.



          The other implication would be according to me, that if a session is expired then the token might be invalid during this call. I did not try that, so it has to be tested, whether the ajax call can be sent with the token (from an expired session. it does not sound too logical).



          Exactly because of this reason (expired tokens) I suggested earlier to keep the session alive, instead of other solutions on sessions.



          FEW ADDITIONAL THOUGHTS ON THIS SUBJECT (since this subject will come up many times here)



          If you try to make an ajax call with an expired session token, then you will always get an 'invalid token' response, thus the ajax call will fail anyway, so it is better to do a redirect in javascript if the response is 'invalid token' because of expired session or because of the invalid response (simply a failed ajax call). Then the check session function could be extended with few lines, as an example, but probably it does not have valid purpose in this case:



          public function checkSession() 
          {
          if (! JSession::checkToken())
          {
          echo new JResponseJson('invalid token');
          // jexit( 'Invalid Token' );
          }
          else
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }
          }


          This I wanted to add to this subject. But without this relatively redundant function, simply any invalid token response should ignite redirect in the javascript, so checking session state is not really needed here. At least I at the moment do not see the reason for that.






          share|improve this answer























          • Thank you for your time @Zollie. I tested your function and it works with a small addition. After the echo new JResponseJson must call die() or JFactory::getApplication()->close(); because it will return html instead of the JSON response. As you already said, only the first if is enough, if the session has expired then since the function is not called at all. I will post a new answer with the complete working code and comments for future searches if is ok with you.
            – mixahlos
            16 hours ago










          • I'm happy that it helped you in solving the problem. I also used jexit() after the invalid token jsonresponse (I just put it as a comment in the code), so I agree with you on this too, it should be closed this way or that way with a required response. :)
            – Zollie
            16 hours ago










          • After a lot of testing it is not working properly. This is because of the asynchronous nature of ajax. When making the ajax call to check the session, the rest of the code is still running. So the next ajax call is also being called and returns before the checkSession. This is happening in most of the times, this results the error message from the next ajax call (the original one) to be displayed before the alert or (reload in my case) if the session has expired, so this takes us back to the original problem.
            – mixahlos
            9 hours ago










          • I see your point and I do not want to start a long session here in comments :) , but you should restructure your javascript/jQuery script because of the nature of javascript. There are at least 3 different solutions on that problem in javascript. The second function should only be ignited if we get the first function' response.
            – Zollie
            5 hours ago













          up vote
          3
          down vote










          up vote
          3
          down vote









          One way I can imagine to check the session is before you ignite the above ajax call, you make a previous ajax call to another function in com_contract/controller(task = your new session checking function. so: url:...com_contract/task=checkSession) where you create a function, something like:



          public function checkSession() 
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }


          I just created this function here fast, so mistakes might be in it and also can be improved with anything more but this is how I would start to check the session via ajax.



          The other implication would be according to me, that if a session is expired then the token might be invalid during this call. I did not try that, so it has to be tested, whether the ajax call can be sent with the token (from an expired session. it does not sound too logical).



          Exactly because of this reason (expired tokens) I suggested earlier to keep the session alive, instead of other solutions on sessions.



          FEW ADDITIONAL THOUGHTS ON THIS SUBJECT (since this subject will come up many times here)



          If you try to make an ajax call with an expired session token, then you will always get an 'invalid token' response, thus the ajax call will fail anyway, so it is better to do a redirect in javascript if the response is 'invalid token' because of expired session or because of the invalid response (simply a failed ajax call). Then the check session function could be extended with few lines, as an example, but probably it does not have valid purpose in this case:



          public function checkSession() 
          {
          if (! JSession::checkToken())
          {
          echo new JResponseJson('invalid token');
          // jexit( 'Invalid Token' );
          }
          else
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }
          }


          This I wanted to add to this subject. But without this relatively redundant function, simply any invalid token response should ignite redirect in the javascript, so checking session state is not really needed here. At least I at the moment do not see the reason for that.






          share|improve this answer














          One way I can imagine to check the session is before you ignite the above ajax call, you make a previous ajax call to another function in com_contract/controller(task = your new session checking function. so: url:...com_contract/task=checkSession) where you create a function, something like:



          public function checkSession() 
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }


          I just created this function here fast, so mistakes might be in it and also can be improved with anything more but this is how I would start to check the session via ajax.



          The other implication would be according to me, that if a session is expired then the token might be invalid during this call. I did not try that, so it has to be tested, whether the ajax call can be sent with the token (from an expired session. it does not sound too logical).



          Exactly because of this reason (expired tokens) I suggested earlier to keep the session alive, instead of other solutions on sessions.



          FEW ADDITIONAL THOUGHTS ON THIS SUBJECT (since this subject will come up many times here)



          If you try to make an ajax call with an expired session token, then you will always get an 'invalid token' response, thus the ajax call will fail anyway, so it is better to do a redirect in javascript if the response is 'invalid token' because of expired session or because of the invalid response (simply a failed ajax call). Then the check session function could be extended with few lines, as an example, but probably it does not have valid purpose in this case:



          public function checkSession() 
          {
          if (! JSession::checkToken())
          {
          echo new JResponseJson('invalid token');
          // jexit( 'Invalid Token' );
          }
          else
          {
          try
          {
          $session1 = JFactory::getSession();
          $isActive = $session1->isActive();
          $sessionState = $session1->getState();
          echo new JResponseJson($isActive, $sessionState);
          }
          catch(Exception $e)
          {
          echo new JResponseJson($e);
          }
          }
          }


          This I wanted to add to this subject. But without this relatively redundant function, simply any invalid token response should ignite redirect in the javascript, so checking session state is not really needed here. At least I at the moment do not see the reason for that.







          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited 19 hours ago

























          answered yesterday









          Zollie

          3819




          3819












          • Thank you for your time @Zollie. I tested your function and it works with a small addition. After the echo new JResponseJson must call die() or JFactory::getApplication()->close(); because it will return html instead of the JSON response. As you already said, only the first if is enough, if the session has expired then since the function is not called at all. I will post a new answer with the complete working code and comments for future searches if is ok with you.
            – mixahlos
            16 hours ago










          • I'm happy that it helped you in solving the problem. I also used jexit() after the invalid token jsonresponse (I just put it as a comment in the code), so I agree with you on this too, it should be closed this way or that way with a required response. :)
            – Zollie
            16 hours ago










          • After a lot of testing it is not working properly. This is because of the asynchronous nature of ajax. When making the ajax call to check the session, the rest of the code is still running. So the next ajax call is also being called and returns before the checkSession. This is happening in most of the times, this results the error message from the next ajax call (the original one) to be displayed before the alert or (reload in my case) if the session has expired, so this takes us back to the original problem.
            – mixahlos
            9 hours ago










          • I see your point and I do not want to start a long session here in comments :) , but you should restructure your javascript/jQuery script because of the nature of javascript. There are at least 3 different solutions on that problem in javascript. The second function should only be ignited if we get the first function' response.
            – Zollie
            5 hours ago


















          • Thank you for your time @Zollie. I tested your function and it works with a small addition. After the echo new JResponseJson must call die() or JFactory::getApplication()->close(); because it will return html instead of the JSON response. As you already said, only the first if is enough, if the session has expired then since the function is not called at all. I will post a new answer with the complete working code and comments for future searches if is ok with you.
            – mixahlos
            16 hours ago










          • I'm happy that it helped you in solving the problem. I also used jexit() after the invalid token jsonresponse (I just put it as a comment in the code), so I agree with you on this too, it should be closed this way or that way with a required response. :)
            – Zollie
            16 hours ago










          • After a lot of testing it is not working properly. This is because of the asynchronous nature of ajax. When making the ajax call to check the session, the rest of the code is still running. So the next ajax call is also being called and returns before the checkSession. This is happening in most of the times, this results the error message from the next ajax call (the original one) to be displayed before the alert or (reload in my case) if the session has expired, so this takes us back to the original problem.
            – mixahlos
            9 hours ago










          • I see your point and I do not want to start a long session here in comments :) , but you should restructure your javascript/jQuery script because of the nature of javascript. There are at least 3 different solutions on that problem in javascript. The second function should only be ignited if we get the first function' response.
            – Zollie
            5 hours ago
















          Thank you for your time @Zollie. I tested your function and it works with a small addition. After the echo new JResponseJson must call die() or JFactory::getApplication()->close(); because it will return html instead of the JSON response. As you already said, only the first if is enough, if the session has expired then since the function is not called at all. I will post a new answer with the complete working code and comments for future searches if is ok with you.
          – mixahlos
          16 hours ago




          Thank you for your time @Zollie. I tested your function and it works with a small addition. After the echo new JResponseJson must call die() or JFactory::getApplication()->close(); because it will return html instead of the JSON response. As you already said, only the first if is enough, if the session has expired then since the function is not called at all. I will post a new answer with the complete working code and comments for future searches if is ok with you.
          – mixahlos
          16 hours ago












          I'm happy that it helped you in solving the problem. I also used jexit() after the invalid token jsonresponse (I just put it as a comment in the code), so I agree with you on this too, it should be closed this way or that way with a required response. :)
          – Zollie
          16 hours ago




          I'm happy that it helped you in solving the problem. I also used jexit() after the invalid token jsonresponse (I just put it as a comment in the code), so I agree with you on this too, it should be closed this way or that way with a required response. :)
          – Zollie
          16 hours ago












          After a lot of testing it is not working properly. This is because of the asynchronous nature of ajax. When making the ajax call to check the session, the rest of the code is still running. So the next ajax call is also being called and returns before the checkSession. This is happening in most of the times, this results the error message from the next ajax call (the original one) to be displayed before the alert or (reload in my case) if the session has expired, so this takes us back to the original problem.
          – mixahlos
          9 hours ago




          After a lot of testing it is not working properly. This is because of the asynchronous nature of ajax. When making the ajax call to check the session, the rest of the code is still running. So the next ajax call is also being called and returns before the checkSession. This is happening in most of the times, this results the error message from the next ajax call (the original one) to be displayed before the alert or (reload in my case) if the session has expired, so this takes us back to the original problem.
          – mixahlos
          9 hours ago












          I see your point and I do not want to start a long session here in comments :) , but you should restructure your javascript/jQuery script because of the nature of javascript. There are at least 3 different solutions on that problem in javascript. The second function should only be ignited if we get the first function' response.
          – Zollie
          5 hours ago




          I see your point and I do not want to start a long session here in comments :) , but you should restructure your javascript/jQuery script because of the nature of javascript. There are at least 3 different solutions on that problem in javascript. The second function should only be ignited if we get the first function' response.
          – Zollie
          5 hours ago










          up vote
          2
          down vote













          To get the session state, you can use the following:



          JFactory::getSession()->getState();


          I'm not sure if this script is inline or a separate file. If it's inline then you can simply add the following to your Javascript:



          var sessionState = '<?php echo JFactory::getSession()->getState(); ?>';
          if (sessionState === 'expired') {
          // redirect to login page
          }


          On a side note, the use of .success() and .error() are deprecated in jQuery. Please use .done() and .fail(). Also, just so you know, .then() will not work in IE11.






          share|improve this answer





















          • This looks like a more workable solution to this question, simpler and better than what I wrote few minutes after this... :) upvoted
            – Zollie
            yesterday










          • Actually this isnt a good solution as it doesnt check when the button is clicked. It checks on page load. Your anawer does the trick properly so I'll delete this
            – Lodder
            yesterday










          • From this approach you are right. But I don't know why, I just liked the simple approach of your answer. I would leave that here any way, it's still very good for reference in other session checking cases for later researchers.
            – Zollie
            yesterday










          • It would be great if it was working. Really clean simple with just a few lines of code. Unfortunately as already said is not working in the click listener. Thank you
            – mixahlos
            16 hours ago















          up vote
          2
          down vote













          To get the session state, you can use the following:



          JFactory::getSession()->getState();


          I'm not sure if this script is inline or a separate file. If it's inline then you can simply add the following to your Javascript:



          var sessionState = '<?php echo JFactory::getSession()->getState(); ?>';
          if (sessionState === 'expired') {
          // redirect to login page
          }


          On a side note, the use of .success() and .error() are deprecated in jQuery. Please use .done() and .fail(). Also, just so you know, .then() will not work in IE11.






          share|improve this answer





















          • This looks like a more workable solution to this question, simpler and better than what I wrote few minutes after this... :) upvoted
            – Zollie
            yesterday










          • Actually this isnt a good solution as it doesnt check when the button is clicked. It checks on page load. Your anawer does the trick properly so I'll delete this
            – Lodder
            yesterday










          • From this approach you are right. But I don't know why, I just liked the simple approach of your answer. I would leave that here any way, it's still very good for reference in other session checking cases for later researchers.
            – Zollie
            yesterday










          • It would be great if it was working. Really clean simple with just a few lines of code. Unfortunately as already said is not working in the click listener. Thank you
            – mixahlos
            16 hours ago













          up vote
          2
          down vote










          up vote
          2
          down vote









          To get the session state, you can use the following:



          JFactory::getSession()->getState();


          I'm not sure if this script is inline or a separate file. If it's inline then you can simply add the following to your Javascript:



          var sessionState = '<?php echo JFactory::getSession()->getState(); ?>';
          if (sessionState === 'expired') {
          // redirect to login page
          }


          On a side note, the use of .success() and .error() are deprecated in jQuery. Please use .done() and .fail(). Also, just so you know, .then() will not work in IE11.






          share|improve this answer












          To get the session state, you can use the following:



          JFactory::getSession()->getState();


          I'm not sure if this script is inline or a separate file. If it's inline then you can simply add the following to your Javascript:



          var sessionState = '<?php echo JFactory::getSession()->getState(); ?>';
          if (sessionState === 'expired') {
          // redirect to login page
          }


          On a side note, the use of .success() and .error() are deprecated in jQuery. Please use .done() and .fail(). Also, just so you know, .then() will not work in IE11.







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered yesterday









          Lodder

          23.1k32771




          23.1k32771












          • This looks like a more workable solution to this question, simpler and better than what I wrote few minutes after this... :) upvoted
            – Zollie
            yesterday










          • Actually this isnt a good solution as it doesnt check when the button is clicked. It checks on page load. Your anawer does the trick properly so I'll delete this
            – Lodder
            yesterday










          • From this approach you are right. But I don't know why, I just liked the simple approach of your answer. I would leave that here any way, it's still very good for reference in other session checking cases for later researchers.
            – Zollie
            yesterday










          • It would be great if it was working. Really clean simple with just a few lines of code. Unfortunately as already said is not working in the click listener. Thank you
            – mixahlos
            16 hours ago


















          • This looks like a more workable solution to this question, simpler and better than what I wrote few minutes after this... :) upvoted
            – Zollie
            yesterday










          • Actually this isnt a good solution as it doesnt check when the button is clicked. It checks on page load. Your anawer does the trick properly so I'll delete this
            – Lodder
            yesterday










          • From this approach you are right. But I don't know why, I just liked the simple approach of your answer. I would leave that here any way, it's still very good for reference in other session checking cases for later researchers.
            – Zollie
            yesterday










          • It would be great if it was working. Really clean simple with just a few lines of code. Unfortunately as already said is not working in the click listener. Thank you
            – mixahlos
            16 hours ago
















          This looks like a more workable solution to this question, simpler and better than what I wrote few minutes after this... :) upvoted
          – Zollie
          yesterday




          This looks like a more workable solution to this question, simpler and better than what I wrote few minutes after this... :) upvoted
          – Zollie
          yesterday












          Actually this isnt a good solution as it doesnt check when the button is clicked. It checks on page load. Your anawer does the trick properly so I'll delete this
          – Lodder
          yesterday




          Actually this isnt a good solution as it doesnt check when the button is clicked. It checks on page load. Your anawer does the trick properly so I'll delete this
          – Lodder
          yesterday












          From this approach you are right. But I don't know why, I just liked the simple approach of your answer. I would leave that here any way, it's still very good for reference in other session checking cases for later researchers.
          – Zollie
          yesterday




          From this approach you are right. But I don't know why, I just liked the simple approach of your answer. I would leave that here any way, it's still very good for reference in other session checking cases for later researchers.
          – Zollie
          yesterday












          It would be great if it was working. Really clean simple with just a few lines of code. Unfortunately as already said is not working in the click listener. Thank you
          – mixahlos
          16 hours ago




          It would be great if it was working. Really clean simple with just a few lines of code. Unfortunately as already said is not working in the click listener. Thank you
          – mixahlos
          16 hours ago


















           

          draft saved


          draft discarded



















































           


          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fjoomla.stackexchange.com%2fquestions%2f23792%2fhow-to-check-jsession-in-javascript%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

          SQL update select statement

          'app-layout' is not a known element: how to share Component with different Modules