AJAX does not pass values to PHP

Asked

Viewed 522 times

0

Code from my home page:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Salão de Beleza – Madame Nora</title>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="classes/jquery-2.1.1.js" ></script>
<script type="text/javascript" src="classes/jquery-2.1.1.min.js"></script>

<script type="text/javascript"> 
    $(function(){
        $("#btnDesativar").click(function(event) {             
            var aux = confirm('Deseja Realmente Desativar Conta?');
            if(aux == true){                                
                 var acao = "1";
                  var url = "includes/conexaoIndex.php";
                  xmlHttp.onreadystatechange = stateChanged;
                  xmlHttp.open("POST",url,true);
                  xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
                  xmlHttp.send("acao="+acao);
            }
        });     
    });     
</script>

</head>
<?php include "/includes/conexaoIndex.php"; ?>
<body>
<form id="loginUsuario" name="loginUsuario" action="" >
 <button type="submit" id="btnDesativar" name="btnDesativar" >Desativar conta</button>
 </form>
 </body>
 </html>

And on my other page, that’s all I have to test:

<?php

if (isset($_POST['acao']))
{ 
echo "aqui";}

?>

In my browser it looks like this:

http://localhost/Projeto/teste.php?btnDesativar=

Why doesn’t it work?

  • 1

    Welcome to the site, Icheli. The response times here are usually extremely fast, but asking for urgency is irrelevant. Your job is to make a cool headline, write in formal Portuguese, format the question well and describe the problem accurately. You can [Edit] the question whenever you need to format or clarify/add details.

  • If you are using the jQuery framework why not take advantage to use the function itself $.ajax to communicate with the server?

4 answers

1

Friend you need to put the &

xmlHttp.send("&acao=" + acao);

1

You can use the $.ajax function of jQuery and the serialize() method that already formats the form data for sending. Example:

HTML:

<form>
    <!-- Não esquecendo de colocar o atributo 'name', pois é o key value -->
    <input type="text" name="usuario" />
    <input type="password" name="senha" />
    <button type="button">Enviar</button>
</form>

jQuery:

$.ajax({
  type: 'post',
  url: 'arquivo.php',
  data: $('form').serialize(),
  success: function (data) { ... }
});

The serialize() formtaria method in this style:

usuario=joao&senha=abcdefg

0

Change the type of your button

<button type="submit" id="btnDesativar" name="btnDesativar" >Desativar conta</button>

for

<button type="button" id="btnDesativar" name="btnDesativar" >Desativar conta</button>

using type="Submit" it sends the form data to the address entered in the action="..." attribute inside the form tag (loads the page again), when you do not enter any address it sends to the same page. Using type="button" it sends nothing, causing the click action to be implemented by you when you call $("#btnDesativar"). click();

Since you are using Jquery I recommend using ajax this way using the $.Ubmit() and $.ajax method():

jquery Submit

jQuery Ajax

$("#loginUsuario").submit(function(event) {
  var aux = confirm('Deseja Realmente Desativar Conta?');
  if (aux == true) {
    var url = "includes/conexaoIndex.php";
    $.ajax({
      type: "POST",
      url: url,
      data: {
        acao: "1"
      },
      success: function(res) {
        console.log(res); //resposta gerada pela pagina requisitada
      }

    });
  }
  event.preventDefault();
});
<form id="loginUsuario" name="loginUsuario" action="">
  <button type="submit" id="btnDesativar" name="btnDesativar">Desativar conta</button>
</form>

0

Why not try jQuery+AJAX’s native function? Follow a simple example:

$.ajax({
                url         : 'login.php' , //Caminho do Arquivo PHP
                dataType    : 'json'    , //Tipo de retorno
                data        : { //Enviar dados
                    usuario : 'douglasdreer' ,
                    senha   : 'admin'
                } , // Enviar alguma 
                success : function(result){     //Tratativa de sucesso               
                    //Neste exemplo, vai retornar um TRUE / FALSE;

                    if(result){
                        alert('Logado com sucesso!');
                    } else {
                        alert('Erro ao fazer login, verifique os parâmetros');
                    }
                } ,
                error : function(jqXHR, textStatus, errorThrown){ //Tratativa de Erro
                    console.error(errorThrown);
                }
            });

In PHP

$params = $_RESQUEST;
   // Verificações 
   $json = array('status' => TRUE);
   return json_encode($login);

You can check with more details on the website below :

jQuery Site (ENG): http://api.jquery.com/jquery.ajax/

Browser other questions tagged

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