0

I have a PHP class object called Datapoints stored in session and I am trying to access a variable from it in a javascript function.

From within the javascript I can access session variables through $_SESSION['foo'], but I can't access the object variables. I've tried all sorts of syntax to return the variable.

I can access variables like this, and it works fine.

<?php echo intval($_SESSION['count']); ?>

but I would rather have the whole object in session, for example if I do this...

<?php
    header("Content-Type: text/javascript");  
    session_start();  
    $c = $_SESSION['datapoints']->count;
    $c1 = $datapoints->count;
?>  
var count = <?php echo $c; ?>
var count1 = <?php echo $c1; ?>

Both return null.

My object looks like this through print_r('datapoints').

Datapoints Object ( [startdate] => 2013-06-05 [currency] => GBP [count] => 4527 [datapoints] => Array ( [0] => Datapoint Object (...) ... ))

Thanks

EDIT:

Thanks for your help, I've solved this now. Turns out it was a problem with the autoloader not loading classes properly from within the javascript files.

4
  • 1
    You can't access PHP values directly in JavaScript. You can, however, emit values to JavaScript using PHP code. There's no difference in how you'd do this between session variables vs. objects. How are you attempting this and in what way does it not work as expected? Instead of describing your code, actually show your code. Commented Feb 11, 2014 at 16:03
  • Your $_SESSION['datapoints'] is an array try $_SESSION['datapoints'][0]->count; Commented Feb 11, 2014 at 16:21
  • Tried that too, unfortunately not working. Commented Feb 11, 2014 at 16:35
  • Thanks for your help, I've solved this now. Turns out it was a problem with the autoloader not loading classes properly from within the javascript files. Commented Feb 11, 2014 at 18:12

2 Answers 2

0

FIRST LINE

@session_start();

use "echo"

var startdate = "<? echo urObject->startdate?>";
3
  • but the object is empty or not? Commented Feb 11, 2014 at 16:18
  • I have the session start and the object is there. Commented Feb 11, 2014 at 16:27
  • what show echo $_SESSION['datapoints']->count; immediately after session_start()? also null? Commented Feb 11, 2014 at 16:37
0

You CAN access PHP variables in javascript. It's simple:

    var whatever = "<?php echo your_php_variable ?>";
1
  • Thanks for your reply, but I already am using that, the problem is when the object is in session I cannot access the object variables. In your example, if I do var whatever = "<?php echo datapoints->count; ?>"; it returns null. Commented Feb 11, 2014 at 16:16

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.