1

im newbie

how to load variable php in javascript?

this is my script (popup.php)

<?php $id_user = $this->session->userdata('id'); ?>

<script type="text/javascript">rules: {
        user: {
  required: true,
  number: true,
  range: [1, 8]
}  <script>

example variable.

$id_user = 10;

how to input a id_user to range: [1,8]

so the range output is range: [1,10]

sory for my bad english

thank you so much

BR

Puja

2 Answers 2

1

try

<script type="text/javascript">

var $uid = <?php echo json_encode($this->session->userdata('id')); ?>;
rules: {
  user: {
  required: true,
  number: true,
  range: [1, $uid]
} 
 <script>

Why json_encode? It turns the value you pass to it into valid JSON - quotes the strings, escapes quotes and other special chars, etc. Without it, you're basically going to break whenever your echoed variable contains something other than a simple alphanumeric string.

Sign up to request clarification or add additional context in comments.

3 Comments

You really should json_encode the value instead of just surrounding it with single quotes.
@DCoder i'm not very well versed in php if you see any room for edit in the anwer plz feel free to edit...
i try with or without 'json_encode' its work for me. thank you so much @DCoder,@3nigma
0

you can just use echo in php to create variables in javascript. personally I would handle this situation like this:

<?php echo "<script>var user_id = ".$this->session->userdata('id').";</script>"; ?>
<script>
  rules: {
    user: {
    required: true,
    number: true,
    range: [1, user_id]
   }
  }  
</script>

Comments

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.