Buttons with HTTP Request Action

Asked

Viewed 834 times

0

The Button Click Request is receiving: { 'QTD1LED, ON': '' }, but I would like to receive only {QTD1LED, ON}. What I have is the change in my code?

var http = require("http").createServer(servidor);
var express = require('express');
var io = require("socket.io").listen(http);
var app = express();
var fs = require("fs");
var querystring = require('querystring');
var fs = require('fs');

var contentTypes = {
    js: 'text/javascript',
    css: 'text/css',
    json: 'application/json',
    png: 'image/png',
    jpg: 'image/png',
    wav: 'audio/wav'
};

function processPost(request, response, callback) {
    // Código boilerplate pra receber a querystring pedido HTTP,
    // convertê-la e formatá-la em uma coleção de pares chave-valor

    var queryData = "";
    if(typeof callback !== 'function') return null;

    request.on('data', function(data) {
        queryData += data;
    });

    request.on('end', function() {
        request.post = querystring.parse(queryData);
        callback();
    });
}

function servidor(req, res) {
    var contentType = 'text/html';
    var filePath = '.' + req.url;

    if(req.method == 'POST') {
        // Se o método do pedido for HTTP POST, processa a querystring

        processPost(req, res, function() {
            // Imprime a querystring convertida em chaves-valores
            console.log(req.post);

            // O request.post está disponível para ser usado aqui

            // Retorna a página para o cliente com o cód. HTTP 200 (OK)
            res.writeHead(200, "OK", {'Content-Type': 'text/plain'});
            res.end();
        });
    }
    else if (filePath == './' || filePath == './index.html') filePath = './index.html';
    else contentType = contentTypes[req.url.split('.').pop()];
    fs.readFile(filePath, function(error, content) {
        if (error) {
            if (error.code == 'ENOENT') {
                fs.readFile('./404.html', function(error, content) {
                    res.writeHead(200, {
                        'Content-Type': 'text/html'
                    });
                    res.end(content, 'utf-8');
                });
            } else {
                res.writeHead(500);
                res.end('Ooops... houve um erro: ' + error.code + ' ..\n');
                res.end();
            }
        } else {
            res.writeHead(200, {
                'Content-Type': contentType
            });
            res.end(content, 'utf-8');
        }
    });
}


app.get('/teste', function(req, res) {
    res.charset = 'UTF-8'
    res.send(recebido);
});


http.listen(5000, "192.168.0.108", function() {
    var host = http.address().address;
    var port = http.address().port;
    console.log('Exemplo na URL http://%s:%s', host, port);
});

HTML

<!DOCTYPE html>
<html lang="en">

<head>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>SmartHouse</title>

    <!-- Bootstrap Core CSS -->
    <link href="/css/bootstrap.min.css" rel="stylesheet">

    <!-- Custom CSS -->
    <link href="/css/sb-admin.css" rel="stylesheet">

    <!-- Morris Charts CSS -->
    <link href="/css/plugins/morris.css" rel="stylesheet">

    <!-- Custom Fonts
    <link href="font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> -->
    <script src="/font-awesome/font.js"></script>

    <script src="/js/socket.io-1.4.5.js"></script> <!-- chamamos o socket.io que por padrão o socket.io cria a rota http sem precisarmos interferir -->

    <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
    <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
    <!--[if lt IE 9]>
        <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
        <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
    <![endif]-->

</head>

<body>

    <div id="wrapper">

        <!-- Navigation -->
        <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
            <!-- Brand and toggle get grouped for better mobile display -->
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
                    <span class="sr-only">Toggle navigation</span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                <a class="navbar-brand" href="index.html">Sistema Smart House - Automação Residencial</a>
            </div>
            <!-- Top Menu Items -->

            <!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
            <div class="collapse navbar-collapse navbar-ex1-collapse">
                <ul class="nav navbar-nav side-nav">
                    <li>
                        <a href="/index.html"><i class="fa fa-home"></i> Home</a>
                    </li>
                    <li>
                        <a href="sala.html"><i class="fa fa-television"></i> Sala</a>
                    </li>
                    <li>
                        <a href="cozinha.html"><i class="fa fa-birthday-cake"></i> Cozinha</a>
                    </li>
                    <li class="active">
                        <a href="javascript:;" data-toggle="collapse" data-target="#demo"><i class="fa fa-bed"></i> Quartos <i class="fa fa-fw fa-caret-down"></i></a>
                        <ul id="demo" class="collapse">
                            <li class="active">
                                <a href="quarto1.html"> Quarto 1</a>
                            </li>
                            <li>
                                <a href="quarto2.html"> Quarto 2</a>
                            </li>
                        </ul>
                    </li>
                    <li>
                        <a href="#"><i class="fa fa-bell"></i> Alarme</a>
                    </li>
                </ul>
            </div>
            <!-- /.navbar-collapse -->
        </nav>

        <div id="page-wrapper">

            <div class="container-fluid">

                <!-- Page Heading -->
                <div class="row">
                    <div class="col-lg-12">
                        <h1 class="page-header">
                            Quarto 1 <small>Geral</small>
                        </h1>
                        <ol class="breadcrumb">
                            <li class="active">
                                <i class="fa fa-bed"></i> Quarto 1
                            </li>
                        </ol>
                    </div>
                </div>
                <!-- /.row -->
                <div class="row">
                    <div class="col-lg-4">
                    </div>
                        <div class="col-lg-4">
                            <div class="panel panel-default">
                                <div class="panel-heading">
                                    <h1><center>Quarto 1 - Lampada</center></h1>
                                </div>
                                <div class="panel-body">
                                    <a onclick="enviarComandoON()" class="btn btn-success btn-lg btn-block" id="QTD1LED, ON">ON</a>
                                    <a onclick="enviarComandoOFF()" class="btn btn-danger btn-lg btn-block" id="QTD1LED, OFF">OFF</a>
                                </div>
                            </div>
                        </div>
                    <div class="col-lg-4">
                    </div>
                </div>
                <!-- /.row -->

            </div>
            <!-- /.container-fluid -->

        </div>
        <!-- /#page-wrapper -->

    </div>
    <!-- /#wrapper -->

    <!-- jQuery -->
    <script src="/js/jquery.js"></script>

    <!-- Bootstrap Core JavaScript -->
    <script src="/js/bootstrap.min.js"></script>

    <!-- Morris Charts JavaScript -->
    <script src="/js/plugins/morris/raphael.min.js"></script>
    <script src="/js/plugins/morris/morris.min.js"></script>
    <script src="/js/plugins/morris/morris-data.js"></script>
    <script>
        document.getElementById('QTD1LED, ON').addEventListener('click', function(event) {
        // Obtém os valores dos elementos #qrt e #led
        var status = document.getElementById('QTD1LED, ON').id;

        // Monta querystring para o POST com os valores dos elementos
        var params = status;

        // Monta a requisição POST
        var http = new XMLHttpRequest();
        http.open("POST", true);

        http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

        http.onreadystatechange = function() {
            // Chama uma função quando o status do pedido for alterado
            if(http.readyState == 4 && http.status == 200) {
                // Se o status for HTTP 200 (ok) e readyState==4 (DONE)
                alert('O servidor recebeu: ' + params);
            }
        }

        // Envia a requisição
        http.send(params);
    });
    </script>

</body>

</html>
  • begins by studying about the Xmlhttprequest, which most popularly is called AJAX. If you want something easy use jQuery that facilitates this, and others, parts.

1 answer

1

To achieve this, it is interesting to send the data via AJAX to the server in nodejs. You will probably end up opting for some framework, but for exercise, it is worth seeing how it is done at hand.

To be very simple, this server differentiates the requests between POST and GET (without checking the request path). If it is POST, it prints the data in the console, if it is GET it returns the index.html:

var http = require('http');
var querystring = require('querystring');
var fs = require('fs');


function processPost(request, response, callback) {
    // Código boilerplate pra receber a querystring pedido HTTP,
    // convertê-la e formatá-la em uma coleção de pares chave-valor

    var queryData = "";
    if(typeof callback !== 'function') return null;

    request.on('data', function(data) {
        queryData += data;
    });

    request.on('end', function() {
        request.post = querystring.parse(queryData);
        callback();
    });
}

http.createServer(function(request, response) {
    // Função que receberá os pedidos HTTP na porta especificado em
    // listen() logo abaixo

    if(request.method == 'POST') {
        // Se o método do pedido for HTTP POST, processa a querystring

        processPost(request, response, function() {
            // Imprime a querystring convertida em chaves-valores
            console.log(request.post);

            // O request.post está disponível para ser usado aqui

            // Retorna a página para o cliente com o cód. HTTP 200 (OK)
            response.writeHead(200, "OK", {'Content-Type': 'text/plain'});
            response.end();
        });
    } else {
        // Se o método não for POST, assume que é GET e que está
        // requisitando o index.html

        fs.readFile('./index.html', function(error, content) {
            if (error) {
                // Se houve um erro ao carregar o arquivo,
                // retorna HTTP 500

                response.writeHead(500);
                response.end('Erro interno do servidor');
            }
            else {
                // Se não houve erro retorna o conteúdo do index.html
                response.writeHead(200, {'Content-Type': 'text/html'});
                response.end(content, 'utf-8');
            }
        });
    }

}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');

index.html is very simple too, just assemble the request and send using Xmlhttprequest:

<!doctype html>
<html>
<body>
<form>
    <div>
        Quarto: <input type="number" name="qrt" id="qrt" value="1">
    </div>
    <div>
        LED:
        <select name="led" id="led">
            <option value="ON">ON</option>
            <option value="OFF">OFF</option>
        </select>
    </div>
    <input type="button" value="Enviar" id="submit">
</form>

<script>
document.getElementById('submit').addEventListener('click', function(event) {
    // Obtém os valores dos elementos #qrt e #led
    var qrt = document.getElementById('qrt').value;
    var led = document.getElementById('led').value;

    // Monta querystring para o POST com os valores dos elementos
    var params = 'valor={QRT' + qrt + 'LED, ' + led + '}';

    // Monta a requisição POST
    var http = new XMLHttpRequest();
    http.open("POST", '', true);

    http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

    http.onreadystatechange = function() {
        // Chama uma função quando o status do pedido for alterado
        if(http.readyState == 4 && http.status == 200) {
            // Se o status for HTTP 200 (ok) e readyState==4 (DONE)
            alert('O servidor recebeu: ' + params);
        }
    }

    // Envia a requisição
    http.send(params);
});
</script>
</body>
</html>

Read the reference to Xmlhttprequest (there has the description and explanation of functions, readyState codes, plus examples and links to articles about it).

These two files make up a minimum testable example of what you want to do. If you have any difficulty running them, I can include instructions here in the reply.

  • thank you so much for the code! Can you put some comments so I understand better? I didn’t get time to test, but apparently it will work!

  • I changed the code and used with bootstrap, however, in addition to not loading the bootstrap when accessing http://127.0.0.1:8000, the "OFF" button does not work, and the qrt variable does not receive value. Can you take a look at the code? (I edited the first question)

  • It depends on your file structure, see the developer’s tools if there is an error. Maybe you’ll have better luck using Cdns to load scripts.

  • First you have two elements with the same id (the id must be unique in a document). Also, my code will not work with <button>s because it was written to get the information from a <select>. Another problem is that buttons typically do not save status (selected and not selected). Frameworks like bootstrap take care of this by modifying a <input type=radio> to look like http://v4-alpha.getbootstrap.com/components/buttons/#checkbox-and-radio-Buttons

  • commented the code so you understand better

  • i tested, but the server is getting { 'QTD1LED, ON': '' } How do I change to only {QTD1LED,ON}?

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.