简体   繁体   中英

codeigniter trying to access session data from view using javascript

Framework: CodeIgniter 2.0

I am trying access session data setup in model from view.

This is the code I am testing in view:

<script type='text/javascript'>
  function notEmpty(elem, helperMsg){
    var num_records = '$this->session->userdata("number_Of_Records_session")';
    alert(num_records);
    if(elem.value.length > 0){
      alert(helperMsg);
      elem.focus();
      return false;
    }else{
      window.location="/path/";
    }
    return true;
  }
</script>

When I use PHP code I could retrieve the value from session and display it.

<?php 
    $numberOfRecords_session = 
    $this->session->userdata('number_Of_Records_session');
    echo "Num records:".$numberOfRecords_session;
?>

But in javascript this line

var num_records = '$this->session->userdata("number_Of_Records_session")';

print this message in alert box:

$this->session->userdata("number_Of_Records_session")

Any advice to retrieve value in javascript and show it alert box is appreciate.

You cannot access your session (stored on server) from JavaScript (executed on client) So you have to declare a JavaScript variable and define it with PHP Like this you're defining a string :

...
<script>
var sessionValue = "<?php echo $this->session->userdata('number_Of_Records_session');?>";
</script>
...

If you're sure that there is always a number you could remove the " above, which are defining the variable as string.

If you're not sure about the datatype of the sessionValue you should use parseInt(string,radix) :

...
<script>
var sessionValue = parseInt("<?php echo $this->session->userdata('number_Of_Records_session');?>");
if(sessionValue == "NaN") sessionValue = 0;
</script>
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM