How to take the value of a php variable and use it in the ajax request

Asked

Viewed 863 times

0

I am creating an order page with the code below, what I want is that when choosing the quantity of the product, it already appears the total value of product x quantity. If I set the value var price_prod1 = 10; works, but in the script that I’m trying to:

var price_prod1 =<?php $PriceProd1;?>

Everything turns white and returns no errors. Could you help me fix this?

Imagery: https://prnt.sc/io8hvf

    <script type="text/javascript" src="jquery.js"></script>
    <title>-> Novo Pedido</title>  
    </head>
    <body>
    <form name="products" id="products" method ="post" action ="registering_request.php">
        <fieldset style = "width: 640px; height: 640px; margin: 0px auto; border-size = 0px;"><legend align ="center"><h2>Novo Pedido</h2></legend> 
        <br>    
        <div class="styled-select">
        <select style="font-family: verdana; font-size: 12pt;" name="CmbCustomers" id="CmbCustomers"> 
        <option value="">Selecione o Cliente</option>
        <?php
        $query_cust = "SELECT `name`, `id` FROM customers";
        $select_customers = $PDO->prepare($query_cust);
        $select_customers->execute();

        //Conta a quantidade de linhas de clientes no BD;
        $number_of_rows_cust = $select_customers->rowCount();

        //Pega os dados dos clientes no BD; 
        $data_cust = $select_customers->fetch();

        //Verifica se a quantidade de linhas de clientes no BD é maior que 0; 
        if ($number_of_rows_cust > 0){
            echo '<option value="'.$data_cust['id'].'">'.$data_cust['name'].'</option>';
            } else {
            echo '<option value="">Sem clientes cadastrados</option>';
        }
        ?>
        </select>
        </p>
        <select style="font-family: verdana; font-size: 12pt;" name="CmbProd1" id="CmbProd1">
        <option value=""> Selecione o Produto </option>
        <?php
        $query_prod1 = "SELECT `name`, `id`, `price` FROM `products`";
        $select_product1 = $PDO->prepare($query_prod1);
        $select_product1->execute();

        //Conta quantas linhas tem no banco de dados; 
        $number_of_rows_prod1 = $select_product1->rowCount();

        //Pega o conteudo do banco de dados;
        $data_prod1 = $select_product1->fetch();

        //Preenche o campo option com o conteudo do BD;
        if ($number_of_rows_prod1 > 0){
            echo '<option value="'.$data_prod1['id'].'">'.$data_prod1['name'].'</option>';
            $PriceProd1 = $data_prod1['price'];
            } else {
            echo '<option value="">Sem produtos disponíveis</option>';
        }
        ?>
        </select>
        </p>
        <select id="CmbQuantProd1" name="CmbQuantProd1" onchange="atualizarValorTotal()" style="display:none; font-family: verdana; font-size: 12pt;"></select>
        <script>
            $("#CmbProd1").on("change",function(){
                var id_product = $("#CmbProd1").val();
                $.ajax({
                    url: "verifyQuantity.php",
                    type: "POST",
                    data:{id_product:id_product},
                    beforeSend: function(){
                        $("#CmbQuantProd1").css({"display":"block"});
                        $("#CmbQuantProd1").html("Carregando...");
                        },
                        success: function(data)
                        {
                            $("#CmbQuantProd1").css({"display":"block"});
                            $("#CmbQuantProd1").html(data);
                        },
                        error: function(data)
                        {
                            $("#CmbQuantProd1").css({"display":"block"});
                            $("#CmbQuantProd1").html("Houve um erro ao carregar");
                        }
                    });
            });
        </script>
        </p>
        <label>TOTAL: </label>

        <b id="total"></b>

        <script>
            $("#CmbQuantProd1").on("change",function(){
                var id_product = $("#CmbProd1").val();
                $.ajax({
                    url: "calculo.php",
                    type: "POST",
                    data:{id_product:id_product},
                    beforeSend: function(){
                        $("$total").css({"display":"block"});
                        $("$total").html("Carregando...");
                        },
                        success: function(data)
                        {
                            $("$total").css({"display":"block"});
                            $("$total").html(data);
                        },
                        error: function(data)
                        {
                            $("$total").css({"display":"block"});
                            $("$total").html("Houve um erro ao carregar");
                        }
                    });
            });
        </script>

The problem is probably in that part:

        <script>
        function  atualizarValorTotal(){
        var total_value = 0;
        $('select[name^="CmbQuantProd1"]').val(function(i,val){total_value += +val; return val;});

        // var price_prod1 = 10; ASSIM FUNCIONA

        var price_prod1 = <?php $PriceProd1;?> <!-----------MESMO USANDO <?PHP E O NOME DA VARIAVEL ELE NAO RETORNA O VALOR E FICA TUDO BRANCO; ---->

        var total = (price_prod1 * total_value).toFixed(2);

        //substitui separador decimal ponto por virgula
        total=total.replace(".", ",");
        //coloca ponto como separador de milhar
        total = total.replace(/\B(?=(\d{3})+(?!\d))/g, ".");
        $("#total").text("R$ " + total);
        }
        </script>
        </form>
        <center>

1 answer

1


Missing you add command echo to print the variable value.

var price_prod1 =<?php $PriceProd1;?>

The mistake is:

var price_prod1 = <?php echo $PriceProd1; ?>
  • It was just that, a stupid detail that made a difference. Thank you! ;)

Browser other questions tagged

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