Multiple parameters in xmlhttp.send();

Asked

Viewed 852 times

1

I am making an entry in the database with ajax, ajax esa working, but the insertion is not being done correctly, I believe it is because I am passing the parameters incorrectly in the send();method. I need to pass the name and age in the method. Here is the code:

HTML:

<h1> Cadastre-se em nosso site </h1>
    <div id="exibeCont"></div>

        <form action="servico.php?p=cadUsr" method="POST" id="frmCadUsr">
            Nome: <input type="text" maxlength="255" name="txtNome" id="txtNome"/>
            Idade: <input type="text" maxlength="3" name="txtIdade" id="txtIdade"/>

            <input type="submit" value="Enviar" />
        </form>

the PHP:

function cadUsr(){
    require("dbCon.php");
    require("mdl_usuario.php");

        $usr = $_POST["txtNome"];
        $idade = $_POST["txtIdade"];

        $resultado = usuario_cadastrar($con,$usr,$idade);

            if($resultado){
                echo "Cadastro efetuado com sucesso";
            } else {
                echo "O cadastro falhou";
            }
    }

PHP function to insert:

function usuario_cadastrar($conexao,$nome,$idade){


        if($nome == "" && $idade == ""){
            return false;
        }





        $sql = sprintf("insert into usuario (nome,idade) values ('%s',%s)",$nome,$idade);

        $resultado = mysqli_query($conexao,$sql);

            return $resultado;
    }

And the AJAX:

window.onload = function(){

            var xmlhttp;
            var frm = document.querySelector("#frmCadUsr");
            var url = frm.getAttribute("action");
            var nm = document.querySelector("#txtNome").value;
            var idade = document.querySelector("#txtIdade").value;

            frm.addEventListener("submit",function(e){
                e.preventDefault();

                try{
                    if(window.XMLHttpRequest){
                        xmlhttp = new XMLHttpRequest();
                    }

                    xmlhttp.open("POST",url,true);
                    xmlhttp.send(nm+idade);

                    xmlhttp.onreadystatechange = function(){
                        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                            alert("Deu certo");
                        }
                    }
                } catch(err){
                    alert("Ocorreu um erro.<br />"+ err);
                }
            });

}

I receive Alert with the message "It worked", but the insertion is not performed.

  • Where you define this function: $result = user_register($con,$usr,$age); ?

  • @Sergio, I just updated the code with the function in question !

  • Where are you calling cadUsr()? gives you some error in PHP?

  • @Sergio, thanks for the help, I found the real problem and I’ve posted the answer !

  • possible duplicate of How the variable passes via $_POST

  • @Guilhermenascimento to be checked by the answer (of my question) is clearly remarkable that this question has nothing to do with mine. My problem was due to the absence of the method xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");, which I was unaware was mandatory, and this is not mentioned at any time in the other question.

  • @anuseranother one question being another’s duplicity does not make it "worse" or something like, just "linka" one on the other. Please don’t take this the wrong way.

  • I do not take, sorry if I was rude, my intention certainly was not that ! I just wanted to explain. Again I’m sorry if I was rude and thank you for your attention !

  • 1

    @anuseranother was not rude, rest assured. Congratulations on the answer, the tip of the application/x-www-form-urlencoded is very important :)

Show 4 more comments

3 answers

1


Apart than @Rgio referred to, missing insert header xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");.

This header is standard in all html Forms, but by disabling the default form, it loses this value. I removed the form and left only the text fields, and added. A função ajax() was thus:

function ajax(){

            var xmlhttp;    
            var nm = document.querySelector("#txtNome").value;
            var idade = document.querySelector("#txtIdade").value;

                try{
                    if(window.XMLHttpRequest){
                        xmlhttp = new XMLHttpRequest();
                    }

                    xmlhttp.open("POST","servico.php",true);

                    /*setRequestHeader(Content-type, application/x-www-form-urlencoded), esta
                    função adiciona ao cabeçalho que o request feito ao servidor será um conteudo,
                    e o conteudo sera levado pela url como em um form.
                    o application/x-www-form-urlencoded é um dos cabeçalhos para enviar dados
                    através de HTTP. Ele faz com o que os dados enviados sejam guardados em uma
                    querystring(parametros de url), e é essencial quando se envia um dado para
                    o servidor.

                    Para enviar um dado para o servidor é necessário atribuir algum tipo de
                    cabeçalho para o HTTP.*/
                    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
                    xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");

                    xmlhttp.onreadystatechange = function(){
                        if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                            alert("Deu certo");
                            //console.log(xmlhttp.responseText);
                        }
                    }
                } catch(err){
                    alert("Ocorreu um erro.<br />"+ err);
                }
}

0

I was having difficulties with mine too, so I put the suggested code:

 xmlreq.open("POST","inserir.php",true);
 xmlreq.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); 
 var dados = 'questao=' + num + '&resposta=' + resposta;  //dados que estou enviando
 xmlreq.send(dados); //xmlreq = xmlhttp

It worked properly, thank you. If yours is not sending take a look at the database fields, those that are NOT NULL or VARCHAR are receiving values according.

0

You have to put the data you want to send in the format query string. That is to say:

chave1=valor1&chave2=valor2

So in search of nm + idade you should wear it like this:

var dados = 'txtNome=' + nm + '&txtIdade=' + idade;
xmlhttp.send(dados);
  • Thanks ! But it hasn’t worked yet. Giving a console.log, it shows that you did the query correctly, and ajax also gives me a positive return but does not insert in the database !

Browser other questions tagged

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