17 Apr

JavaScript function to send http commands via htaccess for remote control

In our recent post Remote Control Raspberry via Apache2 Web Server we explained how to receive a command on an apache2 web server. If we want to send this command e.g. via an android app, we need some code to accomplish this task without any browser. Thus, we show how to write a JavaScript function to send http commands via htaccess for remote control a raspberry pi or any other web accessible http(s) server.

You might think you find a typo and it should say Java instead of JavaScript. But we are aware of that. If you want to use Java, we will present a guide on that soon. This post applies JavaScript, because you can use the same come for a Web Bases Browser Application or e.g. an QT / QML App, as we did it so far.

In the above mentions post we created a web server reacting on calls like


But you have to input username and password for the htaccess security in a popup. So doing this in one command looks like this:


This in great. Now we want to apply JavaScript to send the command above to our server. Here is how it’s done:

function sendSecureCmd() {
            var user = "username"
            var passwd = "password"
            var xhr = new XMLHttpRequest()

            xhr.open( 'POST', 'https://HOSTNAME/control_page.php?my_variable=my_value', true)
            xhr.setRequestHeader( 'Authorization', 'Basic ' + Qt.btoa(user + ':' + passwd) )
            xhr.withCredentials = true
            xhr.onreadystatechange = function() {
                console.log( xhr.status, xhr.statusText )
                console.log( xhr.responseText , xhr.responseText )

Explanation: We user the XMLHttpRequest class to send the http(s) command. for htaccess authentication we need to add a certain header to the post with our correct username and password.

After xhr.send() we get the response in the onreadystatechange function by xhr.status, xhr.statusText and xhr.responseText, by this our app can check what the server did and react accordingly.


  • For a QML app you need to add some includes and code to the main.cpp like this
    #include <QSslConfiguration>
    #include <QSslSocket>

    and on the beginning of main function:

    QSslConfiguration config = QSslConfiguration::defaultConfiguration();

    to be able to handle a self-signed ssl certificate.

  • This JavaScript code can also be applied on another web server controlling your Raspberry Pi at home.

If you like the script or need some help on adapting this to your needs, please leave a comment.

Leave a Reply

Read previous post:
Remote Control Raspberry via Apache2 Web Server

Remote Control Raspberry via apache2 Web Server: This post guides you to remote control your raspberry pi via https (self-signed...