简体   繁体   中英

PHP Function called from javascript

I am trying to make a simple web GUI for a Raspberry Pi. It is supposed to draw a temperature value on an image using php and JavaScript.

I will use some IPC between PHP and a C++ application I am writing. But right now I just want to read a value from a file and draw it on the image. (The file is a temperature value from a 1wire bus using OWFS)

My problems

  • The JavaScript function ReadTemps() gets called every 5 seconds, but the PHP values only gets updated when the page refreshes.

  • I have NO experience in JavaScript.

The code

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <title>Still life web application</title>
    <canvas id="myCanvas" width="768" height="576" style="border:0px solid #d3d3d3;">
    Your browser does not support the HTML5 canvas tag.</canvas>

    <?php
            function get_temp()
            {
                    echo round( floatval( file_get_contents( '/mnt/1wire/uncached/vessel/temperature' ) ), 2 );
            }
    ?>

    <script>
            var bgImg = new Image();
            bgImg.src = 'image.jpg';

            function ReadTemps()
            {
                    var vessel_temp = '<?php get_vessel_temp();  ?>';

                    var c = document.getElementById( "myCanvas" );
                    var ctx = c.getContext( "2d" );

                    ctx.drawImage( bgImg, 0, 0 );

                    ctx.font="20px Georgia";
                    ctx.fillText( vessel_temp + '\u00B0', 330, 430 );

                    setTimeout( ReadTemps, 5000 );
            }
            window.onload = ReadTemps;
    </script>
</head>
<body>
    <a href="javascript:ReadTemps();">Update</a>
</body>
</html>

If I add an alert("hello") in ReadTemps it pops up every 5 seconds.

The solution

<script>
    var bgImg = new Image();
    stillImg.src = 'image.jpg';

    function ReadTemps()
    {
        var vessel_temp = loadXMLDoc( 'get_vessel.php' );

        var c = document.getElementById( "myCanvas" );
        var ctx = c.getContext( "2d" );

        ctx.drawImage( bgImg, 0, 0 );

        ctx.font="20px Georgia";
        ctx.fillText( vessel_temp + '\u00B0', 330, 430 );

        setTimeout( ReadTemps, 5000 );
    }

    function loadXMLDoc( file )
    {
        var xmlhttp;
        if( window.XMLHttpRequest )
            xmlhttp = new XMLHttpRequest();
        else
            xmlhttp = new ActiveXObject( "Microsoft.XMLHTTP" );

        xmlhttp.open( "GET", file, false );
        xmlhttp.send( null );

        if( xmlhttp.readyState == 4 && xmlhttp.status == 200 )
            return xmlhttp.responseText;
        else
            return "error";
    }
    window.onload = ReadTemps;
</script>

The answer is simple, you must use AJAX instead include PHP code inside Javascript, you must to create a php file (get_temp.php) and get it contents with an AJAX call.

First, create the get_temp.php file:

<?php // get_temp.php
print round( floatval( file_get_contents( '/mnt/1wire/uncached/vessel/temperature' ) ), 2 );
die;
?>

Second, adapt your Javascript code to do AJAX calls:

<script>
var bgImg = new Image();
bgImg.src = 'image.jpg';

function ReadTemps() {
    loadXMLDoc('get_temp.php'); 
    setInterval(loadXMLDoc, 5000, 'get_temp.php');
}

function ShowTemp(temp){
    var c = document.getElementById( "myCanvas" );
    var ctx = c.getContext( "2d" );

    ctx.drawImage( bgImg, 0, 0 );

    ctx.font="20px Georgia";
    ctx.fillText( temp + '\u00B0', 330, 430 );
}

function loadXMLDoc(file) {
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
                ShowTemp(xmlhttp.responseText);
        }
    }
    xmlhttp.open("GET",file,true);
    xmlhttp.send();
}

        window.onload = ReadTemps;
</script>

As you can see, I added a loadXMLDoc to your code, this function do the AJAX call to any file in your server.

Of course, you can use jQuery to do the same but it increases the client-side time to load and if you only need to do an AJAX call is completely unnecessary.

Hope it helps!

What you want is achieved by using AJAX. With AJAX you can call a PHP script, which will be executed and return a value to the already loaded site. This value can then be processed with javascript. Therefore you can call the PHP script every 5 seconds and process the value.

To understand how to do this exactly have a look @ MDN

What you want to do is execute your PHP function get_vessel_temp() every five seconds.

Your issue is that the PHP code is only executed once, on the server side. It can not be executed directly on the client side.

You have two solutions : either your function isn't really complicated (no database call, or else ?), and then you can rewrite it in Javascript. Or you'll have to perform AJAX calls.

AJAX allows you to perform a request, from the client browser to the server (to a PHP file, in your case). You can find infos here : https://api.jquery.com/jQuery.ajax/

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