How to run JavaScript with PHP variables

I am trying to run JavaScript code with PHP variables.

This is fine in HTML. The script runs and the subpage is loaded into the content (div).

But when I try to run the script with PHP variables, it only shows me a subpage.

Original script:

<script type="text/javascript" language="javascript">
    $(document).ready(function() {
        $("#ex").click(function(event){
            $("#content").load('example.html');
            return false;
        });
    });
</script>

      

With PHP:

<script type="text/javascript" language="javascript">
    $(document).ready(function() {
        $("#"<?php $link[1] ?>).click(function(event) {
            $("#content").load('<?php $link[0] ?>');
            return false;
        });
    });
</script>

      

where

<?php
    $links = array(
        $link = array('example.html', 'ex', 'Example')
    );

    foreach ($links as $value => $link)
    {
        echo '<li><a href=subpage/' . $link[0].id=' . $link[1] . '>' . $link[2] . '</a><li>';
    }

      

UPDATE:

When I only use JavaScript and HTML, https://drive.google.com/file/d/0B1WsoN01_VlbQ3lWczZrbnh0TnM/view

When I use PHP variables and an array of links, https://drive.google.com/file/d/0B1WsoN01_Vlbc2VjVUVrWldIZ1U/view

+2


source to share


6 answers


Change the code as follows:



<script type="text/javascript" language="javascript">
    $(document).ready(function(){
        $("#" + <?php echo $link[1] ?>).click(function(event){
        $("#content").load('<?php echo $link[0] ?>');
        return false;
        });
    });
</script>

      

0


source


You are not defining an array here.

$links = Array(
   $link = array('example.html', 'ex', 'Example')
);

      

I think one array is enough for this case. Do -

$links = array('example.html', 'ex', 'Example');

      

Then this should work -

$("#content").load('<?php echo $links[0] ?>');

      



Update

php -

echo '<li><a href=subpage/'.$link[0].' id='.$link[1].' class="ex-links">'.$link[2].'</a><li>';

      

js -

<script type="text/javascript" language="javascript">
    $(document).ready(function(){
    $('ex-links').click(function(event){
    event.preventDefault();
    $("#content").load($(this).attr('href'));
    return false;
    });
    });
</script>

      

0


source


Try using this instead

<script type="text/javascript" language="javascript">
    $(document).ready(function(){
        $(<?php echo '"#' . $link[1]'"'; ?>).click(function(event){
            $("#content").load(<?php echo "'" . $link[0]."'"; ?>);
            return false;
        });
    });
</script>

      

Please see if this continues.

0


source


Change your code to this:

<script type="text/javascript" language="javascript">
    $(document).ready(function(){
        $("#<?php echo $link[1]; ?>").click(function(event){
            $("#content").load('<?php echo $link[0] ?>');
            return false;
        });
    });
</script>

      

See, I also fixed the quotes in the first PHP echo.

0


source


The PHP code is buggy and it also mixes up the hyperlink attributes (HREF and id), mix up the jQuery selector, and in addition I'm puzzled why the tag should contain both a link in a

the href attribute and a load event for the onclick event.

This begs the question: have you checked the output and don't know what the syntax should be?

The relative complexity of what you are doing here, compared to the obvious numerous errors in the output, suggests that you really should first learn the correct syntax and check the output in the debugger (browser developer tools).

Below works well with me. I am assuming you are not trying to load a complete HTML page into a div element. The href attribute can also be empty or href = "#" as it doesn't make sense.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
        <title>Untitled Document</title>
    </head>

    <body>
        <?php
            $links = Array(
                $link = array('content.txt', 'ex', 'Example')
            );

            foreach ($links as $value => $link)
            {
                echo "<li><a href='{$link[0]}' id='{$link[1]}'>{$link[2]}</a></li>";
            }
        ?>

        <script type="text/javascript">
            $(document).ready(function(){
                $("#<?php echo $link[1] ?>").click(function(event){
                    $("#content").load('<?php echo $link[0] ?>');
                    return false;
                });
            });
        </script>
        <div id="content"></div>
    </body>
</html>

      

0


source


The best approach when you want to add PHP to JavaScript is to put all the PHP information in an array and then json_encode to the HTML element layout as shown in the example.

IMPORTANT: Do not add sensitive information $phpInfo

because it #hold-php-data

will be visible in developerTools until the JavaScript code is loaded and jQuery removes it.

<!doctype html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  </head>

  <body>

    <?php
      $phpInfo = array();

      $links = array(
        array('example.html', 'ex', 'Example'),
        array('example.html', 'ex', 'Example-2'),
      );

      // Add $links to $phpInfo

      if (!isset($phpInfo['links'])){
        $phpInfo['links'] = array();
      }

      $phpInfo['links'] = $links; // Now we have $links in our "global" variable
    ?>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


    <script id="hold-php-data" data-php='<?php echo json_encode($phpInfo); ?>'></script>

    <script>
      $(function() {

        var mockupElement = $('#hold-php-data');

        // Get the JSON data from attribute and convert it to a valid object
        var phpInfo = JSON.parse(mockupElement.attr('data-php') || []);

        // We can safely remove the mockupElement since we have the
        // data so it won't be exposed to the user later on.
        mockupElement.remove();

        // Now you can access the links as phpInfo.links

        console.log('data from PHP', phpInfo);
      });
    </script>

  </body>

</html>
      

Run codeHide result


0


source







All Articles