Is it possible to put a part of PHP code in <script>?

时间:2015-10-06 09:00:16

标签: php

I have a php page, within is an alert like so:

<script>
alert('Stop the timer!');
</script>";

now i'd like to try/do this:

<script>
<?php echo "$test2"; ?>
alert('Stop the timer!');
</script>

(what i try to do is to give back the content of $test2 by means of the alert...)

Now this does not work. but.... it doesn't give an error message either.

so 2 questions here are:

1) is it even possible to put a part of php in the section 2) if it doesn't work why doesn't it give an error message (3) do i have to make the $test2 global? (and how to best format it if so)

thanks in advance.

 <!DOCTYPE html>
        <head>
      <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
      <script src="//code.jquery.com/jquery-1.10.2.js"></script>
      <!-- deze hieronder is nodig voor touchpad enabled sliders -->
      <script src="jquery.ui.touch-punch.min.js"></script>
      <script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
      <link rel="stylesheet" href="/resources/demos/style.css">




        <script>
    function getSelectValues(select) {
      var result = [];
      var options = select && select.options;
      var opt;

      for (var i=0, iLen=options.length; i<iLen; i++) {
        opt = options[i];

        if (opt.selected) {
          result.push(opt.value || opt.text);
        }
      }
      return result;
    }
        </script>

      <!-- accordion -->
      <script>
      $(function() {
        $( "#accordion" ).accordion({ 
            event: "click",
            active: false,
            collapsible: true,
            autoHeight: false

        });
      });
      </script>

      <script>
      $(function() {
        $( "#slider-vertical" ).slider({
          orientation: "horizontal",
          range: "min",
          min: 0,
          max: 100,
          value: 1,
          slide: function( event, ui ) {
            $( "#amount" ).val( ui.value );
          }
        });
        $( "#amount" ).val( $( "#slider-vertical" ).slider( "value" ) );
      });
      </script>
       <script>
      $(function() {
        $( "#slider-vertical2" ).slider({
          orientation: "horizontal",
          range: "min",
          min: 0,
          max: 100,
          value: 1,
          slide: function( event, ui ) {
            $( "#amount2" ).val( ui.value );
          }
        });
        $( "#amount2" ).val( $( "#slider-vertical2" ).slider( "value" ) );
      });
      </script>
        <title>Left X Right -BrainGame</title>
        <!-- Bootstrap -->
        <link href="css/bootstrap.css" rel="stylesheet">
            <script src="js/bootstrap.min.js"></script>

            <script>
      $(function() {
        $( "#datepicker" ).datepicker();
      });
      </script>
       <script>
      $(".js-example-basic-multiple").select2(); </script>

     <style type="text/css">
    p.label_checkbox_pair {
    clear: both;
    float: none;
    position: relative;
    }
    p.label_checkbox_pair input {
    left: 80px;
    position: absolute;
    top: 1px;
    }
    p.label_checkbox_pair label {
    display: block;
    margin-left: 90px;
    width: 200px;
    }
    </style>

    <script src="js/icheck.js"></script>
    <script>
    //oud $(document).ready(function(){
      //$('input').iCheck({
        //checkboxClass: 'icheckbox_polaris',
        //radioClass: 'iradio_polaris',
     // 


        //increaseArea: '20%'  optional
      //});
    //});
    $(document).ready(function(){
      $('input').each(function(){
        var self = $(this),
          label = self.next(),
          label_text = label.text();

        label.remove();
        self.iCheck({
          checkboxClass: 'icheckbox_line-blue',
          radioClass: 'iradio_line-blue',
          insert: '<div class="icheck_line-icon"></div>' + label_text
        });
      });
    });
    </script>
        <link href="skins/line/blue.css" rel="stylesheet">


        </head>

    <BODY>
    <br /><br />
    <table HSPACE="50" CELLPADDING="20">
    <tr HSPACE=50 CELLPADDING="30">
    <td>
    <?php 
    $a=array("red","blue","black","orange","green");
    $random_keys=array_rand($a,5);


    $textcolours=array('red','blue','black','orange','green');
    shuffle($textcolours);

    echo "<right><font size=6 color='$textcolours[0]' >".$a[$random_keys[0]]."<br><br></font></right>";
    echo "<right><font size=6 color='$textcolours[1]' >".$a[$random_keys[1]]."<br><br></font></right>";
    echo "<right><font size=6 color='$textcolours[2]' >".$a[$random_keys[2]]."<br><br></font></right>";
    echo "<right><font size=6 color='$textcolours[3]' >".$a[$random_keys[3]]."<br><br></font></rightr>";
    echo "<right><font size=6 color='$textcolours[4]' >".$a[$random_keys[4]]."<br><br></font></right>";
    ?>
    </td>

    <td>

      <div class="left">

         <form class="span4" action="" method="post">

      <fieldset>

        <legend>Left X Right  BrainGame</legend>

        <p halign="right" margin="10px">Name: <input type="text" name="naam" ></p>

        <p halign="right" margin="10px">Date: <input type="text" name="date" id="datepicker" ></p>

     <br>

             <?php
    if(isset($_POST['getdata'])){
    $conn=mysql_connect('localhost','t','w');
    mysql_select_db("test",$conn);

    $regexp = "/^[^0-9][A-z0-9_]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/";

    $naam=$_POST['naam'];
    $date=$_POST['date'];
    //$type=$_POST['type'];
    //$core=$_POST['core'];
    //$management=$_POST['management'];


    //$names = $tools; 
    //$output = preg_grep('/(Andrew|John)/i', $names); 
    //print_r( $output );

    //
    //http://webcheatsheet.com/php/regular_expressions.php#match
    $test = $_POST['tools'];
    $result = preg_replace('/({|:|true|}|")/', '', $test);
    $test2 = preg_grep('/(^RED|^BLACK|^BLUE|^ORANGE|^GREEN|^red|^black|^blue|^orange|^green)/i', $result);

    $tools = json_encode($test2);
    //$tools = $_POST['tools'];
    //$tools = json_encode(preg_grep('/(RED|BLACK|BLUE|ORANGE|GREEN)/i', $_POST['tools']));
    //$tools = json_encode($_POST['tools']);
    //$analytisch=$_POST['analytisch'];
    //$eneagram=$_POST['eneagram'];

    if(true == false ){
        echo "<label class='err'>All fields are required</label>";
        }

            else{
    $insert="Insert into kandidaat(naam,date,tools)
     values('".$naam."','".$date."','".$tools."')";

    $rs=mysql_query($insert) or die(mysql_error());

    ?>
    <script>
    <?php echo "$test2"; ?>
    alert('Stop the timer!');

    </script>";
    <?php }
    }
     ?>

      </fieldset>


    <div id="accordion" style="width:90%;">
      <h3>Start...</h3>
      <div>
        <p class="label_checkbox_pair">

    <!--<div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="iCheck" value="true"><label for="certs">ISTQB2</label></div>-->
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[RED]" value="true"><label>RED</label></div>
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[BLUE]" value="true"><label>BLUE</label></div>
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[BLACK]" value="true"><label>BLACK</label></div>
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[ORANGE]" value="true"><label>ORANGE</label></div>
    <div style="font-family: arial; font-size: 6px; color: #0B1DE0; vertical-align: middle;"><input style="vertical-align: middle" type="checkbox" name="certs[GREEN]" value="true"><label>GREEN</label></div>
        </p>
      </div>

      <h3>Part 2</h3>
      <div>
        <p>
        <!-- zie content website https://select2.github.io/examples.html -->
        <fieldset>
    <div><input type="checkbox" name="tools[RED]" value="true"><label>RED</label></div>
    <div><input type="checkbox" name="tools[BLUE]" value="true"><label>BLUE</label></div>
    <div><input type="checkbox" name="tools[BLACK]" value="true"><label>BLACK</label></div>
    <div><input type="checkbox" name="tools[ORANGE]" value="true"><label>ORANGE</label></div>
    <div><input type="checkbox" name="tools[GREEN]" value="true"><label>GREEN</label></div>
    </fieldset>
    </p>
        </div>

    </div>


    <br/>    <button type="submit" name="getdata" class="btn">Submit</button>
    <a href="toonkandidaat.php" class="btn btn-primary">Highscores</a>


    </form>

       </div>
       <?php 
       function save(){

        }
       ?>
    <?php
    function make_links_clickable($text){
        return preg_replace('!(((f|ht)tp(s)?://)[-a-zA-Z&#1072;-&#1103;&#1040;-&#1071;()0-9@:%_+.~#?&;//=]+)!i', '<a href="$1">$1</a>', $text);
    }
    ?>

    </td>
    </tr>
    </table>

        </body>
        </html>

3 个答案:

答案 0 :(得分:1)

Your syntax in wrong. Imagine your have saved foobar in your varibale. If you print it like you the the result will be foobar

But your printed it inside the script part so you need to assign it to a JavaScript variable. There are two possibilities to alert it.

alert("<?php echo $test; ?>");

Or

var content = "<?php echo $test; ?>";
alert(content);

答案 1 :(得分:1)

试试这个?

<script>
alert('<?php echo $test2; ?>');
</script>

alert('<?php echo $test2; ?>');

将替换为PHP变量的内容(&#34; Hello word&#34;例如),就像你写的那样:

alert('Hello word');

答案 2 :(得分:0)

Yes, it is possible due to the fact that PHP scripts are evaluated by a PHP interpreter on the Server first, before delivering plain HTML/CSS/JS to the client browser.

Anyways, it would have been faster to just go ahead and try it yourself.

For answering why it doesnt work in your case, we need more code to see how and where your variable(s) are defined.

相关问题