Execute document and send variable value in PHP by Ajax

Asked

Viewed 323 times

0

Hello, I have to develop a confirm button for deletion of a product. For this, I had the idea of running a file in php through ajax from the moment I click on "Confirm" in JS confirm, along, passing the value of a variable that will serve to make the sqls.

The problem is that I don’t know how to pass the value of this variable, we examples I found shows how to pass input values by id or values already determined, but nothing like what I need.

PHP with the JS:

<?php
  $codprod = $_POST['produtoDelete'];// Esse é o valor que preciso para fazer as sqls

  //JS
  <script>
  function excluirConfirm() {
    var txt;
    var r = confirm("Tem certeza que deseja excluir esse produto?");
    if (r == true) {
        //Aqui fica o ajax
        $.ajax({
            type: 'post',
            url: 'produtoSessionEdit.php',
            dataType: 'json',
            data: {
                codprod: ? //AQUI QUE ESTA MINHA DÚVIDA
            } /* ... */
        });

    }else {
        txt = "You pressed Cancel!";
    }
    document.getElementById("demo").innerHTML = txt;
    }
  </script>
?>

PHP file with sqls

<?php
ob_start();
session_start();

$codprod = $_POST['produtoDelete'];

//Deleção do produto
$select= "DELETE DESCRICAO FROM PRODUTO WHERE COD_PRODUTO=:codd";
$result= $pdo->prepare($select);
$result->bindParam(':codd', $codprod);
$result->execute();

echo '<script type="text/javascript"> alert("Produto excluido!"); </script>';
?>

What can I do to make this go away?

  • From what I understand you want to take this $codprod and send by ajax to the right php page?

  • Exactly. And also "call" the execution of the file, I believe I’m already doing it.

2 answers

1

First, remove javascript from php tag

<?php
  $codprod = $_POST['produtoDelete'];// Esse é o valor que preciso para fazer as sqls ?>

It will then call the delete function on a button or something of the example type

<button onclick="excluirConfirm();">Botao</button>

in the js file you will get the received value in a js variable

//JS
  <script>
  function excluirConfirm() {
    var valorRecebido = <?php echo $codprod; ?>;
    var txt;
    var r = confirm("Tem certeza que deseja excluir esse produto?");
    if (r == true) {
        //Aqui fica o ajax
        $.ajax({
            type: 'post',
            url: 'produtoSessionEdit.php',
            dataType: 'json',
            data: {
                codprod: valorRecebido //AQUI Você passará o valor e o codprod será o name
            } /* ... */
        });

    }else {
        txt = "You pressed Cancel!";
    }
    document.getElementById("demo").innerHTML = txt;
    }
  </script>

With this in php you will receive the name given in ajax

<?php
ob_start();
session_start();

 //Aqui coloca o name dentro do post
$codprod = $_POST['codprod'];

//Deleção do produto
$select= "DELETE DESCRICAO FROM PRODUTO WHERE COD_PRODUTO=:codd";
$result= $pdo->prepare($select);
$result->bindParam(':codd', $codprod);
$result->execute();

echo '<script type="text/javascript"> alert("Produto excluido!"); </script>';
?>
  • When I do so Anderson the confirm does not appear on the screen.

  • When you do what confirm does not work?

  • When I comment on the 2 lines that were added by you, it appears.

  • You can edit your question with modified code by doing a favor?

  • The code is the way you put it.

  • excluirConfirm(); sorry I forgot the point and comma here, I will edit see if this was it

  • Well, it wasn’t that.

  • brother here is working normal, only the php tag will not work but calls the function usually looks https://codepen.io/anon/pen/LjRJLW, you import javascript all certinho la no header?

  • Because, in this case, still persists my problem of not being able to pass the value of the php variable...

  • @Andersonamorim see if you imported javascript in the header from an Alert inside the javascript function and put the updated code

Show 6 more comments

1

Your php variable will have to be stored in client, so that in the submission of the form, the value of the name be its name in php, example...

<form name="formEnv" id="env" method="post">

    <input type="hidden" name="produtoDelete" value="<?php echo $_POST['produtoDelete']?>">

    <input type="submit">

</form>

JS

$(document).ready(function(){


        $( "#env" ).submit(function( event ) {
         event.preventDefault();

         var r = confirm("Tem certeza que deseja excluir esse produto?");

         if(r == true) {

         var data = $("#env").serialize();

            $.ajax({
                type : "POST",
                url  : "suaPagina.php",
                data : data,
                dataType: "json",
                success : function(response){
                    if (response == 1) {

          document.getElementById("demo").innerHTML = 'sucesso';

                    };
                    if (response == 0) {

          document.getElementById("demo").innerHTML = 'falha';

                    };
                }
            })

           }else{alert('operação cancelada!');}
        });

})

PHP

<?php
ob_start();
session_start();

$codprod = $_POST['produtoDelete'];

//Deleção do produto
$select= "DELETE DESCRICAO FROM PRODUTO WHERE COD_PRODUTO=:codd";
$result= $pdo->prepare($select);
$result->bindParam(':codd', $codprod);
$result->execute();

if($result){$retorno = 1}else{$retorno = 0};

echo json_encode($result)
exit();

?>

if your javascript is embedded in the page, the php variable can be explicit.

  • Your alternative seems cool, as I would to apply it using confirm?

  • good just add it before ajax communication, I will edit the code...

Browser other questions tagged

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