-1

sub1 is not working it is being called on the click of the button can use please help me how can i get values from php variables to javascript variable,

<html>
<head>
<script language="javascript">

 function sub1()
 {
     var x=<?php echo $present; ?>;
     var y=<?php echo $min; ?>;
     var z=<?php echo $max; ?>;
     change(x,y,z);

     alert("hello");
     change();
  }


  function change(var no,var min,var max)
  {
       alert("hello1");
       var x=document.getElementById("show");
       x.src='<?php
           if($con==true)
           {
               $cmd="select * from showcase where item_no=3";
               if($res=$con->query($cmd))
               {
                    if($res->num_rows>0)
                    {
                        while($rw=$res->fetch_array())
                        {
                             echo "$rw[1]";
                        }
                    }
                    else
                    {
                        echo "no record found";
                    }
               }
               else
               {
                   echo "query problem";
               }
           }
       ?>'; 
   }
</script>
</head>
</html>

i am working on a slider which changes pic on the click of the button

7
  • you need to enclose the php code within quotes in js .like this var x="<?php echo $present; ?>"; Commented Jul 23, 2013 at 9:19
  • What is the actual output of the code? Commented Jul 23, 2013 at 9:21
  • The right way to pass PHP variables into JS is var x = <?php echo json_encode($present); ?>;. Not wrapping it in quotes. Commented Jul 23, 2013 at 9:22
  • @DCoder Yes, for arrays and objects you have to use json_encode, but it's perfectly ok to use quotes for simple types. Commented Jul 23, 2013 at 9:51
  • @HeinAndréGrønnestad: Where "simple types" are "a number", "boolean true" and "a string that does not contain special characters such as newlines or double quotes". As I see it, it's easier to use json_encode all the time instead of thinking "do I echo this or encode it first?". Commented Jul 23, 2013 at 10:19

1 Answer 1

3

Edit based on suggestion from @DCoder:

You should use json_encode() which is able to output arrays, objects and complex strings safely:

var x=<?php echo json_encode($present); ?>;

You could also just wrap the PHP output in quotes, but you would have to have full control over the contents of the variable. If you know that the variable is always going to be a number, a boolean value or a simple string without quotes, that should be safe too.

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

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.