How to receive a POST without the <form> tags in PHP?

Asked

Viewed 3,409 times

3

<?php

if(isset($_POST['pagando'])) {
    //faz alugma coisa
}

?>

<input type="submit" name="pagando" value="PAGAR">

Gave a general blank here personal. How to send pagando to the PHP without the input is inside the tags <form> causing it to trigger an action?

  • 8

    um... $.ajax() ?

  • I get it, @Sneepsninja. He wants to do an ajax, but he doesn’t know it calls ajax :)

3 answers

7


Html5

You can use the attribute form="" of Html5 (it is necessary for the browser to support this, I believe all modern browsers support):

<form id="form_pagamento" method="post" action="test.php">
    <label>Nome:</label>
    <input type="text" id="nome" name="nome" value="fulano">
</form>

<input type="submit" name="pagando" value="PAGAR" form="form_pagamento">

Note that the attribute form in the <input> must have the same value as the attribute id of <form>, in the case in both used form_pagamento

Ajax

You can also use XMLHttpRequest (the famous ajax):

var nome    = document.getElementById("nome");
var pagando = document.getElementById("pagando");

function XHR() {
    var xhr = null;
    if(XMLHttpRequest){
        xhr = new XMLHttpRequest();
    } else if(ActiveXObject){
        //Compatibilidade com InternetExplorer antigo IE6
        try { xhr=new ActiveXObject("Msxml2.XMLHTTP"); }catch(e){
            try { xhr=new ActiveXObject("Microsoft.XMLHTTP"); }catch(e){}
        }
    }

    return xhr;
}

function Enviar() {
var botaoValor = pagando.value; //Pega o valor do input
var nomeValor = pagando.value;  //Pega o valor do input

var ajax = XHR();

ajax.open("POST", "arquivo.php", true);//Configure a sua página aqui

//Está linha é obrigatoria no POST, pois senão os dados vão como RAW
ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

//Ajax é async então precisa de um callback
ajax.onreadystatechange = function () {
    if (ajax.readyState === 4) {
        if (ajax.status === 200) {
            alert(ajax.responseText);
        } else {
            alert("Erro HTTP na resposta do servidor: " + ajax.status);
        }
    }
};
ajax.send("pagando=" + encodeURI(botaoValor) + "&nome=" + encodeURI(nomeValor));//É necessário codificar as variáveis
}

pagando.onclick = Enviar;
<input type="text"   id="nome"    value="Fulano">
<input type="submit" id="pagando" value="PAGAR">

  • 1

    There’s an interesting thing huh !!!!!

0

In Javascript you can send via post, with the jquery post method:

<script src="//code.jquery.com/jquery-latest.js" type="text/javascript"></script>

Putting the following script:

$(function() {
    $('#sub').on('click',function() {

      var data = {pagando: '<?php echo "xxxxx"; ?>'};
       $.post('sua_pagina.php', data, function(rtn) {
             var e = jQuery.parseJSON(rtn);
              /* --- se prefirir, tem mais duas formas de fazer parse 
                var e = eval('('+rtn+')');
                 --- ou
                var e = JSON.parse(rtn);  */
               if (e.success) {
                  alert(e.message);
              }
        });
    });
});

On the body, put the button:

<input type="button" id="sub" value="PAGAR">

And in PHP, you do what you need and then return if you have a valid condition:

if (isset($_POST['pagando'])) {
    //faz o que você quer aqui dentro 
   echo json_encode(array('message'=>'sucesso!', 'success'=>'1'));
}

0

A simple and safe technique is to create the element <form> "on-the-fly" (at runtime).

See an example without using a framework or ajax:

<html>
<head>
<script type="text/javascript">
function fmrSend(){
    var frm = document.createElement("form");
    frm.id='frm1';
    frm.method='POST';
    frm.action='tmp.php';

    var input = document.getElementById("foo");
    frm.appendChild(input);

    document.body.appendChild(frm);
    frm.submit();
}
</script>
</head>
<body>



<input type="text" value="123" size="10" name="foo" id="foo" />

<br />
<a href="JavaScript:fmrSend();">SEND</a>

</body>
</html>

This simple technique is compatible with "all" browsers.

Browser other questions tagged

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