I'm building a custom add to cart system. One product can have many criteria such as color, size etc. These criteria can be added dynamically in the backend.
Now in the front end, I use php to fetch all the dynamic criteria to my product page. The script is as follows:
<form class="cart">
<div class="add-to-cart-table">
<?php
$sqlac = "SELECT * FROM sym_product_option WHERE product_id = '$pk'";
$stmtac = $dbo->prepare($sqlac);
$stmtac->execute();
while($rowac = $stmtac->fetch(PDO::FETCH_ASSOC)){
$huhu = $rowac["option_id"];
$sqlag = "SELECT * FROM sym_product_option_value WHERE option_id = '$huhu'";
$stmtag = $dbo->prepare($sqlag);
$stmtag->execute();
?>
<div class="option">
<?php echo $rowac["option_name"]; ?>
<select name="" class="form-control" class="option" onchange="calc()" data-option-id="<?php echo $rowac["option_"]; ?>" >
<?php while($rowag = $stmtag->fetch(PDO::FETCH_ASSOC)){
if($rowag["value_price"] == "0.00"){
$demson = "";
} else {
$demson = "Add-On RM ".$rowag["value_price"];
}
?>
<option value="<?php echo $rowag["value_id"]; ?>" data-price="<?php echo $rowag["value_price"]; ?>"><?php echo $rowag["value_name"]." ".$demson; ?> </option>
<?php } ?>
</select>
</div>
<?php } ?>
<div style="margin-top: 30px;" >
<button type="button" class="button" onclick="addtocart();" style="width:100%;">Add to cart</button>
</div>
</div>
Now I'm wondering how to use jquery to fetch each criteria ID(data-option-id), criteria option value(select dropdown value) and combine them into an array to be sent to php backend. I think the array should look like this:
$data = array ( "0" => array ( "option-id" => "1", "option-value" => "5"), "1" => array ( "option-id" => "2", "option-value" => "8"));
Can someone help me on this? Really appreciate your help. Thanks!
I think what you want to do is to add a start and end form tag surrounding the option dropdowns. After that you can use the code below to serialize the form and send it to the server with ajax
$( "form" ).on( "submit", function( event ) {
event.preventDefault();
console.log( $( this ).serialize() );
});
Related
So i have a form that that does a simple calculation, depending on the users input. If the results is a certain value then it stores that value in a database, then it displays that value on a page. But i have to refresh the whole page for it to retrieve the latest updated value from the the database and display on the page.
I know how to write code to refresh the whole page, but in this case i only need the section where the it displays to be refreshed.
The original form to calculate
<div class="formC">
<form action="" method="post">
<label>Base Amount</label>
<input type="text" name="base"</input>
<label>Select Currency</label>
<div class="custom-select">
<span></span>
<select name="cur_name">
<option value="" selected>Choose a Base Currency</option>
<option value="EUR">EUR</option>
<option value="USD">USD</option>
</select>
</div>
<button type="submit" value="Submit">SUBMIT</button>
</form>
</div>
The form that gets the new values from the database
<div class="formC">
<form action="test.php" method="post">
<label>Base Amount</label>
<input type="text" name="base" id="new_base" value="<?php
$results = mysqli_query($con, "SELECT * FROM contents_arr ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($results)){
echo $row["new_base"];
}
?>">
<div id="load_data"></div>
<label>Select Currency</label>
<input type="text" name="cur_name" value="<?php
$results = mysqli_query($con, "SELECT * FROM gain_name_table ORDER BY id DESC LIMIT 1");
while($row = mysqli_fetch_array($results)){
echo $row["gain_name"];
}
?>">
<button id="btn_submit" type="submit" value="Submit">SUBMIT</button>
</form>
</div>
Calculation
<?php
$base = $_POST['base'];
$value = $_POST['val'];
$selected = $_POST['cur_name'];
if ($selected == 'EUR') {
$results_eur = $base * $value;
// USD
}elseif ($selected == 'USD') {
$results_usd = $base * $value;
}
if($selected == 'EUR'){
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_eur."')";
mysqli_query($con,$sql);
}elseif($selected == 'USD'){
$sql = "INSERT INTO calculation(new_base) VALUES('".$results_usd"')";
mysqli_query($con,$sql);
}
I managed to find the solution for this code using Ajax and jQuery:
$(document).ready(function(){
$('#btn_submit').click(function(){
var get_data = $('#new_base').val();
if($.trim(get_data) != '')
{
$.ajax({
url:"db2.php",
method:"POST",
data:{new_base:get_data},
dataType:"text",
success:function(data)
{
$('#new_base').val("");
}
});
}
});
setInterval(function(){
$('#load_data').load("fetch.php").fadeIn("slow")
}, 1000);
});
This can be done by creating a seperate php file and replacing the content on your page with the content of that other php page using javascript. This is not a full description on how to do it, just a hint on how this is done. There are plenty of resources where it is described in detail.
One place to start could be here W3Schools Ajax & Php
getData.php
header('Content-Type: application/json; charset=utf-8');
// do your php database stuff here
$data = //...
$data = json_encode($data);
echo $data;
And in your main file, you can fetch() the content of your getData.php in javascript to get the latest result and then inject the results into your div using document.getElementById('content').innerHTML = ...
Using this method, only your div refreshed, not the whole page.
I don't see this question ever asked anywhere. I looked but couldn't find answer or a guide to walk through this problem.
I'm making a setting form right now, where there are 2 arrays: array city (which stores different cities) and array store (which stores different stores). Some city has the same stores, but some doesn't have that store at all. For example: Adam (city) has KFC, Ramen, Subway; Newton city has Subway, Sushi; etc.
The object array that I have in my mind is:
let city_has_store = {
Adam: {
"KFC",
"Ramen",
"Subway"
},
Newton: {
"Subway",
"Sushi"
}
};
English isn't my first language, so it's kind of tough to describe the idea. But in my form now, I have checkboxes inside radio buttons. Which is generated through php, by grabbing two arrays that I mentioned about.
<?php
foreach ( $cities as $city ) : ?>
<label><input type="radio" name="selCity" value="<?php echo _e( $city->id ); ?>"><?php echo _e( $city->name ); ?></label>
<?php
foreach ( $stores as $store ) : ?>
<label><input type="checkbox" name="selStore" value="<?php echo _e( $store->id ); ?>"><?php echo _e( $store->name ); ?></label>
<?php
endforeach;
endforeach;
?>
The form right now look like this
() Adam
[] KFC
[] Subway
[] Ramen
[] Sushi
[] Pizza
() Newton
[] KFC
[] Subway
[] Ramen
[] Sushi
[] Pizza
() Vine
[] KFC
[] Subway
[] Ramen
[] Sushi
[] Pizza
My problem is, how do I start my javascript / jquery, so that when the user select any store under the radio button, it will know how to put those selected value into the object array that I planned in beginning.
first my asumption you php array like this
$cities=array('Adam','Newton');
$stores=array('KFC','Ramen','Sushi','Pizza','Subway');
$city_has_store=array('Adam'=> array("KFC",
"Ramen",
"Subway"
),
'Newton'=> array("Subway",
"Sushi"
)
);
and i foreach the array like this
foreach ( $cities as $city ) : ?>
<div style="margin-bottom: 20px;">
<label style="display: block;">
<input type="radio" onclick="changeCheck(this.value);" id="selCity" name="selCity" value="<?php echo $city; ?>"><?php echo $city; ?>
</label>
<?php
foreach ( $stores as $store ) : ?>
<label style="display: block;">
<input type="checkbox" id="<?=$city?>_<?=$store?>" name="selStore" value="<?php echo $store; ?>" disabled><?php echo $store; ?>
</label>
<?php
endforeach;
?>
</div>
<?php
endforeach;
?>
when i foreach the array i add onclick="changeCheck(this.value);" to input radio button and i add id into input checkbox its combine from $city and the $store value and i disabled first all checkbox
and at javascript
function changeCheck(val) {
//first disable all checkbox
$('input[type="checkbox"]').prop('disabled', true);
// get the array city_has_store
var city_has_store = <?php echo json_encode($city_has_store); ?>;
//get the radio button val when click
var val_radio = val;
//foreach the array city_has_store
for (i = 0; i < city_has_store[val_radio].length ; ++i) {
//and change disabled to false when the input checkbox id like combine $city_$store
$('#'+val_rad+'_'+city_has_store[val_radio][i]).prop('disabled', false);
}
}
and the full code look like this
<?php
$cities=array('Adam','Newton');
$stores=array('KFC','Ramen','Sushi','Pizza','Subway');
$city_has_store=array('Adam'=> array("KFC",
"Ramen",
"Subway"
),
'Newton'=> array("Subway",
"Sushi"
)
);
foreach ( $cities as $city ) : ?>
<div style="margin-bottom: 20px;">
<label style="display: block;">
<input type="radio" onclick="changeCheck(this.value);" id="selCity" name="selCity" value="<?php echo $city; ?>"><?php echo $city; ?>
</label>
<?php
foreach ( $stores as $store ) : ?>
<label style="display: block;">
<input type="checkbox" id="<?=$city?>_<?=$store?>" name="selStore" value="<?php echo $store; ?>" disabled><?php echo $store; ?>
</label>
<?php
endforeach;
?>
</div>
<?php
endforeach;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function changeCheck(val) {
//first disable all checkbox
$('input[type="checkbox"]').prop('disabled', true);
// get the array city_has_store
var city_has_store = <?php echo json_encode($city_has_store); ?>;
//get the radio button val when click
var val_radio = val;
//foreach the array city_has_store
for (i = 0; i < city_has_store[val_radio].length ; ++i) {
//and change disabled to false when the input checkbox id like combine $city_$store
$('#'+val_rad+'_'+city_has_store[val_radio][i]).prop('disabled', false);
}
}
</script>
I have a html/php code as shown below. The below html/php code is working in a way that on adding rows, we can select date from every row and can save it as well.
Two things need to be done.
On clicking Delete button, it should remove the value from the JSON array because everything is pulled from the JSON after saving the form.
Also, on clicking Delete button it should delete the complete row from the DOM.
you should give each added row an id corresponding to its rank:
row.id=i.toString();
then use the following code to remove the row:
var row = document.getElementById(rowrankid);
row.parentNode.removeChild(row);
I have prepared a code sample for you using your example that does exactly what you say.
It is using a javascript fetch post request to post to the script you have provided to remove the dom elements and update the json file.
I have changed some of your paths slightly so you will need to change those back (add in the ../feeds/ parent directory)
Once the user has pressed the button the page will reload, showing the updated interface that is loaded from the json file.
There are some improvements that could be made, for example the javascript is not checking to make sure the request was successful before reloading, but as the input is date select it should be ok.
<?php
if(file_exists('./ptp-ess_landing_house.json')){
$data = json_decode(file_get_contents('./ptp-ess_landing_house.json'));
}
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$_POST = json_decode(file_get_contents('php://input'), true);
if(isset($_POST['requestType']) && in_array($_POST['requestType'], ['remove'])) {
switch ($_POST['requestType']) {
case 'remove' :
//Unset the values
unset($data->row_delete[$_POST['data'] -1]);
unset($data->house_sitting_date[$_POST['data'] -1]);
//We are reindexing the arrays as we have deleted some rows, note that we are using +1 array indexes
$data->row_delete = array_values($data->row_delete);
$data->house_sitting_date = array_values($data->house_sitting_date);
foreach($data->row_delete as $key=>$value) {
$data->row_delete[$key] = strval($key+1);
}
//Write the file back
$fp = fopen('./ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
header("HTTP/1.1 200 OK");
echo 'ok';
die;
break;
default:
}
}
}
?>
<script>
function rowDelete(row) {
//Make a request to your entry file (index.php here) to do the removal
fetch('/index.php', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({requestType: 'remove', data: row})
}).then(function(response) {
location.reload();
return response;
});
}
</script>
<?php if($data) { ?>
<form method="post">
<div id="rows" style="display:flex; justify-content: center;"><!-- Big div START -->
<!-- Remove Button START -->
<div class="rows-delete">
<h4 style="text-align:center;">Delete Rows</h4>
<?php if (empty($data->row_delete)) { ?>
<div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
<button type="button" id="delete" onclick="rowDelete()">Remove</button>
<input type="hidden" name="row_delete[]" value="1" />
</div>
<?php } else { ?>
<?php foreach ($data->row_delete as $row_delete){ ?>
<div class="row-delete" style="margin-right:30px; margin-top:22.5px;">
<button id="delete" type="button" onclick="rowDelete(<?php echo $row_delete;?>)">Remove</button>
<input type="hidden" name="row_delete[]" value="<?php echo $row_delete;?>" />
</div>
<?php }} ?>
</div>
<!-- Remove Button END -->
<!-- Sitting Date START -->
<div class="sitting-days">
<h4 style="text-align:center;">Select Date</h4>
<?php if (empty($data->house_sitting_date)) { ?>
<!-- Select Date START -->
<div class="select-date" style="margin-right:30px; margin-top:20px;">
<input type="date" class="house-sitting-date" name="house_sitting_date[]" value="">
</div>
<?php } else { ?>
<?php foreach ($data->house_sitting_date as $date){ ?>
<!-- Select Date START -->
<div class="select-date" style="margin-right:30px; margin-top:20px;">
<input type="date" class="house-sitting-date" name="house_sitting_date[]" value="<?php if($date) {echo $date;}?>">
</div>
<!-- Select Date END -->
<?php }} ?>
</div>
<!-- Sitting Date END -->
</div><!-- Big div END -->
</form>
<?php } else {
echo 'Cannot read JSON settings file';
}
?>
If your json is known at the front-end (which I think you are implying, since your rowDelete is a JS-function), you can pass this with the call to rowDelete. Then you can traverse the DOM to get to value the corresponding sibling input-field (perhaps something like this.parentNode.childNodes[1]).
Once you have that value, you can easily remove it from the corrsponding array in your json:
let d = '2020-01-30'
let idx = arr.indexOf(d)
let newdates = ([...arr.slice(0,idx), ...arr.slice(idx+1)])
data.house_sitting_date = newdates
(with some additional index bounds checking, of course).
After that, you can perform a similar DOM traversal to remove the corresponding element from the DOM.
Flash, unfortunately, the desing of the code itself is not much professional... there are separate loops for rows (in php), which instead should be only 1 loop, like (with example simple Javascript binding on click):
<?php
for ($i=0; $i<count($data["house_sitting_date"]); $i++)
{
echo '<div class="remove"><a id="'.$data["row_delete"][$i].'" onclick="deleteRow(this);">Remove</a></div>';
echo '<div class="date">....</div>';
...
}
?>
<script> function deleteRow(el) { el.remove(); } </script>
also, lots of embedded style="".. codes, instead you might use 1 style file.
This is how I did in past, and it works perfectly
Prerequisite for this answer to work is each button and input field should be in DIV with unique id and there should be container for all these div in my case its .
On Add button(if you have one) you need clone node, and paste it under or above the element where it was clicked,
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#row'+rownumber).cloneNode( true );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
Then every time you add a new row or delete a row you need to append ids on these row, to do this you would a common class for all these rows in my case I used, rows
function changeids()
{
let rows =document.getElementsByClassName('rows');
for(let i=0; i<rows.length; i++)
{
let thisid="row"+i;
rows[i].setAttribute("id", thisid);
let thisAddButton = rows[i].getElementsByClassName("add")[0];
let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];
let onclickaddfunction = "addrow("+i+")";
thisAddButton.setAttribute("onclick", onclickaddfunction);
let onclickDeletefunction = "removerow("+i+")";
thisDeleteButton.setAttribute("onclick", onclickDeletefunction);
}
}
Then when you remove you need to remove node and call changeids again
function removerow(rownumber){
document.getElementById('row'+rownumber).remove();
changeids();
}
This would give you whole working idea of add and delete rows, whole code below please ignore my messy code, just did it to give you and idea
<p>
<div id="row1" class="rows">
<button class="add" onclick="addrow(1)">add</button>
<button class="delete" onclick="removerow(1)"> remove </button>
<input type="text">
</div>
</p>
<script>
function addrow(rownumber)
{
// Create a clone of element with id ddl_1:
let clone = document.querySelector('#row'+rownumber).cloneNode( true );
// Append the newly created element on element p
document.querySelector('p').appendChild( clone );
changeids();
}
function removerow(rownumber)
{
document.getElementById('row'+rownumber).remove();
changeids();
}
function changeids()
{
let rows =document.getElementsByClassName('rows')
for(let i=0; i<rows.length; i++)
{
let thisid="row"+i;
rows[i].setAttribute("id", thisid);
let thisAddButton = rows[i].getElementsByClassName("add")[0];
let thisDeleteButton = rows[i].getElementsByClassName("delete")[0];
let onclickaddfunction = "addrow("+i+")";
thisAddButton.setAttribute("onclick", onclickaddfunction);
let onclickDeletefunction = "removerow("+i+")";
thisDeleteButton.setAttribute("onclick", onclickDeletefunction);
}
}
</script>
To delete row from dom, you have to specify unique id for main element of row and you can use [ElementObject].remove() method to delete, So everything inside that will be removed.
Also You should simplify and change JSON data, so that it will delete from json also using ajax with using single id(key) as parameter.
Here is the working code:
<?php
if (!empty($_GET)) {
if (!empty($_GET['action']) && $_GET['action'] == 'delete') {
if(file_exists('ptp-ess_landing_house.json')) {
$data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
if (!empty($_GET['row_number'])) {
unset($data[$_GET['row_number']]);
$fp = fopen('ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($data));
fclose($fp);
echo 1;
exit;
}
}
echo 0;
exit;
}
}
if (!empty($_POST)) {
$output = array();
if (!empty($_POST['row_item'])) {
$output = $_POST['row_item'];
}
$fp = fopen('ptp-ess_landing_house.json', 'w');
fwrite($fp, json_encode($output));
fclose($fp);
}
$data = array();
if(file_exists('ptp-ess_landing_house.json')) {
$data = json_decode(file_get_contents('ptp-ess_landing_house.json'), true);
}
?><form method="post">
<!-- Add New Row Button START -->
<div class="plus-minus-button" style="text-align:center;">
<button type="button" id="addRow" onclick="rowAdd()">+</button>
</div>
<!-- Add New Row Button END -->
<div id="maindiv">
<div style="display:flex; justify-content: center;">
<div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<h4 style="text-align:center;">Delete Rows</h4>
</div>
</div>
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<h4 style="text-align:center;">Select Date</h4>
</div>
</div>
<div class="choose-options" style="text-align:center;">
<div class="yes-no-option" style="display:inline-grid;">
<h4 style="text-align:center;">Yes/No</h4>
</div>
</div>
</div>
<!-- Big div START --><?php
$totalrow = 0;
foreach ($data AS $key => $row) {
?><div id="row-<?php echo $key; ?>" style="display:flex; justify-content: center; margin-top:20px;"><?php
?><div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<button type="button" class="delete" onClick="delete_row(this.value)" value="<?php echo $key; ?>">Remove</button>
<input type="hidden" name="row_item[<?php echo $key; ?>][row_delete]" value="<?php echo $row['row_delete'];?>" />
</div>
</div>
<!-- Remove Button END -->
<!-- This is what I have tried to add a button (END) -->
<!-- Sitting Date START -->
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<input type="date" class="house-sitting-date" name="row_item[<?php echo $key; ?>][house_sitting_date]" value="<?php echo $row['house_sitting_date']; ?>">
</div>
</div>
<!-- Sitting Date END -->
<!-- YES/NO START --><?php
?><div class="choose-options">
<div class="yes-no-option" style="display:inline-grid;">
<select name="row_item[<?php echo $key; ?>][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "nada" ) echo "selected";?>>Please choose an option</option>
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "yes" ) echo "selected";?>>Yes</option>
<option value="<?php echo $row['house_sitting_date_yes_no']; ?>" <?php if($row['house_sitting_date_yes_no'] == "no" ) echo "selected";?>>No</option>
</select>
</div>
</div>
<!-- YES/NO END -->
</div><?php
if ($key > $totalrow) $totalrow = $key;
else $totalrow++;
}
?>
<input type="hidden" name="totalrow" id="totalrow" value="<?php echo $totalrow; ?>">
</div>
<!-- Big div END -->
<hr />
<div style="text-align:center;">
<input type="submit" value="submit" />
</div>
</form>
<script>
function delete_row(row_number) {
var data = '<?php echo json_encode($data) ?>';
data = JSON.parse(data);
if (typeof(data[row_number]) != undefined) {
var request = new XMLHttpRequest();
request.open("GET", "index.php?action=delete&row_number=" + row_number);
request.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var row = document.getElementById('row-'+row_number);
row.remove();
}
}
request.send();
}
else {
var row = document.getElementById('row-'+row_number);
row.remove();
}
}
function rowAdd(event) {
var totalrow = document.getElementById("totalrow").value;
totalrow = parseInt(totalrow) + 1;
document.getElementById("maindiv").insertAdjacentHTML('beforeend', newRow(totalrow));
document.getElementById("totalrow").value = totalrow;
}
function newRow(row_number) {
return `<div id="row-` + row_number + `" class="sitting-days" style="display:flex; justify-content:center; margin-top:20px;">
<div class="rows-delete" style="text-align:center;">
<div class="row-delete" style="margin-right:30px;">
<button type="button" class="delete" onClick="delete_row(this.value)" value="` + row_number + `">Remove</button>
<input type="hidden" name="row_item[` + row_number + `][row_delete]" value="` + row_number + `" />
</div>
</div>
<div class="sitting-days" style="text-align:center;">
<div class="select-date" style="margin-right:30px;">
<input type="date" class="house-sitting-date" name="row_item[` + row_number + `][house_sitting_date]" value="">
</div>
</div>
<div class="choose-options">
<div class="yes-no-option" style="display:inline-grid;">
<select name="row_item[` + row_number + `][house_sitting_date_yes_no]" class="house-yes-no" style="height:24px; ">
<option value="nada">Please choose an option</option>
<option value="yes">Yes</option>
<option value="no">No</option>
</select>
</div>
</div>
</div>`;
}
</script>
I am trying to add items in my cart through Ajax call. I tried it doing simple just with php and it works fine. But now i am trying to convert my code for php+ajax. I have an index.php page in which i am dynamically changing my content. When i click on some nav list. It redirects me to page like this: index.php?page=item&category=Shirts&s_cat_id=2&cat_id=1 where page is passed through $_GET command every time a new page is called. I have a cart button on index.php header section.I want to refresh the div whose id is named as "cart". I am failing to do this through AJAX.Here i am pasting my code. Any suggestions or help will be appreciated.
cart div
<div id="cart">
<li style="color: #515151">
<img id="cart_img" src="images/cart.png">
Cart <span class='badge' id='comparison-count'>
<?php
if(isset($_SESSION['cart'])&& !empty($_SESSION['cart']))
{
$cart_count=count($_SESSION['cart']);
echo $cart_count;
}
else {
$cart_count=0;
echo $cart_count;
}
?>
</span>
</li>
</div>
item.php
<div>
<?php
$query=mysqli_query($con,"select * from products where cat_id='$cat_id' and s_cat_id='$s_cat_id' ORDER BY product_name ASC");
if(mysqli_num_rows($query)!=0){
while($row=mysqli_fetch_assoc($query)){
?>
<div>
<input type="hidden" id="pid" value="<?php echo $row['productid'] ?>">
<h4><?php echo $row['product_name']; ?></h4>
<h4>Price<?php echo "$" . $row['product_price']; ?> </h4>
<form method="post" action="">
<input type="hidden" id="page" name="page" value="items">
<input type="hidden" id="action" name="action" value="add">
<input type="hidden" id="id" name="id" value="<?php echo $row['productid']; ?>">
<input type="hidden" id="name" name="name" value="<?php echo $row['product_name']; ?>">
<input type="hidden" id="cat_id" name="cat_id" value="<?php echo $row['cat_id']; ?>">
<input type="hidden" id="s_cat_id" name="s_cat_id" value="<?php echo $row['s_cat_id']; ?>">
<input type="hidden" id="category" name="category" value="<?php echo $cat ?>">
<td>Colors:
<select name="color" id="color">
<option selected value="choose">choose</option>
<option value="blue" id="blue">Red</option>
<option value="blue" id="blue">Blue</option>
<option value="yellow" id="yellow">Yellow</option>
<option value="green" id="green">Green</option>
</select></td>
<td>Size : <select name="size" id="size"><option selected value="Choose size">Choose</option>
<option value="XL" id="XL">XL</option>
<option value="L" id="L">L</option></select>
</td>
</div>
<input type="submit" class="add-to-cart" id="addtocart" value="Add to Cart">
</form>
</div>
</div>
add_cart.php
<?php
include ("db/db.php");
session_start();
if($_POST){
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
//exit script outputting json data
$output = json_encode(
array(
'type'=>'error',
'text' => 'Request must come from Ajax'
));
die($output);
}
if(isset($_POST['Action']) && $_POST['Action']=="add" && isset($_POST['S_cat_id']) && isset($_POST['Cat_id']) ){
$id=intval($_POST['Id']);
$size = $_POST['Size'];
$color = $_POST['Color'];
$sql="SELECT * FROM products WHERE productid={$id}";
$data = mysqli_query($con,$sql);
if (mysqli_num_rows($data) == 1)
{
$row = mysqli_fetch_array($data);
$index = $id." ".$color. " ".$size;
if( isset($_SESSION['cart'][$index]) && isset($_SESSION['cart'][$index]['color']) && $_SESSION['cart'][$index]['color'] == $color && isset($_SESSION['cart'][$index]['size']) && $_SESSION['cart'][$index]['size'] == $size){
$_SESSION['cart'][$index]['quantity']++;
$output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
die($output);
}else{
$_SESSION['cart'][$index] = array('quantity' => 1,'id'=> $id, 'price' => $row['product_price'], 'size' => $size, 'color' => $color, 'name' => $row['product_name']);
$output = json_encode(array('type'=>'message', 'text' => ' You have updated record successfully!'));
die($output);
}
}
else{
$message="Product ID is invalid";
$output = json_encode(array('type'=>'error', 'text' => $message));
die($output);
}
}
}
?>
Ajax
<script>
$(document).ready(function() {
$('#addtocart').click(function(e){
e.preventDefault();
var page = $("#page").val(),
action = $("#action").val(),
name= $("#name").val(),
cat_id= $("#cat_id").val(),
s_cat_id = $("#s_cat_id").val(),
id=$("#id").val(),
color=$("#color").val(),
size=$("#size").val(),
category = $("#category").val();
var proceed = true;
if(proceed){
post_data= { 'Page': page, 'Action': action,'Name': name, 'Cat_id': cat_id,'S_cat_id':s_cat_id, 'Category': category,'Id':id,'Color':color,'Size':size};
$.post('add_cart.php', post_data, function(response){
//load json data from server and output message
if(response.type == 'error')
{
//output=$('.alert-error').html(response.text);
}else{
output= $("#cart").load();
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>
So, I'm assuming that your PHP code works and that the data is sent properly. I'm also assuming that your $.ajax call works. If one of these isn't true let me know.
You should be able to simply use jQuery to update the data of the div.
$("some div").html = response.text;
Or if you want to process the data before hand.
$("some div").html = process(response.text);
I am also assuming both the php and ajax codes work well...
All you need do is store the current value state of the div by saying something like
div=document.getElementById('elem_id');
oldv = div.firstChild.nodeValue;
and then appending the new result as
newv = oldv + responseMessage;
and finally saying
div.innerHTML=newv;
I believe this should work perfectly for your refresh request situation. You could adopt and adapt this idea in various conditions.
Note: I am also assuming that both the old and new values are either text/HTML contents not requiring any mathematical calculations
I have a select drop down on my form, of my categories from my database
Question: When I select a category from my select form, if it has a parent id
how am I able to attract that parent id to the hidden input value on my form.
Controller
<?php
class Pages extends Admin_Controller {
public function index() {
$this->load->model('admin/catalog/model_catalog_pages');
$data['page_categories'] = array();
$results = $this->model_catalog_pages->get_category();
foreach ($results as $result) {
if ($result['parent_id']) {
// If Child Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $this->model_catalog_pages->get_parent_name($result['parent_id']) .' > '. $result['name']
);
} else {
// If Parent Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $result['name']
);
}
}
$this->load->view('template/catalog/page_form_view', $data);
}
}
?>
View
<form action="" method="post" enctype="multipart/form-data" id="form-page" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" >Categories</label>
<div class="col-sm-10">
<select class="form-control" name="category_select" id="category_select">
<?php foreach ($page_categories as $category) {?>
<option value="<?php echo $category['category_id'];?>"><?php echo $category['name'];?></option>
<?php }?>
</select>
<input type="hidden" id="category_parent_id" name="category_parent_id" value="" />
</div>
</div>
</form>
The way I would tackle this problem is to add a data attribute to the dropdown menu options and then use some javascript to detect if its present. Try this:
<select class="form-control" name="category_select" id="category_select">
<?php foreach ($page_categories as $category) {?>
<option value="<?php echo $category['category_id'];?>" <?php echo isset($category['parent_id']?'data-parent_id="'.$category['parent_id]'"':'';?>><?php echo $category['name'];?></option>
<?php }?>
</select>
<input type="hidden" id="category_parent_id" name="category_parent_id" value="" />
The Javascript:
var dd = document.getElementById('category_select');
var hidden = document.getElementById('category_parent_id');
dd.addEventListener('change',selectParent,false);
function selectParent(){
for(var i in dd.options){
if(dd.options[i].selected == true){
if(dd.options[i].dataset.parentid){
hidden.value = dd.options[i].dataset.parentid
}else{
hidden.value = "";
}
}
}
}
selectParent();
Here is a fiddle of the javscript doing its thing, I've used type='text' input field in the fiddle to demonstrate that it works but this the code will still work with type='hidden'
http://jsfiddle.net/cpr63ajb/1/
Edit: I've tweaked the javascript so that when the page loads, it should select whatever is in the dropdown menu by default. This avoids the need of adding a dummy 'please select' option. (old JS code available here: http://jsfiddle.net/cpr63ajb).
Thanks to #Ben Broadley working now.
By his way on the option i added data-parentid and echoed parend id so looks like this now
data-parentid="<?php echo $category['parent_id'];?>
And added his script all working
<?php
class Pages extends Admin_Controller {
public function index() {
$this->load->model('admin/catalog/model_catalog_pages');
$data['page_categories'] = array();
$results = $this->model_catalog_pages->get_category();
foreach ($results as $result) {
if ($result['parent_id']) {
// If Child Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $this->model_catalog_pages->get_parent_name($result['parent_id']) .' > '. $result['name']
);
} else {
// If Parent Category
$data['page_categories'][] = array(
'category_id' => $result['category_id'],
'parent_id' => $result['parent_id'],
'name' => $result['name']
);
}
}
$this->load->view('template/catalog/page_form_view', $data);
}
}
?>
View
<form action="" method="post" enctype="multipart/form-data" id="form-page" class="form-horizontal">
<div class="form-group">
<label class="col-sm-2 control-label" >Categories</label>
<div class="col-sm-10">
<select class="form-control" name="category_select" id="category_select">
<?php foreach ($page_categories as $category) {?>
<option value="<?php echo $category['category_id'];?>" data-parentid="<?php echo $category['parent_id'];?>"><?php echo $category['name'];?></option>
<?php }?>
</select>
<input type="hidden" id="category_parent_id" name="category_parent_id" value="" />
</div>
</div>
</form>
<script type="text/javascript">
var dd = document.getElementById('category_select');
var hidden = document.getElementById('category_parent_id');
dd.addEventListener('change',function(e){
for(var i in dd.options){
if(dd.options[i].selected == true){
if(dd.options[i].dataset.parentid){
hidden.value = dd.options[i].dataset.parentid
}else{
hidden.value = "";
}
}
}
},0);
</script>