How to receive form data with pure HTML?

Asked

Viewed 5,900 times

6

I created a simple form. In it I put:

<form action="02.html" method="get" name="meu_formulario">
<input type="text" name="nome" size="60" maxlength="40"/>
</form>

I want to create the 02.html that receives this data form and displays on the screen the data filled, that’s it. But I can’t use PHP, it has to be pure HTML. How do I do that? It is possible to do this?

  • 1

    Maybe using javascript, but n know if it is possible without a server-side language.

  • You can use HTML 5 @Diegofelipe.

  • @Adriano, since you can’t use a server-side technology, you can make a offline app for Chrome and to store the data, use a Indexeddb

4 answers

9


Could do with javascript, but the parameter would be broken according to the characters contained in it by URL he will pass to string, but will format in link, removing spaces and accents:

01.html

<form action="02.html" method="get">
    <input type="text" name="nome" size="60" maxlength="40"/>
</form>

02.html

<script> //se enviar "Stack Over" ele receberia "Stack+Over"
    var url   = window.location.search.replace("?", "");
    var itens = url.split("&");
    var valor = itens[0].slice(5); // 5 pois nome= tem 5 caracteres
    alert(valor);
</script>

A more sophisticated form I found in How to read Javascript URL values (Querystring)?, in it the errors I quoted above are treated (except of accent), and to pick up values would be as in php:

<script>
    // parametro `a` opcional, ex: `tipo=1&nome=espada#custo=0`
// o valor padrão é da URL atual
function GetQueryString(a)
{
    a = a || window.location.search.substr(1).split('&').concat(window.location.hash.substr(1).split("&"));

    if (typeof a === "string")
        a = a.split("#").join("&").split("&");

    // se não há valores, retorna um objeto vazio
    if (!a) return {};

    var b = {};
    for (var i = 0; i < a.length; ++i)
    {
        // obtem array com chave/valor
        var p = a[i].split('=');

        // se não houver valor, ignora o parametro
        if (p.length != 2) continue;

        // adiciona a propriedade chave ao objeto de retorno
        // com o valor decodificado, substituindo `+` por ` `
        // para aceitar URLs codificadas com `+` ao invés de `%20`
        b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
    }
    // retorna o objeto criado
    return b;
}

// uso
var qs = GetQueryString();
alert(qs['nome']);
</script>

5

Only with HTML is not possible. If you use GET, it is possible with HTML + Javascript, as shown in other responses. To use POST, you need a language that runs on the server.

  • That’s where the wonderful PHP comes in

3

You can send and receive parameters without using server-side resources (php, Asp, ruby, etc)

There is the traditional GET method way where you just read the URI and extract the parameters with Javascript. Another way is by using cookies.

Extracting data from the URI with Javascript

Practical example:

Suppose this page is tmp.html

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">

/* 
Função usada para decodificar dados de uma URI. 
Créditos e fonte oficial: http://phpjs.org/functions/urldecode/
*/
function urldecode(str) {
  return decodeURIComponent((str + '')
    .replace(/%(?![\da-f]{2})/gi, function() {
      // PHP tolerates poorly formed escape sequences
      return '%25';
    })
    .replace(/\+/g, '%20'));
}

/*
Função que extrai parâmetros de uma URI
*/
function GetURLParameters(){
    var sstr = window.location.search.substring(1);
    var arr = sstr.split('&');
    if (arr.length < 1 || arr[0] == "")
        return null;

    var rs = new Array();
    for (var i = 0; i < arr.length; i++){
        var KeyValuePair = arr[i].split('=');
        rs[KeyValuePair[0]] = urldecode(KeyValuePair[1]);
    }
    return rs;
}

p = GetURLParameters();
</script>
</head>
<body>

<form action="tmp.html" method="GET">
<input type="text" size="10" value="" name="foo" id="foo" />
</form>

<script type="text/javascript">
p = GetURLParameters();
if (p)
    for (k in p) 
        if (document.getElementById(k) !== null)
            document.getElementById(k).value = p[k];
</script>

</body>
</html>

Obtaining data from cookies

Another way is by using cookies, also with Javascript.

Example, simulating sending by the POST method:

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>test</title>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function createCookie(name, value, days) {
    var date, expires;
    if (days) {
        date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        expires = "; expires="+date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}
function getCookieData(name) {
  var value = "; " + document.cookie;
  var parts = value.split("; " + name + "=");
  if (parts.length == 2) return parts.pop().split(";").shift();
}
function setObj(eln){
    var rr = false;
    if( document.all ){
        if(  document.all[eln]  ){
        rr = document.all[eln];
        }
    }else{
        if(  document[eln]  ){
        rr = document[eln]; 
        }else{
            if(  document.getElementById(eln)  ){
            rr = document.getElementById(eln );
            }
        }
    }
    return rr;
}

function GetURLParameters(){
    var sstr = getCookieData("frm1");
    if (!sstr)
        return null;
    var arr = sstr.split('&');
    if (arr.length < 1 || arr[0] == "")
        return null;

    var rs = new Array();
    for (var i = 0; i < arr.length; i++){
        var KeyValuePair = arr[i].split('=');
        rs[KeyValuePair[0]] = decodeURI(KeyValuePair[1]);
    }
    return rs;
}

//p = getCookieData("frm1");
p = GetURLParameters();
console.log(p);
</script>
</head>
<body>

<form id="frm1" name="frm1" action="cookies.html" method="POST">
<input type="text" size="10" value="" name="foo" id="foo" /><br />
<input type="text" size="10" value="" name="bar" id="bar" />
<input type="submit" value="enviar" />
</form>

<script type="text/javascript">

p = GetURLParameters();
if (p)
    for (k in p) 
        if (document.getElementById(k) !== null)
            document.getElementById(k).value = p[k];

createCookie("frm1", "", -1);

var obj = setObj("frm1");
obj.addEventListener("submit", function() {
    var e = obj.elements;
    var d = new Array();
    for(i=0; i < e.length; i++){
        t = e[i].type;
        if(t != "submit")
            d[i] = e[i].name+"="+encodeURI(e[i].value);
    }
    var data = d.join("&");
    alert(data);
    createCookie("frm1", data, 1);
});

</script>

</body>
</html>

Obs: Examples do not use crossbrowser code. Recommended is to use a framework such as Jquery.

1

if it’s just a simple form, and you just want to add its data to localStorage, you can remove the tag and have a button at the end of the form run a Javascript function that adds the data to Storage

for example

<label for="nome">Nome:</label>
<input type="text" id="nome" value="Seu Nome">

for the person to enter the name in a text field

<button type="button" onclick="SendForm()">Enviar sua Mensagem</button>

to create a button that calls the Sendform function()

for it to work you have to link the JS file

for that use <script defer src="./arquivo.js"></script>

in JS define the Sendform function()

function SendForm() {
    var nome = document.getElementById("nome");

    var dados = JSON.parse(localStorage.getItem("dadosForm"));

    if (dados === null) {
        localStorage.setItem("dadosForm", "[]");
        dados = [];
    }

    var auxRegistro = {
        nome: nome.value,
    };
    dados.push(auxRegistro);
    localStorage.setItem("dadosForm", JSON.stringify(dados));

    alert('nome adicionado a localStorage');
    nome.value = "";
}

Browser other questions tagged

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