php inside Javascript

-1

My problem is this:

I have an html button, which I call with php, pair that I perform a discount function (-1) with an api, putting it this way it works perfect to discount and shows me the result. But before discounting I want an alert with JS, asking if you are sure of discounting and if it gives if the api is executed in php.

I have the following code:

if ($_POST['action'] == 'descontar') {
            ?>

            <script type="text/javascript">
            x = window.confirm('¿Está Seguro de Descontar?');
            if (x == true) {
             <?php //aquí empieza la api que descuenta
$Mostrar_saldo = file_get_contents('http://api.xxx.com/suscriptor/index/id_usuario/00006/id_suscripcion/000');
         $Mostrar = json_decode($Mostrar_saldo, true);
         $my_array = array_shift($Mostrar);
         $saldo = $my_array['saldo'];
         echo "<br>";
         print "Saldo Anterior: $my_array[saldo]"; 
         echo "<br>";
         $nuevo_saldo = $saldo - 1;
         $actualiza_saldo = (file_get_contents('http://api.xxx.com/suscriptor/actualizar/id_usuario/000/id_suscripcion/000/saldo/'.$nuevo_saldo));
         $actualiza = json_decode($actualiza_saldo, true);

         $my_array = array_shift($actualiza);
         echo "Saldo Actual: $nuevo_saldo";
             ?> //aquí termina la api que descuenta
            return true;
            }else{
                  document.write ("No continuar. Elija una Opción");
                  return false;
                }
            </script>
            <?php
            }

With this code, the api works and it discounts normally, but it does not show me any alert, nor the echo that says the balance.

    
asked by giselle 17.04.2017 в 17:30
source

1 answer

0

What you have to do is the following.

In the interface, that is, the form or where the button is, you must add the following code in javascript, I write it for convenience using Jquery.

$("button").on("click",function(){
   var confirmar = confirm("¿Desea hacer algo con este botón?");
   if (confirmar){
      $.post("url-pagina-php",{"action":"descontar"},function(){
         alert("ya se descontó lo que debía descontar);
      })
   }
})

On the other hand in a PHP page you must put all the code you published at the beginning.

How does it work? A page will be executed, the one with javascript but nothing will be done until the user presses the button and clicks on accept. Once that happens, just call the PHP page.

Now if you want everything on the same page and running at the same time it is not possible since first the PHP code is armed (it is executed on the server) and then the Javascript code is executed (in the client's browser).

    
answered by 18.04.2017 в 01:58