Send a string name via post using javascript

0

Good night, I'm trying to send only the name to the server, but every time I pass the string it arrives at the server as "name:", here is the way I'm trying:

    <!DOCTYPE html>
<html>
<head>
<script>
            var btn = document.getElementById("btn");
            btn.addEventListener("click", function(){

                var req = new XMLHttpRequest();
                var jsObj = {nome: "Test"};
                var sendData = JSON.stringfy(jsObj);

                req.open('POST', 'https://url.com');
                req.Send(sendData);

            });
</script>
</head>
<body>

<button id="btn">Send an HTTP POST request to a page and get the result back</button>

</body>
</html>
    
asked by anonymous 14.08.2018 / 03:19

3 answers

1

The correct way to write the json data in your case would be

var jsObj = {"nome": "Test"}; 

See what name outside the quotation marks would be a variable, but in your case it is the name of the field that will receive the "Test" content.

    
03.09.2018 / 18:18
1

There are many errors, even the w3schools that is a source that I never recommend has examples ready for you to know how to do that would give a good idea, I sincerely hope it does not understand as a criticism, but as tips, your script is well wrong

First that XMLHttpRequest in a synchronous way is a bad way to use, one because it freezes the browser depending on the response time and another that is something that will probably not work in the main process, Web Worker (there is no date foreseen, but it is possible), the ideal is to use callbacks, als javascript lives on callbacks, there is no harm in learning what is almost a mandatory requirement for this language, even more in front -end (yes there is JavaScript for backend, but that's another story and I do not want to get away from the main topic)

To summarize this is synchronization, do not use:

req.open('POST', 'https://url.com');

This is asynchronous (it is preferable):

req.open('POST', 'https://url.com', true);

Second problem, JavaScript is case-sensitive, so this is wrong:

req.Send(sendData);

Should be:

req.send(sendData);

Now on how to get JSON on the server side, I think you use PHP (from what I've seen in your other questions) so use php://input for this example:

<?php
$dados = file_get_contents('php://input');

if ($dados) {
    $json = json_decode($dados, true);

    if ($json) {
       $nome = $json['nome'];
       echo 'nome:', $nome;
    }
}

You also need to either put the script at the bottom of the page or use

document.addEventListener("DOMContentLoaded", function () {});

Do this:

<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener("DOMContentLoaded", function () {

    var btn = document.getElementById("btn");
    btn.addEventListener("click", function(){

        var req = new XMLHttpRequest();
        var jsObj = {nome: "Test"};
        var sendData = JSON.stringfy(jsObj);

        req.open('POST', 'https://url.com/pagina.php', true);

        req.onreadystatechange = function () {
            if (req.readyState != 4) return; //Ignora o resto enquanto readyState é diferente de 4 (4 = completo)

            if (req.status == 200) { //Resposta http padrão do PHP, afirma que esta tudo ok
                alert(req.responseText);//Exibe a resposta HTTP
            } else {
                alert("Erro HTTP ou conexão: " + req.status);//Exibe o código de erro HTTP ou um código de erro como "0" ou um outro numer (geralmente em IE) sobre problemas de conexão
            }
        };

        req.send(sendData);
    });
});
</script>
</head>
<body>

<button id="btn">Send an HTTP POST request to a page and get the result back</button>

</body>
</html>
    
14.08.2018 / 22:40
0

Hello, I think you could use JQuery and do as follows:

$('#btn').click(function(){
    var nome= $("#nome").val();

    $.post("caminho_da_serve", "&variavel=" + nome , function(result) {

    });
});
    
03.09.2018 / 16:41