0

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 Answer 1

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"},
Sign up to request clarification or add additional context in comments.

5 Comments

Woops my mistake there Jeff. I made a little typo. My default value is 'false' and not 'true'.
you could just toggle the state everytime the notificationCall function is called. I've updated my answer with a possible solution
This does not use the Ajax right? The session value should only be changed to 'true' when clicked on a button. And the default value always has to be 'false'.
ah, I think you're missing the function call inside your ajax request data action: "notificationCall"
Hi Jeff, your last comment seems do have done the trick! I had to specify the action inside of data. Thanks very much for the help!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.