How to use a JavaScript variable on a php page via ajax

0

Basically I need to use a JavaScript variable in a php to later register in the database. I have a <a href="carrinho.php"><button id="btnTestar">TESTE</button></a> button that leads to the cart.php page.

In the cart.php page I want to receive the variable.

$teste = $_POST['teste'];

ajax code

$(document).ready(function () {
$("#btnTestar").click(function(){
    var teste = "testando";
        $.ajax({
          type: "POST",
          url: "carrinho.php",
          data:{'teste':teste},
          success: success,
          dataType: dataType
        });

    });
});

I do not know what's wrong because I've never used ajax before so I'm in doubt. The error that appears on the php page is essse Notice: Undefined index: teste

    
asked by anonymous 14.10.2017 / 21:06

1 answer

0

In my view it does not make sense for you to redirect to the same page that is sending the data via ajax .

If so, just do a basic form with the following code:

<form action="carrinho.php" method="post">
  <input name="teste" type="text" value="testando">
  <input type="submit">
</form>

The advantage of using ajax is not having to load the page again or not being directed to another page.

What we can do is bring data from the other page with ajax .

In this code it is possible to send the variable teste and receive the return by ajax , this return will be entered in div with id result .

In the PHP code, an exception is thrown if the value is blank.

In this code you can delete the value of input to test any other value.

JavaScript:

$(document).ready(function () {
  $("#btnTestar").click(function(){
    $.ajax({
      type: "POST",
      url: 'carrinho.php',   
      data: {
        teste: $('#teste').val()
      },
      success: function (result) {
        $('#result').html(result);
      },
      error: function (result) {
        $('#result').html(result);
      }
    });
  });
});

HTML:

<input id="teste" type="text" value="testando">
<button id="btnTestar">Teste</button>
<div id="result"></div>

PHP:

$teste = $_POST['teste'];
if ($teste == '') {
    throw new Exception('Recebido valor em branco!');
} else {
    echo "Valor recebido: " . $teste;
}
    
15.10.2017 / 17:39