http form to get data

Posted on
  • Hello, i am newbie in html. How i can get data from my http webserver from input text field to variable in code or console.log()? I am trying, but nothing didn't work. ver 1.91 esp8266

  • Take a look at @ClearMemory041063's post:
    Processing POST using Forms.

    For very simple forms you can - client-side - on 'post' grab the data from the form fields and add it as url parms to a get url and do a get and then use - server-side - url.parse...

  • do you have simple code how it do? (input text field with button "send" on web server, and put data on JS code after click button)

  • Here is a snippet of code from the script section of an HTML document. A button press event triggers the JSONpost function.
    As written it sends an 'A'. The Espruino code sees the 'A' and sends some data back in S.

    I think there is a way to insert the message length as well, but that work is currently archived.

    function JSONpost(){
     //code to post the Postobj to the server and get a reply
     var yhttp = new XMLHttpRequest();
     yhttp.addEventListener("error",JSONpost1­);
     yhttp.open("POST","CMD", true);
     yhttp.send("A"); // text to send
    
     yhttp.onreadystatechange = function() { 
      if (yhttp.readyState == 4 && yhttp.status == 200) { 
       var S=JSON.parse(yhttp.responseText);
    // the reply is in S
      }//endif 
     };//end onreadystate function 
    }//end JSONpost 
    

    Additional info can be had here:
    Add Event Listener

  • Look at the attached HTML files in the link @allObjects supplied above.

  • thanks!

  • In extra post I will provide you with code from an active robot I made for my wife as stage partner for a kid summer camp themed 'Maker Fair'. The idea was to use recycled stuff... so some of my hunted and gathered items (and hoarded for decades -literally) re-found their destiny and purpose...

    The robot was blinking/flahing/steady lighting its eyes, rotating its antenna slow, medium, and fast (at one point it was also turning its head). Other options are left for the next opportunity, like driving around on his swivel wheels, moving its arms, and sensing and talking.... In the picture the - just taped on - electronics have been removed (shown in separate shot, also attached). The attached clip robotAction.mp4 shows some action...

    A Espruino-Wifi was all in one: independent Wifiu Access Point, Web Server, and Robot controller. Any Wifi device / phone can drive it through browser Web page interface.

    For driving/flashing the heavy LED lights for the eyes I used @DrAzzy 's MOSFETs from Tindies, for the Antenna (and Head Turning) I used some cheap, geared steppers. The Head Truning was done with 3 wheels running around, one driven (as shown with the 3d printed wheel... unfortunately, it had not enough grip and one driving stepper was not reliably turning / sufficient). As power supply I used these battery banks you get cheap. They can easily push some real Amps...

    The controlling Web page was just buttons with some javascript on click.


    4 Attachments

  • Here the complete code:

    // robot2.js
    var lon = false;
    var pag='
    <html><head><style>
    td {text-align:center; vertical-align:middle; }
    </style>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script>var ifrm;
    function eb(b) { ifrm.src = "/ifrm.html?e=" + b.id; }
    </script>
    </head><body onload="ifrm = document.getElementById(\'ifrm\');">
    <h3>Hello from <i><b>robot!</b></i></h3>
    <table width="100%"><tr>
    <td><button id="le"  onclick="eb(this)"><br>LEFT EYE<br><br></button></td>
    <td><button id="be"  onclick="eb(this)"><br>BOTH EYES<br><br></button></td>
    <td><button id="re"  onclick="eb(this)"><br>RIGHT EYE<br><br></button></td>
    </tr><tr>
    <td><button id="lb"  onclick="eb(this)"><br>LEFT BLINK<br><br></button></td>
    <td><button id="bl"  onclick="eb(this)"><br>BLINK<br><br></bu­tton></td>
    <td><button id="rb"  onclick="eb(this)"><br>RIGHT BLINK<br><br></button></td>
    </tr></table><table width="100%"><tr>
    <td><button id="s-3" onclick="eb(this)"><br>-f<br><br></butto­n></td>
    <td><button id="s-9" onclick="eb(this)"><br>-m<br><br></butto­n></td>
    <td><button id="s-27"onclick="eb(this)"><br>-s<br><b­r></button></td>
    <td><button id="s+0" onclick="eb(this)">Antenna<br>Spin<br>ST­OP<br></button></td>
    <td><button id="s+27"onclick="eb(this)"><br>+s<br><b­r></button></td>
    <td><button id="s+9" onclick="eb(this)"><br>+m<br><br></butto­n></td>
    <td><button id="s+3" onclick="eb(this)"><br>+f<br><br></butto­n></td>
    </tr></table>
    <iframe id="ifrm" width="100%" height="30"></iframe>
    </body></html>
    ';
    
    pinMode(LED1,"output");
    pinMode(LED2,"output");
    pinMode(A0,"output");
    pinMode(B0,"output");
    var WebServer = require('WebServer')
      , wifi = require('EspruinoWiFi')
      ;
    function onInit() {
      if (wifi)
        wifi.startAP('robot', {
          authMode:'open', password:'password'
        }, startServer);
      else
        startServer();
    }
    
    function startServer() {
      var ws = new WebServer(
    { port: 80
    , file_system: '/var/www/'
    , memory:
    {'index.html':{'type':'text/html','conte­nt': pag }
    ,'ifrm.html':{'type':'text/html','conten­t':
        '<html><body>e: XX</body></html>' }
    }});
    ws.on('start', function (WebServer) {
      if (lon) console.log('WebServer listening on port ' + WebServer.port); });
    ws.on('request', function (request, response, parsedUrl, WebServer) {
      var e = (parsedUrl.query) ? parsedUrl.query.e : null, v;
      if (lon) console.log('WebServer requested', parsedUrl, response, "e="+e);
      if (e=="le"||e=="be") { v = !digitalRead(LED2);
        digitalWrite(LED2,v); digitalWrite(B0,v); }
      if (e=="re"||e=="be") { v = !digitalRead(LED1);
        digitalWrite(LED1,v); digitalWrite(A0,v); }
      if (e=="lb") { setTimeout(blnkl,50,13); }
      if (e=="bl") { setTimeout(blnkb,50,9); }
      if (e=="rb") { setTimeout(blnkr,50,13); }
      if ((e+" ").substr(0,1)=="s") { var s = Math.round(1 * e.substr(1));
         s=(s<0&&s>-3)?-3:(s>0&&s<3)?3:s; e="s"+s; r(s); }
      response.dSnd = response.dSnd.replace("XX",e);
    });
    ws.on('error', function (err, WebServer) {
      if (lon) console.log('WebServer error', err); });
    ws.createServer();
    }
    
    function blnkl(c) { var v;
      v = !digitalRead(LED2); digitalWrite(LED2,v); digitalWrite(B0,v);
      if (c) setTimeout(blnkl, 50, c - 1);
    }
    function blnkb(c) { var v;
      v = !digitalRead(LED1); digitalWrite(LED1,v); digitalWrite(A0,v);
      v = !digitalRead(LED2); digitalWrite(LED2,v); digitalWrite(B0,v);
      if (c) setTimeout(blnkb, 50, c - 1);
    }
    function blnkr(c) { var v;
      v = !digitalRead(LED2); digitalWrite(LED2,v); digitalWrite(A0,v);
      if (c) setTimeout(blnkr, 50, c - 1);
    }
    
    // mirror stepper code from http://forum.espruino.com/comments/12187­872/
    // stepper.js
    // stPs stepper pins
    // st   step 0..8
    // stT  step Time in milliseconds [ms]
    // stI  step Interval (from setInterval() and for clearInterval()
    // sts  steps 0001,0011,0010,... pin signals
    // stBW sts - steps Backwards
    // stFW sts - steps Forward
    // dmy  ...because of (cond) ? exprT : exprF needs something to assign to
    var run = false;
    var st = 0;
    var stT = 0;
    var stI = null;
    var sts = null;
    var stSt =  0b0000;
    var stFW = [0b1000,0b1100,0b0100,0b0110,0b0010,0b00­11,0b0001,0b1001];
    var stBW = [0b1001,0b0001,0b0011,0b0010,0b0110,0b01­00,0b1100,0b1000];
    var stPs = [A4,A5,A6,A7];
    
    // setI setInterval(i,stsC) i in [ms] with (optionl) step Change (if not null), 
    // and direction info (string)
    var setI = function(t,stsN,d) {
      if (lon) console.log("t = ",t, d); 
      if (stI) clearInterval(stI);
      if (stsN) sts = stsN;
      run = true;
      stI = setInterval(stp,t);
    };
    
    // stp step
    var stp = function() { digitalWrite(stPs, sts[st = ++st % 8]); };
    
    // _sFW step ForWard
    var _sFW = function(t) {
      if (lon) console.log("FW w/ " + t);
      if (stT > 0) { setI((stT = t),null," ~F");
      } else { if (stT) { st = Math.abs(st - 7); } if (!stI) { st--; } setI((stT = t),stFW," FW"); }
    };
    
    // _sBW step BackWards
    var _sBW = function(t) {
      if (lon) console.log("BW w/ " + t);
      if (stT < 0) { setI(-(stT = t),null," ~B"); 
      } else { if (stT) { st = Math.abs(st - 7); } if (!stI) { st--; } setI(-(stT = t),stBW," BW"); }
    };
    
    // stop
    var stop = function() {
      if (lon) console.log("stop");
      if (stI) { stI = clearInterval(stI); stI = null; }
      if (lon) console.log(stI);
      run = false;
      digitalWrite(stPs, stSt);
    };
    
    
    // run function - t is stepping interval in [ms]
    var r = function(t) {  
      if (typeof t === "undefined" ) {
        if (stT) {
          if (lon) console.log((stT > 0) ? "F>B" : "B>F");
          r(-stT);
        } else {
          if (lon) console.log("What ?");
        }
      } else { 
        dmy = (t) ? (t>0) ? _sFW(t) : _sBW(t) : stop(); 
      }
    };
    

    The page has an iFrame which was used as the communication vehicle (sending a get with parms in line 9 by setting the iFrame's source (url) and url.parse in lines 61..71) so that not the whole page has to be loaded again, and also use a simpler approach than XHTMLRequest / POST / body work... It was all put together in a few hours on Sun afternoon...

  • thanks for all!)

  • i developed most brut variant, but it working)))

    var wifi = require("Wifi");
    
    var page = "<!DOCTYPE html>\r\n<html>\r\n<body>\r\n\r\n";
    page += "<form action=\"\" method=\"get\">\r\n First name: ";
    page += "<input type=\"text\" value=\"\" name=\"fname\"><br>\r\n  ";
    page += "Last name: <input type=\"text\" value=\"\" name=\"lname\"><br>\r\n  ";
    page += "<input type=\"submit\" value=\"Submit\">\r\n</form>\r\n\r\n";
    page += "<p>Click on the submit button, and the input will be sent to Espruino.";
    page += "</p>\r\n\r\n</body>\r\n</html>";
    
    var b;
    
    function onPageRequest(req, res) {
      var a = url.parse(req.url, true);
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(page);
      if (a.query) b = a.query;
    }
    require("http").createServer(onPageReque­st).listen(8080);
    

    var b consist all your data)

  • ...and also more correct variant

    var wifi = require("Wifi");
    
    var page = "<!DOCTYPE html>\r\n<html>\r\n<body>\r\n\r\n";
    page += "<form action=\"\" method=\"post\">\r\n First name: ";
    page += "<input type=\"text\" value=\"\" name=\"fname\"><br>\r\n  ";
    page += "Last name: <input type=\"text\" value=\"\" name=\"lname\"><br>\r\n  ";
    page += "<input type=\"submit\" value=\"Submit\">\r\n</form>\r\n\r\n";
    page += "<p>Click on the submit button, and the input will be sent to Espruino.";
    page += "</p>\r\n\r\n</body>\r\n</html>";
    
    var b;
    
    function onPageRequest(req, res) {
      if (req.method == "GET") {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end(page);
      } else {  
        req.on("close", function () {
          console.log("AVAIL:" + req.available());
          b = req.read();
          console.log("BODY: " + b);
        });
    
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end("ok");
      }
    }
    require("http").createServer(onPageReque­st).listen(8080);
    

    var b consist all your data, but data requires parse. (example data: "fname=Pavel&lname=123&xname=rtavel&znam­e=12673")

    for do this i developed little parser:

    var str = "fname=Pavel&lname=123&xname=rtavel&znam­e=12673";
    
    function splitData(data) {
        var dataReady = [];
        var part = true;
        var commVal = "";
    
        for (var index = 0; index < data.length; index++) {
            if (part) {
                if (data[index] != '=') commVal += data[index];
                else {
                    dataReady.push(commVal);
                    commVal = "";
                    part = false;
                }
            }
            else {
                if (data[index] != '&') commVal += data[index];
                if (data[index] == '&') {
                    dataReady.push(commVal);
                    commVal = "";
                    part = true;
                }
                if (index == data.length - 1) {
                    dataReady.push(commVal);
                    return dataReady;
                }
            }
        }
    }
    
    console.log(splitData(str));
    
    

    or more simple variant parser:

    var str = "fname=Pavel&lname=Dubailo&xname=TEST"
    
    var arr = str.split("&")
    var result = {};
    
    arr.forEach(function (pair) {
        var elem = pair.split("=");
        result[elem[0]] = elem[1];
    });
    
    console.log(result);
    
  • In code in post #10

    function onPageRequest(req, res) {
      var a = url.parse(req.url, true);
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(page);
      if (a.query) b = a.query;
    }
    

    I would change the sequence to do the request processing first (lines 2 and 5), and then the response (lines 3 and 4):

    function onPageRequest(req, res) {
      var a = url.parse(req.url, true);
      if (a.query) b = a.query;
     // ...more of request processing
      res.writeHead(200, { 'Content-Type': 'text/html' });
      res.end(page);
    }
    

    On a side note: Using single quote (') instead of double quotes (") for coding html fragments as literal Strings makes life much easier (and code much more legible): you do not need to escape the double quotes ("). Furthermore, you do not need the carriage returns and line feeds / new lines (/r, /n) in html source. This helps you preserve memory of which you are usually anyway in short supply... last but not least, mutli-line literal strings that recently became available helps even more with legibility: ;)

    var page = '<!DOCTYPE html><html><body>
    <form action="" method="post">
    First name: <input type="text" value="" name="fname"><br>
    Last name: <input type="text" value="" name="lname"><br>
    <input type="submit" value="Submit"></form>
    <p>Click on the submit button, and the input will be sent to Espruino.</p>
    </body></html>';
    

    In 1st code in post #11:
    if it is not a GET, you cannot assume that it is a POST since there are other valid http verbs/methods. Interestingly is that - last time I checked - request.method returns for method (erroneously) always "GET". Only parsed url returns the actual method!

    For some GET/POST discussion, take a look at Testing SW from Espruino book, ....code from page 246 (Espruino Pico+ESP8266).

  • For anyone else who gets here, there's now a tutorial on HTTP POST and Forms: http://www.espruino.com/Posting+Forms

  • Post a reply
    • Bold
    • Italics
    • Link
    • Image
    • List
    • Quote
    • code
    • Preview
About

http form to get data

Posted by Avatar for Planer @Planer

Actions