2

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.

1
  • Daniel, Thanks for editing my code. It helps a lot. Commented Feb 26, 2015 at 5:51

1 Answer 1

3

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

3 Comments

Thanks again. It works. One more advice I am trying to check sessionValue like this if(elem.value.length > 0 && sessionValue > 0) any advice?
Don't say thanks, that blurs the information... if you're thankfull for an answer, just vote up and someday, give yourself answers to others ;)

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.