The Coding Clan
The Coding Clan

Reputation: 21

JavaScript: How to send HTTP post requests on a key-bind

I am new to HML and JavaScript and would like to know how to send a HTTP post request upon pressing a key for example 'w', in order to control a python based robot.

I've looked on google and researched the individual components of the question but failed to even make the key-binds even change attributes about the page, including the background.

My code is currently

<!DOCTYPE html>

<html>
 <head>
  <title>Rover</title>
 </head>
 <body>
  <script>
    $(document).keypress(function(e){
      if(e.shiftKey && e.keyCode === 87){
        alert('UP');
      }
    });
  </script>
  <img src = /stream.mjpg>
 </body>
</html>

Where stream.jpg is a live feed from a camera.

The code should send a HTTP post to the server, in which python will detect (the server uses pythons http.server), which will control the motors.

Upvotes: 1

Views: 1043

Answers (1)

Dacre Denny
Dacre Denny

Reputation: 30390

Seeing that you're using JQuery, you could issue a POST request via the $.post() method in your keypress() handler like this:

<!-- Include JQuery library before script block -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<!--
To host file locally, download the js file above (at cloudflare URL) to
the same directory that your HTML is hosted from on your PI, and then
use this script block instead (and remove the cloudflare one above)
<script src="/jquery.min.js"></script>
-->

<body>
  <script>
    /* 
    Replace server url with actual hostname/ip and port of 
    your python server 
    */
    var SERVER_URL = "http://localhost:8080/";

    $(document).keypress(function(e) {
    
      if (e.shiftKey && e.keyCode === 87) {
        /* 
        If shift + w key combination, issue POST request to 
        server running at address 
        */
        $.post(SERVER_URL);
        
        console.log("Shift + w detected");
      }
    });
  </script>
  <img src="/stream.jpg">
</body>

Upvotes: 2

Related Questions