简体   繁体   中英

Javascript generated in PHP is not executing

I'm trying to create a roulette system, which should work as follows: The user clicks on a submit button, which is then checked on the opening_case_handler.php file to see whether the user has sufficient funds in his account or not, and if he does it will echo javascript code which will create the animation for the roulette and will also come out with the winning prize. For security purposes I am executing the js code in php so the user has no access to it since it is executed in the server side.

The issue here is that the js and jquery code do not get executed once this line of code has been reached:

var gw = $(".gift").outerWidth(true);

in the opening_case_handler.php .

You will notice that there are two alerts before and after the previous line code I have just mentioned. If I uncomment alert("TEST1") it will get executed and an alert message will appear however the rest of the code will no be executed. Also if I uncomment only the alert("TEST2") it will not be executed and nothing will happen.

To make sure that the javascript code actually works. I previously tested it in a javascript file and sourced it in the index.php file and it worked perfectly.

index.php

This page contains the roulette with all the different images of each item. The submit button is at the bottom. This is the button that users will click to be able to spin the roulette.

    <div class='rafflebox'>
      <div class='pointer'></div>
      <div class='boxwrapper'>
        <ul class='giftwrapper'>

          <div class="gift item bg-size2 box-bg3">
              <img class="item-product2" src="graphics/mouse.png" draggable="false">
          </div>

          <div class="gift item bg-size2 box-bg2">
              <img class="item-product2" src="graphics/mouse.png" draggable="false">
          </div>

          <div class="gift item bg-size2 box-bg3">
              <img class="item-product2" src="graphics/mouse.png" draggable="false">
          </div>

          <div class="gift item bg-size2 box-bg4">
              <img class="item-product2" src="graphics/mouse.png" draggable="false">
          </div>


        </ul>
      </div>
    </div>

    <form  method="post">
      <button type="submit" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
    </form>

  </div>

opening_case_handler.php

<?php
session_start ();

if(isset($_POST['opening_case']))
{
 opening_case ();

} 

function opening_case ()

{

if ($_SESSION['balance'] >= $_SESSION['box price'])

  {
    echo '
    <script>
      //alert("TEST1");
      var giftamount = 10;
      var gw = $(".gift").outerWidth(true);
      //alert("TEST2");
      var giftcenter = gw/2;
      var cycle = 7;

      var containercenter = $(".boxwrapper").outerWidth(true)/2;
      for(var i = 0; i <=5; i++)
        {
          var giftduplicate = $(".giftwrapper").children().clone(true,true);
           $(".giftwrapper").append(giftduplicate);
        }

      $(".button").click(function()
      {
            alert("You DO have sufficient funds");
            var btn = $(this);
            btn.hide();
            var randomgift = Math.floor(Math.random() * 4) + 1;
            var dev = Math.random()*(giftcenter+1);
            var distance = giftamount *  cycle * gw   + (randomgift*gw) - containercenter -24 +dev;

            console.log(distance);

            $( ".giftwrapper" ).css({left: "0"});

            $(".giftwrapper").animate({left: "-="+distance},10000,function()
              {
                alert("You Won Gift" + randomgift);
                btn.show();
              });

    });


    </script>';

   } else {

    //to be done

  }
}


?>

Please feel free to express your ideas on how this type of system should be better built. I am open to all suggestions, I am fairly new to this.

Thank you!!

Try using Heredoc string quoting example for printing your JavaScript:

$str = <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;

Heredoc text behaves just like a double-quoted string, without the double quotes. This means that quotes in a heredoc do not need to be escaped, but the escape codes listed above can still be used. Variables are expanded, but the same care must be taken when expressing complex variables inside a heredoc as with strings.

If it is just a php code file. You can try some below.

<?php

echo "some stuff here" 

if ($condition){ ?>

<script>
alert("condition true");
</script>

<?php } else { ?>

<script>
alert("condition false");
</script>


<?php }?>

When a form gets submitted it redirects you to the PHP page (ie when you click submit in index.php you will get redirected to opening_case_handler.php ) and then the PHP page will send you back to the index page with the new info. Thus, your javascript code gets printed in the opening_case_handler.php which is why your javascript did not get executed. Also, your javascript code will always be visible unless if you do something really creative so if you are trying to handle any sensitive information do it in PHP or any backend framework you are using.

There are ways to fix this issue but I would recommend a different approach to solve this issue. You can use an AJAX request which basically works in the following manner:

  1. You send a request to your PHP server with the data you want to send.
  2. Your PHP server will process the request and send it back to you
  3. Your Javascript code will process the result and show the animations or whatever you want to do.

    This way your algorithm is not shown and your client ( the javascript side ) only handles information entered by the user and the results came from the server.

In your case, we can do that using the following changes

Index.php (which can be changed to index.html now)

  <button type="submit" id="opening_case" name="opening_case" class="btn open-box-btn btn-openbox-font button"><img id="lock" src="graphics/iconos/Candado Cerrado Black.png">ABRIR CAJA</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
    $("#opening_case").on("click", ()=>{
        // $.get( "opening_case_handler.php?opening_case=true", function( data ) {
        //     console.log(data.funds)
        // });
        $.ajax({
            url: "opening_case_handler.php?opening_case=true",
            success: (data)=>{
                if(data.funds) {
                    alert("You DO have sufficient funds")
                } else {
                    ("You don't have sufficient funds")
                }
            },
            dataType: "JSON"
        });
    })
</script>

opening_case_handler.php

<?php

if(isset($_GET['opening_case'])) {
   $result = [
      "funds" => true,
   ];
   $ResultsInJSON= json_encode($result);
   echo $ResultsInJSON; 
} 
?>

The index.php will send the request when the button is clicked using AJAX which you can read about it here https://api.jquery.com/jquery.get/ then your PHP will receive the request and response with a JSON code which can be processed using the data.whatever as shown in the example above.

Note: I am not a PHP expert but I believe this will be a better method to use in this case.

Note2: You don't need Jquery for Ajax but it's easier! Here is how you do it without Jquery https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

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