简体   繁体   中英

how to fix passing the value of a PHP variable to a javascript variable

The challenge is how to get a certain PHP variable ($length) that contains the length of a message (stored in a MYSQL-database) to get passed to a javascript variable (var = length) in order to let javascript decide whether or not to show a certain marquee on a HTML-page.

I am preparing a website for a primary school. On specific pages they would like to have a marquee, showing some latest or urgent messages to the parents. If you look at the page www.transitum.org/try_1 you see an example of such a marquee. If you look at the page www.transitum.org/try_2 you see a copy of the previous page, with the difference that the marquee is still there but on this page no message is shown.

Both marquees are generated with an iframe, which has as disadvantage that when no message is shown, the iframe still will occupy some vertical height. Ideally I would like the iframe not to be visible at all when no message (content) is offered.

The messages that are shown to the parents are taken from a MYSQL-database via a PHP-script. Part of this PHP-script is to also derive the length of each message (this is done with: $length = strlen($result[.....]);) and echo the result (as echo json_encode($length);) to allow further processing with a JSON/AJAX script.

The javascript itself to check via an if else statement whether a message is there (so length > 0 and thus showing the iframe) or whether no message is there (so length = 0 and thus not showing the iframe) is running flawlessly.

The challenge is how to get a certain PHP variable ($length) that contains the length of a message (stored in a MYSQL-database) to get passed to a javascript variable (var = length) in order to let javascript decide whether or not to show a certain marquee on a HTML-page.

On www.transitum.org/try_3 I am running the following script.

<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
       $.ajax({
            type:'POST',
            url:'https://www.transitum.org/linski_nach/check3.php',
            dataType: "json",
            data:{length:length},
            success:function(data){
                console.log(data);
                if(data.status == 'ok'){
                var length = JSON.parse(length);
                } else {}
            }
        });
    });

document.write(length);

</script>

If I look in the console-log then the number "53" is shown, which indeed is the correct value of the length of the message that is shown on page Try 1 . However the above script always gives me "0".Thus I am not able to let javascript "detect" whether a message is there Yes / No and if an iframe needs to be shown Yes / No.

2019-08-26: All the 3 answers gave me good insights how the mechanism of transferring the value of a php variable to a javascript variable works.

@Halfer: I will open a separate topic for the last step to get my issue solved. At this place, for now, I will only add the modified script and two links that show that the code that Mr. Polywhirl has provided basicly is working. His following code (with an if else javascript addition) is entered in a HTML-page.


<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {
  $.ajax({
    type: 'POST',
    url: 'https://www.transitum.org/linski_nach/check3.php',
    dataType: "json",
    data: { length: length },
    success: function(data, textStatus, jqXHR) {
      console.log(data); // 53
      if (textStatus === 'success' && jqXHR.readyState === 4) {
        length = JSON.parse(data); // Set the global variable
        if(length <1)
        {
            document.write(length);            
            document.write('<table><td>no message available</td></table>');
        }
        else
        {
            document.write(length);
            document.write('<iframe src="https://www.transitum.org/linski_nach/test3.php" width="100%" height="55" border="no" scrolling="no"></iframe>');
        }
        } else {
        // Do nothing...
      }
    }
  });
});
</script>

At present, via the link Try_5 , the length of the message and the message self is displayed.

At present, via the link Try_6 , the length of the message and the message itself (only the announcement that there is no message) is displayed.

The only issue now is that the HTML-page itself is not displayed any longer .... I am trying to find out how to get my HTML page as can be seen via Try 1 . Any suggestions are highly appreciated.

You are writing the length to the page before the asynchronous Ajax call is completed.

Also, you are incorrectly using the success function.

 var length = 0; // Global value $(document).ready(function() { $.ajax({ type: 'POST', url: 'https://www.transitum.org/linski_nach/check3.php', dataType: "json", data: { length: length }, success: function(data, textStatus, jqXHR) { console.log(data); // 53 if (textStatus === 'success' && jqXHR.readyState === 4) { length = JSON.parse(data); // Set the global variable } else { // Do nothing... } document.write(length); // Write out global length value } }); }); 

You could output the variable straight into the script with echo .
But be sure to check what kind of value has been outputted by PHP.

<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">

// Variable for example
$length = 53;

$(document).ready(function(){
    $.ajax({
        type:'POST',
        url:'https://www.transitum.org/linski_nach/check3.php',
        dataType: "json",
        data:{
            length: <?php echo $length; ?> // Output variable in length property
        },
        success:function(data){
            console.log(data);
            if(data.status == 'ok'){
                var length = JSON.parse(length);
            } else {}
        }
    });
});

document.write(length);

</script>

Or when you have multiple variables to pass, like an associative array, try to convert it to JSON first, then echo it and parse it back to JavaScript.

<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">

// Array for example
$vars = array(
   'length'   => 53,
   'string'   => 'text',
   'bool'     => true
);

// Encode to JSON
$json = json_encode( $vars );

$(document).ready(function(){
    $.ajax({
        type:'POST',
        url:'https://www.transitum.org/linski_nach/check3.php',
        dataType: "json",
        data: JSON.parse(<?php echo $json; ?>), // { length: 53, string: 'text', bool: true }
        success:function(data){
            console.log(data);
            if(data.status == 'ok'){
                var length = JSON.parse(length);
            } else {}
        }
    });
});

document.write(length);

</script>

So PHP can variables can only be outputted with echo in an inline script. If you have multiple variables to use in JavaScript you could create an inline script, output all your variables into JS and use them in other scripts.

If the console.log has the right number, try this

var length = data;
<script src="https://code.jquery.com/jquery-1.11.0.min.js"></script>
<script type="text/javascript">

$(document).ready(function(){
    $.ajax({
        type:'POST',
        url:'https://www.transitum.org/linski_nach/check3.php',
        dataType: "json",
        data:{length:length},
        success:function(data){
            console.log(data);
            var length = data;
        }
    });
});

document.write(length);

</script>

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