Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to (locally) call a JavaScript function from PHP (on Raspberry Pi)

Tags:

javascript

php

I'm in a slight predicament where I can't really understand how to proceed. I've got a set-up where I'm hosting a website locally, on a Raspberry Pi which is used to send commands to a LED-donut + speaker. The website also contains a scheduler, which allows people to drag/drop music playlists and licht-scenes to a date and time. The concept is that these will be fired off automatically.

The interface on this website has several functions we can call. The point is, I'm using Cronjobs to fire off PHP scripts that will for instance grab information out of my MySQL database and use that information (date+time+string of licht-scene / audio file) to send to the LED-donut and speakers.

My issue here is that everywhere I've searched, people tell me that PHP can't access JS functions, simply because they are server-side vs client-side or that it has to be within one file.

However, all of these scripts etc. are run locally on a Raspberry Pi and I'm working on pre-existing code.

I'll show you some snippets:

A function I would like to call: (URL_address is not very useful, same with startmodulo. It can be applied afterwards.)

function sendStartSceneAjax(URL_address, filename, startmodulo){
$.ajax({
    type: "POST",
    dataType: "json",
    url: "/cgi-bin/scene?"+Math.random(), //"/cgi-bin/scene?"
    data: {file: filename, startdelaymodulo:startmodulo },
    success: function (data) {
        updateScene(data);
        console.log(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        document.getElementById("sceneplay").innerHTML = "error playing: " + filename;
        console.error("OH SHIT STARTSCENEAJAX " + errorThrown + " " + XMLHttpRequest + URL_address + filename + startmodulo);
    } }); }

Just a makeshift test I've built -- obviously doesn't work, but might show you what I am thinking of:

if($split_sentence_2 == $nowDate)
{
        ?>
        <button name="Play" onclick="startSelectedSceneFromDB('Blauwe_Pulse.csv');" class="play" title="<? echo $label_play; ?>"></button>
        <?   
}

I'm really hoping you guys and gals could at least give me some pointers on how to proceed. It would be highly appreciated!

p.s. I wanted to post more links to show that I have been doing research, but I'm only allowed 2 at the moment. My apologies!

like image 877
Sander Van Den Hout Avatar asked Nov 27 '15 14:11

Sander Van Den Hout


People also ask

How can I use JavaScript and PHP together?

You can combine PHP code only with HTML Code. On the other hand, JavaScript code can be combined with the latest technologies like HTML, XML, and Ajax.

Can you run JavaScript in PHP?

You can execute Javascript through PHP by calling javascript code/function as a string in PHP and send it to the client browser to execute.

How call JavaScript function in PHP if condition?

PHP considers every HTML element as strings inside the echo command. So, we will trigger the javascript function calls inside the echo command. Let us illustrate a simple function call from PHP, <script> function display() { //display the text document.

How do I run a PHP script on Raspberry Pi?

Probably the easiest way to use PHP with Raspberry Pi is through the shell_exec() function. This function lets you execute shell commands, so it can act as a sort of bridge between PHP and the Raspberry Pi. In the most simple case, shell_exec() can call Python scripts that perform certain tasks and control GPIO pins.


2 Answers

Start script:

function sendStartSceneAjax(URL_address, filename, startmodulo){
$.ajax({
    type: "POST",
    dataType: "json",
    url: "/cgi-bin/scene?"+Math.random(), //"/cgi-bin/scene?"
    data: {file: filename, startdelaymodulo:startmodulo },
    success: function (data) {
        updateScene(data);
        console.log(data);
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        document.getElementById("sceneplay").innerHTML = "error playing: " + filename;
        console.error("OH SHIT STARTSCENEAJAX " + errorThrown + " " + XMLHttpRequest + URL_address + filename + startmodulo);
    } }); }

And:

 setInterval( function( e ) {
            $.post( '/to_php_script_to_get_song_info.php', function( returnData ) {
                    if ( returnData != '' ) {
                        returnData = JSON && JSON.parse(json) || $.parseJSON(json);
                        sendStartSceneAjax( returnData.URL_address, returnData.filename, returnData.startmodulo );
                    }
                });
        }, 500 );

Then on the php part:

//find whatever songinfo is about to start
<?php
    $data = array(
        'URL_address' => $found_url_address,
        'filename' => $found_filename,
        'startmodulo' => $found_startmodulo,
);

echo json_encode( $data );
?>

This way you call the bit that searches songinfo and lighting stuff on every 500 ms, and return data back if found some. When the script found some it calls the sendStartSceneAjax with the appropriate variables. Maybe you can use some of it.

like image 188
Wolfeh Avatar answered Sep 30 '22 08:09

Wolfeh


What you are requesting is not possible using standard AJAX. The client can request anything from the server, but the server cannot directly communicate to the client. Previous solutions to this have been rapid polling or long polling, which are starting to be replaced with the technology that I would recommend you investigating, WebSockets.

There are abundances of information on WebSockets on the internet and a few google searches should start putting you down the right path, but the basics are that WebSockets will allow two-way direct communication between the server and the client in near real-time. This would then allow your server to tell clients to do something, essentially allowing your server to call javascript in the browser.

Update: After re-reading your application I realize that you might be talking about a slightly different scenario, of which web sockets would still work, but if you don't actually need the web page at all, and just want this to be an automated background task, then perhaps moving all code to the server-side would be what you need. However, if you do need a web-page to drive all of this, then WebSockets will be your best bet.

There are many implementations out there, and I would recommend doing your own research to find the one that works best for you, but the one that I have used before is autobahn.js which follows the WAMP (Web-Application Messaging Protocol) specification. There should be a PHP WAMP compliant implementation somewhere that you can use for the server.

like image 36
SnareChops Avatar answered Sep 30 '22 08:09

SnareChops