How to use a Javascript variable in a php page via ajax

Asked

Viewed 716 times

0

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

On the cart page.php 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 don’t 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 thisNotice: Undefined index: teste

  • Try to pass teste: teste instead of 'teste': teste

  • Try modifying in AJAX: date: test

1 answer

1

In my view it makes no sense for you to redirect to the same page that is sending the data via ajax.

If it were so just make 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 the ajax does not need to load the page again or does not need to be directed to another page.

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

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

In PHP code an exception will be made if the value is empty.

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

Browser other questions tagged

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