1

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?

2
  • looks like, for starters, you're missing including the action in your ajax call: action: 'notificationCall' will tell admin-ajax.php what function you want to run with that data.
    – Caspar
    Commented Apr 22, 2016 at 0:28
  • Hi Caspar, thanks for the comment. I've added the action: 'notificationCall' But still my session always returns false even though I clicked the button Commented Apr 22, 2016 at 6:59

1 Answer 1

1

For me, Session with ajax working with the following code snippet

add_action('init', 'start_session', 1);
function start_session(){
    if(!session_id()) {
    session_start();
    }
}

// form submition 
add_action( 'wp_ajax_nopriv_form_response', 'form_response' );
add_action( 'wp_ajax_form_response', 'form_response' );

function form_response() {
   $_SESSION['value'] = $_POST['formFiled'];
}

 //Session value
if(isset($_SESSION['value'] ))
{
    echo $_SESSION['value'];
}

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.