Reputation: 307
I am currently setting up a checkout for my website. I have a product that I offer options that vary in price and I'd like to have a price preview at the end before the customer decides to pay. I have a checkout modal and ideally I'd want to have the price preview reflect the final price of the product after everything is taken into account. The math is done server side on php, how do I echo or display the variables back into the html page without reloading after pressing a button?
<?php
//sets price based on options selected//
$ord_type_explode = explode('|',$_POST['ord_type']);
$base_price = $ord_type_explode[1];
$item_options_explode = explode('|',$_POST['item_options']);
$options_add = $item_options_explode[1];
$quantity_select_explode = explode('|',$_POST['quantity_select']);
$quantity_multiplier = $quantity_select_explode[1];
$final_price = ($base_price + $options_add) * $quantity_multiplier;
echo $final_price;
?>
Upvotes: 1
Views: 97
Reputation: 2840
This is typically performed through an XHR.
Here is a simplistic GET and POST example to help you wrap your head around it.
Get:
var url = 'mypage.php';
var xhr= new XMLHttpRequest() || new ActiveXObject( "Microsoft.XMLHTTP" );
xhr.onreadystatechange = function () {
if ( xhr.readyState == 4 && xhr.status == 200 ) {
//Response text
console.log( xhr.responseText );
}
};
xhr.open( "GET", url, true );
xhr.send();
Post:
var url = 'mypage.php';
var sendData = 'a=1&b=2'
var xhr= new XMLHttpRequest() || new ActiveXObject( "Microsoft.XMLHTTP" );
xhr.onreadystatechange = function () {
if ( xhr.readyState == 4 && xhr.status == 200 ) {
//Response text
console.log( xhr.responseText );
}
};
xhr.open( "POST", url, true );
xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
xhr.send( sendData );
There are also many javascript libraries that offer this type of functionality, see List of Ajax frameworks
Once you have the xhr.responseText
you can then handle this text however it is best to do based on the response the page is giving back. For example if it is sending a message that says "Success" then you could take the xhr.responseText
and populate an element with it with innerHTML.
There are numerous ways to do this. The question no longer becomes about ajax now, but on how to handle strings in javascript at this point, and this can be researched comfortably through google such as "How to put text into element".
Upvotes: 1