Changing the value of a session with Ajax in Wordpress not working

时间:2016-04-21 22:23:52

标签: php jquery ajax wordpress

I´m kind of new to using Ajax but I am trying to update the value of a session using Ajax. The Ajax call shoud fires when clicked on a button.

When I click on this button it also returns the succes function. I am using Wordpress with this Ajax call.

Currently this is my code:

Ajax call:

$('.button').click(function(){
    $.ajax({
                type: "POST", 
                url: "/wp-admin/admin-ajax.php", 
                data: {click: "true"},
                success: function() { 
                    alert('bro it worked!'); 
                }
            }); 
}); 

functions.php in Wordpress: session_start();

function notificationCall() { 
  $_SESSION['clicked'] = $_POST['click']; 
  die(); 
}

add_action('wp_ajax_notificationCall', 'notificationCall');
add_action('wp_ajax_nopriv_notificationCall', 'notificationCall');

echo $_SESSION['clicked']; 

So my Ajax call returns the succes function containing a string with "Bro it worked". However, my session always stays my same default value of "false".

Any ideas?

1 个答案:

答案 0 :(得分:1)

the reason it's always true is because your ajax post data data: {click: "true"} is hardcoded to true, and since that's what you're setting the value of it with $_SESSION['clicked'] = $_POST['click'];, then it will always be true.

one solution might be to hard code a toggle in there:

function notificationCall() {
  if ($_SESSION['clicked'])
     $_SESSION['clicked'] = false;
  else
     $_SESSION['clicked'] = true;
  die(); 
}

update

I think you'll need to specify the php function to call inside your ajax request data, so that should look something like this:

data: {action: "notificationCall", click: "true"},