How to receive form data with pure HTML?

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 form data and displays the filled data on the screen, that's all. But I can not use PHP, it has to be pure HTML. How do I do this? Is it possible to do this?

    
asked by anonymous 14.01.2016 / 17:51

3 answers

9

It could do with javascript , but the parameter would be broken according to the characters contained in it because by URL it will pass 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 way I found in How do I read values from the URL in Javascript (QueryString)?, in it the errors I mentioned above are treated (except for accents), and to get values would be as 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>
    
14.01.2016 / 18:06
5

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

    
14.01.2016 / 17:54
3

It is possible to send and receive parameters without the use of server-side resources (php, asp, ruby, etc.)

There is the traditional GET method where you just have to 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>

Getting cookie data

Another way is to use cookies, also with JavaScript.

Example, simulating sending by 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 codes. It is recommended to use a framework like JQuery.

    
14.01.2016 / 18:06