I have 2 drop down boxes to select products and a div for a shopping cart.
<select id="RAM">
<option value="1">4 GB</option>
<option value="2">8 GB</option>
</select>
<select id="HDD">
<option value="1">300 GB</option>
<option value="2">500 GB</option>
</select>
<ul id="cart">
<li>PRODUCT NAME (PRICE)</li>
<li>PRODUCT NAME (PRICE)</li>
</ul>
and I want to pass this dropdown value to a PHP file using AJAX and return product name & Product price etc, to #cart
as a <li>
with out refreshing page. and also without repeating the same product. Please suggest me a good/secure way to do this.
you can use jquery get or post for the ajax.
$('#RAM').change(function() {
var value = $('#RAM option:selected').text();
$.ajax(
{
type: 'POST', // Request method
url: 'yourFile.php?value='+ value, // URL
dataType: 'html',
success: function(result)
{
// do something here when PHP return result (or nothing?)
}
});
});
$('#RAM').change(function() {
var value = $('#RAM').val();
$.ajax(
{
type: 'POST',
url: 'service.php?value='+ value,
dataType: 'html',
success: function(response)
{
$('#price').html(response.price);
$('#name').html(response.name);
}
});
});
Firstly, create form:
<form id="form">
<select name="RAM">
<option value="0">4 GB</option>
<option value="1">8 GB</option>
</select>
<select name="HDD">
<option value="0">300 GB</option>
<option value="1">500 GB</option>
</select>
</form>
<ul id="cart">
<li>PRODUCT NAME (PRICE)</li>
<li>PRODUCT NAME (PRICE)</li>
</ul>
And ajax code (I use jQuery library because of its compatibility with all browsers):
$(document).ready(function() {
$('#form').change(function() {
$.ajax({
url: 'script.php',
type: 'post',
data: $(this).serialize(),
dataType: 'json',
success: function(data) {
$('#cart').empty();
$.each(data, function(index, value) {
var $li = $('<li></li>')
.text(value['product'] + ' (price: ' + value['price'] + ')')
.appendTo($('#cart'));
});
}
});
});
});
Now you have to write PHP script:
<?php
$prices = array(
'HDD' => array(30, 50),
'RAM' => array(100, 200)
);
$data = array();
foreach ($_POST as $product => $index)
$data[] = array('product' => $product, 'price' => $prices[$product][$index]);
print json_encode($data);
exit;
I think you want to save users choices. If I'm right, add saving products to cookies or database. Cookie example:
setcookie('cart',$data,time()+24*3600*5,'/'); // save cookie for 5 days
I hope it is useful for you :)