darth-dev-vader
darth-dev-vader

Reputation: 93

how to auto calculate price and quantity and then display the result? AJAX PHP

I am creating this simple project that includes auto calculate of the price and quantity and then display it only after two < select > tags has been triggered,set or selected using AJAX without using submit button. I can achieve this but does not automatically calculates and display it without using submit button.

this is my code in HTML:

<form method="post">
    <select name="days">
        <option value="2">2 days</option>
        <option value="3">3 days</option>
    </select>
    <select name="persons">
        <option value="2">2 persons</option>
        <option value="4">4 persons</option>
        <option value="6">6 persons</option>
        <option value="8">8 persons</option>
    </select>
</form>

Assume that in my Database

day 2 == 1000

day 3 == 2000

this is my code in PHP:

if(isset($_POST['submit'])) {

    $days     = $_POST['days'];
    $persons  = $_POST['persons'];

    // get database of the 'price' from rates tbl 
    $sql = "SELECT * FROM rates WHERE duration='$days'";
    $res = mysqli_query($conn,$sql);

        $rates_tbl = mysqli_fetch_assoc($res);

    $rates = $rates_tbl['price'];

    $total_price = ($rates*$persons);

    echo 'total: ' . number_format($total_price) . '.00';

}

Should i use this type of ajax?? I dont even know if this is right.

    <script type="text/javascript"> 
       $.ajax({  
            url:"autocalculate.php",  
            method:"POST"
       }) 
    </script>

Upvotes: 0

Views: 2712

Answers (1)

CMartins
CMartins

Reputation: 3293

If the goal is to display the values on screen you can use this.

<form method="post">
<select name="days">
    <option value="2">2 days</option>
    <option value="3">3 days</option>
</select>
<select name="persons">
    <option value="2">2 persons</option>
    <option value="4">4 persons</option>
    <option value="6">6 persons</option>
    <option value="8">8 persons</option>
</select>

and your jQuery script

    var readyToCalculate = false;
var optionChanges = 0;
$('select').on('change', function (e) {
   if(readyToCalculate==true){
        calculate();
   } else {
    optionChanges ++;   
    if (optionChanges==2){
    readyToCalculate = true;
    calculate();
    }
   }
});

function calculate(){

var val1 =  parseInt($('select[name=days]').val());
var val2 =  parseInt($('select[name=persons]').val());
var result = (val1 + val2);
$(".results").html(result);
}

Upvotes: 1

Related Questions