0

There is a link on my menu that send a user to a page where, if he used that specific link, triggers an action (it adds a class to a div element).

Right now I'm doing it with php with a link like : /mypage.php?action=go
and on mypage.php I check with php with : if(isset($_GET['action']) && $_GET['action'] == go) and then the php code is executed

However I would like to do this in a JS equivalent, so instead of php I'd be able to trigger a JQuery action. I'm not very experienced with JS/JQuery, how can I do that properly ?

the script JS script that would be trigger is something along

$("#div1").toggleClass("class-triggered");
apatik
  • 383
  • 4
  • 17

2 Answers2

1

Use sessionStorage to have something stateful in client-side :

  • The first page : sessionStorage.setItem('prop1','value1');.

  • The second page includes:

    var getParamValue=function(param) {
           var v = window.location.search.match(new RegExp('(?:[\?\&]'+param+'=)([^&]+)'));
           return v ? v[1] : null;
       }
    if(sessionStorage.getItem('prop1')==='value1' && getParamValue('action')==='go'){
          //
          $("#div1").toggleClass("class-triggered");
    
     }
    

Dont forget to run this code after loading the whole page , specially : #div1.

$(()=>{
    //your code here after load page 
    // Thus, code above should be copy/past here
});
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
  • if he visits the page without the url params the above will still be true. – chchrist Aug 30 '16 at 16:55
  • Thanks for your answer ! How would this work ? is it just sent to the next page or is it conserved client-side for the whole session ? edit : chchrist is right ! this is very likely to happen since the link in question is in the website's menu (in every page) – apatik Aug 30 '16 at 16:57
  • You could drop the `sessionStorage` bit. Parsing the query parameters for `action=go` will do the trick, and it satisfies the desire to keep it in the JS. You wouldn't have to add anything in the PHP code. – Chad Aug 30 '16 at 17:08
0

I think the way you're doing it is the best. If you do anything with cookies or client-side storage, the user has to have that enabled in their settings, and you have to remember to delete the cookie or storage item afterwards.

Chad
  • 693
  • 5
  • 17
  • Indeed, the problem is that it looks very complicated and messy to trigger a JQuery script with the php $_GET['action'] – apatik Aug 30 '16 at 17:00
  • 1
    I wouldn't worry about how it looks. Focus on how it works, and keep it simple. Query parameters are transient by nature, and I think that's exactly what you want here. – Chad Aug 30 '16 at 17:01