Send a string name via post using javascript

Asked

Viewed 713 times

1

Good evening, I’m only trying to send name to the server, but every time I pass the string to the server as "name:", here’s 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>

3 answers

1

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

First that XMLHttpRequest synchronously is a bad way to use, one because it freezes the browser depending on the response time and another that is something that probably soon will not work in the main process, only with Web Worker (no due date, but possible), the idea is to use callbacks, Adobe 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 back-end, but that’s another story and I don’t want to run away from the main topic)

To summarize this is synchronous, do not use:

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

This is asynchronous (it is preferred):

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 saw 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;
    }
}

It is also necessary to either put the script at the bottom of the page or use:

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

Do so:

<!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>
  • thanks for the reply friend, but I’m not using php, I’m actually using Heroku as server

  • @Publioelon example in PHP is just one example, Heroku uses php, python, ruby on Rails, vc can adapt anyway, Heroku is not language is just the server.

  • perfectly friend, but the part of picking up what was sent this done, the problem is in the shipping part

  • @Publioelon then tested the shipping code I made there?

  • Yes, and not even the empty name was sent this time

  • @Publioelon how do you know it wasn’t sent? Did you look through the browser console? Can’t it simply be that your application on Heroku is wrong on the back-end side? Allies in what language you did this?

  • i am with the server link, where returns a get with the data sent, I tried using ajax with jquery and was, but this way will not even, I did not understand why yet

  • @Publioelon blz, but without me looking at the code I really have no way to guess where the error is, I don’t even know what you did, there’s no way I can say it’s in X that’s wrong, can you understand that? Do you know what a browser console is? You’ve used this?

  • unfortunately I do not have access to the server code, anyway that was the error that the console gave me"

  • @Publioelon is, but then I only changed an excerpt of your code to explain the Ajax part, that’s another problem, even though I already answered in https://answall.com/a/207824/3635, just use document.addEventListener("DOMContentLoaded", function () { <codigo aqui dentro> });, edited the answer.

  • ah, now it showed right, only that to receiving HTTP error or connection: 0 ai on the console Failed to load server url: No 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'null' is therefore not allowed access, and yet it passed the blank

  • @Publioelon first you are probably trying to access via protocol file:///, For it to work both must be in the same domain, if yours. html is on your computer and the site you want to access in another domain there is no access right? It would be a security flaw if it were possible, when reading an error message gives a searched on the site, example: https://answall.com/questions/86342/cors-no-access-control-allow-origin-header-present-on-the-requested-resou

  • there’s some private way I can send you the container link, so you can take a look?

  • @Publioelon sends in my email that is in my profile here of the site, but I promise nothing, because as I said, there is no way to circumvent security, the links I have sent already explain what you have to do, if you do not have access to the application in Heroku then you have nothing to solve, it is simply impossible.

Show 9 more comments

1


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

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

See which unquoted name would be a variable, but in your case is the name of the field that will receive the content "Test".

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) {

    });
});

Browser other questions tagged

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