简体   繁体   中英

How do I edit PHP variable with JavaScript/jQuery?

I want to update a PHP variable $LinkOpen based on the current state of a checkbox element .avflipswitch .

Based on the .avflipswitch checkbox state, I want to toggle the value of my PHP variable $LinkOpen between '_blank' and '_self' so I can push that value to my Google CSE link target attribute.


What I have tried so far:

 $('.avflipswitch').on("change", function (e){ 
   if(this.checked){
     functionOne(<?php $LinkOpen = '_blank';?>);
   }
   else{
     functionTwo(<?php $LinkOpen = '_self';?>);
   }
});

<gcse:searchresults-only linktarget="<?php echo $LinkOpen;?>"></gcse:searchresults-only>

You can just push the value to a cookie using JavaScript or jQuery and then let PHP retrieve the value from that cookie like this:

JavaScript + PHP:

 /* JavaScript */ const switch = document.querySelector(".avflipswitch")[0]; switch.addEventListener("change", function(){ let blankTar = "_blank"; let selfTar = "_self"; if(this.checked){ document.cookie = "target =" + blankTar; window.location.reload(); } else{ document.cookie = "target =" + selfTar; window.location.reload(); } } /* PHP */ <gcse:searchresults-only linktarget="<?php echo $_COOKIE['target']; ?>"></gcse:searchresults-only>

jQuery + PHP:

 /* jQuery */ $('.avflipswitch').on("change", function (){ let blankTar = "_blank"; let selfTar = "_self"; if(this.checked){ document.cookie = "target =" + blankTar; window.location.reload(); } else{ document.cookie = "target =" + selfTar; window.location.reload(); } }); /* PHP */ <gcse:searchresults-only linktarget="<?php echo $_COOKIE['target']; ?>"></gcse:searchresults-only>

What you are trying is not possible in php, but very easy with jquery:

$('.avflipswitch').on("change", function (e){ 
    if(this.checked){
     $('a').attr("target","_self")
    }
    else{
     $('a').attr("target","_blank")
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM