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>
Related
This form contains a dropdown list that has multiple options with checkboxes, now when a user selects 1 or more checkboxes and presses submit, the values should be processed with the matching search results. Previously, I had a select tag with an option tag that was used to get the results. Now, since I added the functionality of searching for more than one option, I added checkboxes, but now I am not sure how to get the results.
Html and Php Code
<form action="<?php the_permalink() ?>" class="ajax-search-form leaders-header" id="searchform" method="post" role="search">
<?php get_template_part( 'blocks/leaderboard/search-form' ) ?>
<div class="sort">
<body>
<?php if ($departments = get_field_object('field_5da06da87ae0f')) : ?>
<div class="sort-item">
<div id="list1" class="dropdown-check-list" tabindex="100">
<span class="anchor" style="font-size: small">All Departments</span>
<ul id="items" class="items" name="department" >
<label for="test">
<?php foreach ($departments['choices'] as $key => $department) : ?>
<input type="checkbox" name="check" id="test" value="unchecked" /> <option style="font-size: small" <?php if ( isset($_REQUEST['role']) and $_REQUEST['role'] == $key) echo 'selected' ?> value="<?php echo $key; ?>">
<?php echo $department; ?></option></label></br>
<?php endforeach; ?>
<input style="font-size: small" type="submit" value="Submit" "/>
</ul>
</div>
</div>
<?php endif ?>
</body>
JavaScript:
<script type="text/javascript">
var checkList = document.getElementById('list1');
var items = document.getElementById('items');
var isChecked = document.getElementById('items').checked;
checkList.getElementsByClassName('anchor')[0].onclick = function (evt) {
if (items.classList.contains('visible')){
items.classList.remove('visible');
items.style.display = "none";
}
else{
items.classList.add('visible');
items.style.display = "block";
}
}
items.onblur = function(evt) {
items.classList.remove('visible');
}
</script>
Problem is that every checkbox will have the same name and id so you will be not able to recognize which option belongs to which checkbox but you can try something like this
<?php foreach ($departments['choices'] as $key => $department) : ?>
<input type="checkbox" name="<?= $department ?>" id="<?= $department ?>" value="unchecked" />
I'm trying to get different data to display based on a select value. This select is in a Bootstrap modal which I am displaying different products by running a loop. I already have all of the data that I need without running an AJAX request, although I think that I may need to run one to display the data now.
What I'm trying to do is:
Output the amount of stock from row['size_sm'] if I select small or from row[size_lg] if I select large and so on.
Hide size from the select if the size is out of stock. My method does not seem to be working as options are still showing even when they are out of stock.
Here is my code. I'm passing the value from the database via the div classes inside of the link clicked to open the modal that do not show on the page as they are empty but it does not seem to work for the stock sizes.
I don't really understand AJAX, if that is the way to go about this, and I am stuck. What is my best route here? I don't really want to build the whole modal again as I have a carousel inside the body which works fine displaying
pic1, pic2, pic3 from the database.
$(document).ready(function() {
$(".t_shirt_pic_main").on('click', function() {
// // get the title of current item and add to modal from the "value" of the item a link that opens modal
var title = $(this).attr("value");
// get the image by going inside the a link to the image.. faster than first child
var main_pic = $(this).find('.main_img').attr('src');
var second_pic = $(this).find('.pic2').attr('rel');
var third_pic = $(this).find('.pic3').attr('rel');
var price = $(this).find('.price').attr('rel');
var stock_xl = $(this).find('.stock_xl').attr('rel');
var stock_lg = $(this).find('.stock_lg').attr('rel');
var stock_md = $(this).find('.stock_md').attr('rel');
var stock_sm = $(this).find('.stock_sm').attr('rel');
// get the title of current item and add to modal from the "value" of the item a link
$("#modal_title").text(title);
// change modal pics to the ones from the clicked on item getting values from hidden inputs
$("#first_slide").attr('src', main_pic);
$("#second_slide").attr('src', second_pic);
$("#third_slide").attr('src', third_pic);
// add price in the bottom of modal
$('#modal_price').html('£' + price);
if (stock_sm == 0) {
$('#option_small').hide()
}
if (stock_sm != 0) {
$('#option_small').show()
}
if (stock_md == 0) {
$('#option_medium').hide()
}
if (stock_md != 0) {
$('#option_small').show()
}
if (stock_lg == 0) {
$('#option_large').toggle()
}
if (stock_lg != 0) {
$('#option_large').show()
}
if (stock_xl == 0) {
$('#option_extralarge').toggle()
}
if (stock_xl != 0) {
$('#option_extralarge').show()
}
$("#t_shirt_and_jumper_modal").modal('show');
});
});
while($row = mysqli_fetch_assoc($result)){ ?>
<div class="col-lg-3 col-md-6 products">
<a class="t_shirt_pic_main" href="javascript:void(0)" value="<?php echo $row['title'] ?>" rel="<?php echo $row['id'] ?>">
<!-- hidden values to pass to jquery for the modal -->
<div class="stock_xl" rel="<?php echo $row['size_xl'] ?>"></div>
<div class="stock_lg" rel="<?php echo $row['size_lg'] ?>"></div>
<div class="stock_md" rel="<?php echo $row['size_md']; ?>"></div>
<div class="stock_sm" rel="<?php echo $row['size_sm'] ?> "></div>
<div class="pic2" rel="<?php echo $row['image_2'] ?>"></div>
<div class="pic3" rel="<?php echo $row['image_3'] ?>"></div>
<div class="price" rel="<?php echo $row['price'] ?>"></div>
<img class="img-fluid main_img" src="<?php echo $row['image_1'] ?> ">
</a>
<h5 class="item_title"><?php echo $row['title'] ?></h5>
<p class="price_para">£<?php echo $row['price'] ?></p>
</div>
<?php include "includes/t_shirt_and_jumper_modal.php" ?>
<?php } ?>
<!-- Here is the modal i thought it would be easier to read putting it underneath instead of in the loop -->
<div class="modal-footer">
<form action="basket.php" method="post">
<div class="form-group">
<label for="size">Size</label>
<? here i would like to hide the size from the select if the stock is empty ?>
<select name="size" id="size">
<option id="option_small" value="sm">small</option>
<option id="option_medium" value="md">medium <span id="available"></span></s>
</option>
<option id="option_large" value="lg">large <span id="available"></span></s>
</option>
<option id="option_extralarge" value="xl">x-large <span id="available"></span></s>
</option>
</select>
</div>
<? HERE IS WHERE I WANT THE INFO $row[size_selected] to display once i choose a size. ?>
<p> Available: <span id="available"> </span> </p>
<div class="form-group">
<label for="quantity">Quantity</label>
<input type="text" id="quantity" name="quantity"> <br>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary"> Add to basket <i class="fa fa-shopping-basket" aria-hidden="true"></i></button>
</div>
</form>
</div>
</div>
</div>
sorted now i was able to do it without a ajax call and just by passing the values via div attributes it was still holding the id from the last item clicked on as it was in a loop and i was able to fix it with jquery and javascript i used on change in the select to display amounts of stock and the .remove to clear the modal of previous item when it was closed here is the code i used incase anybody else has the same problem ` // size
$('#size').change(function(){
var selected_size = $(this).children("option:selected").val();
if(selected_size == "sm"){
$('#display_stock').html( stock_sm )
};
if(selected_size == "md"){
$('#display_stock').html( stock_md )
};
if(selected_size == "lg"){
$('#display_stock').html( stock_lg )
};
if(selected_size == "xl"){
$('#display_stock').html( stock_xl )
};
});
// clears modal so that we dont pick up ids from previously clicked on stock
//and so select size returns to please choose
$('#t_shirt_and_jumper_modal').on('hidden.bs.modal', function () {
// location.reload();
setTimeout(function(){
$('#t_shirt_and_jumper_modal').remove();
},500)
});`
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() );
});
I hava a PHP MVC project. I read data from database and create a form for each record. I want to make update when pressed the button which it is in the form. But I confused how I can access form elements in javascript function. I used an index for each record but I could not overcome how I can find it in javascript.
My php file:
$index = 1;
foreach ($categories as $category) {
?>
<div class="row">
<form id="updateForm">
<div style="visibility: hidden">
<input type="text" name="editId<?php echo "$index"?>" id="editId<?php echo "$index"?>" value="<?php echo $category['id']; ?>">
</div>
<div class="form-group col-md-4">
<input type="text" class="form-control" name="editTitle<?php echo "$index"?>" id="editTitle<?php echo "$index"?>"
value="<?php echo $category['title']; ?>">
</div>
<div class="form-group col-md-4">
<select class="form-control" name="editline<?php echo "$index"?>" id="editline<?php echo "$index"?>">
<option disabled selected value="">Sıra</option>
<?php
for ($i = 1; $i <= $rows; $i++) {
?>
<option value="<?php echo $i; ?>"><?php echo $i; ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-1">
<a class="btn btn-success" id="btnUpdateSubmit" name="btnUpdateSubmit" href="<?php echo BASE_URL; ?>/category"
onclick="updatecategory();"><i class="fa fa-check"></i> Kaydet</a>
</div>
<div class="form-group col-md-1">
<a class="btn btn-danger" href="#"><i class="icon-trash icon-large"></i> Sil</a>
</div>
</form>
</div>
<?php
$index++;
And my javascript function:
function updatecategory() {
if (window.XMLHttpRequest){
xmlhtpp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhtpp.onreadystatechange = function () {
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("existCategories").innerHTML = xmlhtpp.responseText;
}
};
xmlhtpp.open("POST", '<?php echo BASE_URL ?>/category');
}
remove the ID from the form - IDs must be unique.
Change the links to submit buttons
add an event hander:
window.onload=function() {
var forms = document.getElementsByTagName("form");
for (var i=0;i<forms.length;i++) {
forms[i].onsubmit=function() {
updateCategory(this);
return false; // cancel submit
}
}
}
then have
function updatecategory(theForm) {
var categoy = theForm.elements[0].value; // editIdxxx
I currently have a div which when clicked posts data to another page and reloads the div. I would like to add a back button (#backref) to the new div to take me back to the previous div. I have found several posts on this whereby you add display:none; to the div you want to browse to, but obviously this is my initial div so I cannot use that css. Any suggestions on how to get round this would be appreciated!
Code I am using to achieve this:
$(document).ready(function () {
$('.clickthrough2').click(function () {
// get car id
carId = $(this).attr('id'); // get the car id to access each class element under the car div container
$.post('referrer-ajax2.php', {
clickthrough: $('#car-'+carId+' .clickthrough').val(),
ref_date_from2: $('#car-'+carId+' .ref_date_from2').val(),
ref_date_to2: $('#car-'+carId+' .ref_date_to2').val()
},
function (data) {
$('#car1').html(data);
});
});
});
index.php:
<div id="car1" class="declined3 statdivhalf2">
<h4>Select Car</h4>
<div class="statgrid">
<?php
$result=$ mysqli->query($sql);
if($result->num_rows === 0) { echo 'No Cars in selected time period.'; }
else { while ($row = $result->fetch_array()) {
?>
<div id="car-<?php echo $row['car_id'];?>">
<input type="hidden" class="ref_date_from2" value="<?php echo $date_from; ?>" />
<input type="hidden" class="ref_date_to2" value="<?php echo $date_to; ?>" />
<input type="hidden" class="clickthrough" value="<?php echo $row['car_name'] ?>" />
<a><div id="<?php echo $row['car_id'];?>" class="clickthrough2 col-5-6"><?php echo $row['car_name'] ?></div></a>
</div>
<div class="col-1-6">
<?php echo $row[ 'quantity']; ?>
</div>
<?php } } ?>
</div>
</div>
referrer-ajax2.php:
<div id="car1" class="declined4 statdivhalf2">
<h4>Car Details</h4>
<div class="statgrid">
<?php
$result=$ mysqli->query($sql);
if($result->num_rows === 0) { echo 'No Cars in selected time period.'; }
else { while ($row = $result->fetch_array()) {
?>
<div id="clickthrough2" class="col-5-6"><?php echo $row['car_details'] ?></div>
<div class="col-1-6"><?php echo $row[ 'quantity']; ?></div>
<?php } } ?>
<a><div id="backref">< Back</div></a>
</div>
</div>
EDIT: I have tried the below be it did not work:
$('#backref').click(function () {
$('.declined4').hide();
$('.declined3').show();
});
Instead of reloading the div with the new content you could create a new div each time hiding the old one. You would then cycle through them by indexing each div with either an id or (probably better) a "data-" attribute.