简体   繁体   中英

PHP & JQuery passing variables

I am creating a plugin for WordPress and I have been stuck for a two days trying to figure a way of passing variables and it's values from jQuery to PHP, at the moment I have resorted to setting the boolean output of a conditional inside a cookie and then reading it with PHP in order to perform and update.

jQuery I am using activeStatus to perform some conditionals in jQuery and then i am setting a cookie in order to continue performing other set of conditionals in PHP

var activeStatus = true;
jQuery.cookie('activeStatus', true, {expires: 1, path: '/'});

PHP now we read the cookie set by jQuery and perform update

if (!isset($_COOKIE["uniqueUser"])) { //unique visitor
            if ($_COOKIE["activeStatus"] == 'true') { //if cookie found and true
                $uniqueVisitor = get_option('stats');
                $uniqueVisitor['uniqueVisits']+=1;
                update_option('stats', $uniqueVisitor);
             }

The problem now is that the second if conditional will never be performed since cookies can only be read on the second refresh, hence, the update will never take place because the cookie would have been set. for this reason I wish to pass the variable in real time.

One more thing I would like to mention is that I am using PHP to print the whole javascript ie

<?php

add_action('exec_script', 'script');
function script() {
?>

<script type="text/javascript">
//code
</script>

<?php
}

To fit my purposes I need to print the js code in the page and cannot save it in a js file.

Anyone has any ideas?

Just output your variables on the page inside a script tag like so:

<script>
  window.myvariable = "<?php $my_string ?>"
</script>

To do it the other way around I would suggest putting your variables in a post request. So if its a button the user is clicking do this:

<form action="/action.php">
  <input id="hidden_input" name="the_value" type="hidden" value="">
  <input type="submit" value="Click here to send variable">
</form>

<script>
  $("#hidden_input").value(javascript_variable);
</script>

You should set the cookie with a PHP script called with ajax. Then when you load the next page, it will already be set for the PHP script to find it. I admit I don't know the ins and outs of jquery.cookie so this may not be the answer. But this is what I'd start with.

I think you are counting the unique visitors so use

if (!isset($_COOKIE["activeStatus"]) && !isset($_COOKIE['uniqueVisitor']))) { } 

It will increase the stats for first time and not after that

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