0

I'm using JSON to produce some data on Wordpress which I need to store in a PHP session variable. Here's the current setup that I'm messing around with but having no luck:

jQuery(document).ready(function($) {    
    $.ajax({
    url: 'url', 
    type: 'POST',
    dataType:'json',
    data: {foo: 145},
    success: function(data){
        console.log(data);
        alert(data);
        }
    });  
});

and the PHP:

session_start(); 
$_SESSION['bar'] = $_POST['foo']; 

I can see the data in the console but nothing will display when I echo my sesh var. Using vardump returns an empty array. Where am I going wrong here?

(I realize there are plenty of other questions just like this, but believe me, I've tried them all - nada.)

user2512982
  • 11
  • 1
  • 3
  • you can't really set a php variable with javascript. When you send data over to your ajax script thats when the data becomes exposed to PHP, but you cannot set a variable from data returned back from the ajax call to a php variable. – Eli Apr 21 '14 at 23:57
  • http://stackoverflow.com/questions/19976627/posting-json-with-jquery-ajax-to-php – bovino Marcelo Bezerra Apr 21 '14 at 23:57

2 Answers2

1

Answer: You can't use javascript to store server side variables.

You must save the $_SESSION var in the PHP script that this AJAX calls. Which you have put URL?? In WordPress you can use JQuery to call a special hook which can be caught he functions.php that handles all AJAX.

There's info about this everywhere, see solution to this answer: Using AJAX in a WordPress plugin

Community
  • 1
  • 1
ptimson
  • 5,533
  • 8
  • 35
  • 53
0

You would have to set a global variable for both languages and then transfer them via javascript you could do this on every page using php includes.