Okay I have a html table given below:
<table class="table">
<thead>
<tr>
<th>Product</th>
<th>Quantity</th>
<th colspan="2">Total</th>
</tr>
</thead>
<tbody id="cart_table">
...
</tbody>
<tfoot>
<tr>
<th colspan="2">Total</th>
<th colspan="2">$446.00</th>
</tr>
</tfoot>
</table>
I am using ajax to append values clear tbody at every click of a button and refill the tbody with multidimensional session array. It works fine for 1st turn, but does not work for 2nd click
My jquery code is given below
<script>
$(document).ready(function(){
$('.addToCart').on('click',function(e){
$("#cart_table").empty();
var price = $(this).attr('data-price');
var item = $(this).attr('data-itemname');
e.preventDefault();
$.ajax({
method : "POST",
async: false,
url: "./php/addToCart.php",
dataType : "json",
data : {item:item,price:price},
success : function(response){
$("#cart_table").empty();
<?php
$i = 0;
foreach ($_SESSION["cart_array"] as $each_item):
$item = $each_item['item'];
$price=$each_item['price'];
$quantity=$each_item['quantity'];
?>
$('#cart_table').append("<tr><td><?php echo $item; ?></td><td><?php echo $quantity; ?></td><td><?php echo $price; ?></td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>");
<?php
endforeach;
?>
}
});
});
});
</script>
I have checked my session values are updated. However, the change is not shown on my table except for first click.
As pointed out in comments PHP is server side language, for it to reflect the changes, your page needs to reload but because you are using ajax page is not going to reload (Or rather we don't need it to reload).
It work for the first time because for the first time when page is loaded, the current data will already be present in your JavaScript function :
Right here :
$('#cart_table').append(<?php echo "<tr><td>".$item."</td><td>".$quantity."</td><td>".$price."</td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>";?>);
So what happens here is that when you click for the first time, your ajax will execute and success function is called, this function will add the already presented data because it will not update unless your page is reload. So every time you click, your session will be updated and success function is also called but your table will not reflect the changes.
So, You need to change your PHP code To JavaScript, Here the basic idea of what to do, (Here i have assumed your response is JSON, And also note that following code will not work out of the box because i didn't tested it.)
<script>
$(document).ready(function(){
$('.addToCart').on('click',function(e){
$("#cart_table").empty();
var price = $(this).attr('data-price');
var item = $(this).attr('data-itemname');
e.preventDefault();
$.ajax({
method : "POST",
async: false,
url: "./php/addToCart.php",
dataType : "json",
data : {item:item,price:price},
success : function(response){
$("#cart_table").empty();
//New JavaScript code, make appropriate changes.
jQuery.each(response, function(key, row) {
$('#cart_table').append("<tr><td>" + row.item + "</td><td>" + row.quantity + "</td><td>" + row.price + "</td><td><a href='#'><i class='fa fa-trash-o'></i></a></td></tr>");
});
}
});
});
});
Related
This question already has answers here:
Does ID have to be unique in the whole page?
(14 answers)
Closed 4 years ago.
I'm implementing delete functionality via AJAX but when i hit delete icon from the table, first element deletion request works fine and at first click it deletes the record, but it doesn't send deletion request for the 2nd or 3rd elements.
JS Ajax Request:
// Delete symptom which is linked with a Remedy ( Causes page )
$("#linked-symptom").click(function(e) {
e.preventDefault();
var symptom_id = $("#linked-symptom").attr('data-id');
var dataString = '&id='+symptom_id;
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-symptom') ?>',
success: function(data) {
$("#successMessage").show().delay(5000).fadeOut();
}
});
});
HTML Markup:
<table id="cx-records-table" class="table display table-striped table-bordered" width="100%">
<thead>
<tr>
<th>
Title
</th>
<th>
Delete
</th>
</tr>
<?php foreach($symptoms as $key => $symptom){ ?>
<tr>
<td class="all"><?php echo $symptom['title']; ?><br></td>
<td><a class="cx-action row-delete" href="javascript:void(0)" data-id="{{symptom['id']}}" id="linked-symptom"><i class="fa fa-trash-o"></i></a></td>
</tr>
<?php } ?>
</thead>
<tbody></tbody>
</table>
Function:
public function deldeleteLinkedSymptomAction(){
// Get the Evaluation Symptom Id (if any)
$symptomId = $this->request->get('id', null);
$symptom = CxEbEvaluationSymptomCause::getLinkedSymptomEntryForDeletion($symptomId);
if( $symptom ){
$symptom->delete();
return true;
}else{
return false;
}
}
HTML ID should be unique across the page, but you have multiple instances that you then try to use for a jQuery action. It will only affect the first one it finds. Try using this instead:
// Delete symptom which is linked with a Remedy ( Causes page )
$("a.row-delete").click(function(e) {
e.preventDefault();
var symptom_id = $(this).data("id");
var dataString = '&id='+symptom_id;
...
});
I have done my research and I can't seem to find the appropriate answer.
Here is the problem. First off, this question may be broad. And I am new to ajax. I am using laravel and I have just created a controller which handles two dates whereBetween to find the result set and ajax is handling the get request. I am having two issues.
First being, I have no idea on how to append to my existing table. The other issue is a bit complicated. Currently i am using carbons diffForHumans() to display the time taken.
Also using if else statements. Here is how my current table looks like (this is looped from controller for sample data. this is not ajax):
<table class="table">
<thead>
<tr>
<th>Room Number</th>
<th>Cleaned By</th>
<th>Total Time</th>
<th>Supervised</th>
<th>Issues</th>
<th>Cleaned</th>
<th>View</th>
</tr>
</thead>
<tbody>
#foreach($clean as $cleans)
<tr>
<td>{{$cleans->roomnumber}}</td>
<td>{{$cleans->users->name}}</td>
<td>{{$cleans->roomnumber}}</td>
#if($cleans->verified == 1)<td class="verified">Yes</td>#else()<td class="notverified">No</td>#endif
#if($cleans->img1 || $cleans->img1 || $cleans->img1 == !null)<td class="verified">Yes</td>#else()<td class="notverified">No Issues</td>#endif
<td>{{$cleans->created_at->diffForHumans()}}</td>
<td><i class="lnr lnr-eye"></i></td>
</tr>
#endforeach
</tbody>
</table>
As shown above, i have used with() in my controller to get the users name using user_id column. And the diffForHumans(). Also some if else statements.
Here is my AJAX so far:
$(function() {
$('.form').submit(function(event) {
// get the form data in value key pair using jquery serialize
var data = $(this).serialize();
// get the url we are posting to from the forms action attribute
//var url = $(this).attr('/admin/search');
// process the form
var search = $.ajax({
type: "POST", // define the type of HTTP verb we want to use (POST for our form)
url: "search", // the url where we want to POST
data: data, // the url where we want to POST, set in variable above
dataType: "json", // what type of data do we expect back from the server
encode : true
})
// using the done promise callback (success)
search.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});//submit function
});//doc ready end
So how can I append to the above table and still maintain those diffForHumans(), if else statements and most importantly the user name using user_id column (relation)?
Update (Controller):
public function search(Request $request){
$data = $request->only(['from', 'to']);
$data['to'] .= ' 23:59:59';
$output = Clean::whereBetween('created_at', $data)->get();
//return view('admin/search-test', compact('output'));
//return Response($output);
return Response::json(array($output));
}
In my project (some kind of online game store), i have a jQuery generated table from click on original table row. The original table is populated from mysql database. On submit i need to send that generated table to another php page. I'm quite new with it and so far this is my code:
on php_first.php
generated table
<form action="php_second.php" id ="form_send" name ="form_send1" method="POST">
<div>
<table id="generated_table" style="display:none" name ="generated_table1">
<tr><th>Game</th><th>Platform</th> <th>Genre</th> <th>Price</th><tr>
// generated rows here
</table>
<input type="submit" value="Confirm" id="btnOrder" style="display:none"></input>
</div>
</form>
generated rows
$(document).ready(function(){
$('#original_table tbody tr').click(function(){
var data = $(this).children("td").map(function(){
return $(this).text();
}).get();
var row= '<tr name ="new_row"><td name = "game">' + data[0] + '</td><td name = "platform">' + data[1] +
'</td><td name = "genre">' + data[2] + '</td><td name = "price">' + data[3] +
'<button type="button" onclick="remove(this)" class ="btn_remove">Remove</button>' +'</td></tr>';
$("#generated_table tbody").append(row);
$('#generated_table').show();
$('#btnConfirm').show();
});
ajax post to php_second.php
$('#btnOrder').click(function(){
var table= $('#generated_table');
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {data: table},
async: false,
success: function(data){
alert(data);
}
});
However, ajax dosen't do alert(data) so i asume this is the problem but i cant determine it.
and on php_second.php
<table id="table_order" name = "table_order1" style="display:show">
<?php
if(isset($_POST['generated_table'])){
$table= $_POST['generated_table'];
echo $table;
}
?>
</table>
The problem is that i cannot post table data to another php (and print that table on other php when redirected). Tried to use ajax to send row data on row click, or passing div where table is but nothing. It shows no errors but no data is passed.
This is my first question so it is possible that i missed out some details to make the problem more clear. Thanks!
EDIT
I've tried Kalaikumar Thangasamy's code and ajax is working fine now, but the problem is on other php page.
<?php
if(isset($_POST['data'])){
$table = $_POST['data'];
echo $table;
}
else {
echo "None selected";
}
?>
The $_POST['data'] or any other parameter from first php is always null.
Change data: {data: table} to data: {'generated_table': escape(table)}. Posting data as but referring post data in $_POST['generated_table']. You suppose to be used $_POST['data']. Try this
var table= $('#generated_table').html();
$.ajax({
url: 'php_second.php',
type: 'POST',
data: {'generated_table': escape(table)},
async: false,
success: function(data){
alert(data);
}
});
The Problem: When I click on a pagination link the script is generating the new html table content, but it's not refreshing the table in the browser.
I have class user with method called showUsers($limit, $offset) which is fetching all the data I need and displaying it in table.
<table id="table" class="table table-striped table-bordered table-hover table-sm">
<thead class="thead-default">
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Nickname</th>
<th>User ID</th>
</tr>
</thead>
<?php $user->showUsers($limit, $offset); ?>
</table>
this is my offset varaible: $offset = ($page - 1) * $limit, $page is the number of the pressed pagination link.
This is how I generate the pagination links:
<div class="col-sm-9 mx-auto">
<?php
for ($i=1; $i <= $allPages ; $i++) {
echo "<span class='pag-link' id='$i' style='cursor: pointer; padding: 6px; border: 1px solid #ccc; margin: 3px;'>". $i. "</span>";
}
?>
</div>
This is my JS Script:
//pagination-link handler.
$('.pag-link').click(function(){
var page = $(this).attr("id");
console.log(page);
$.ajax({
type: "POST",
url: "info.php",
data: {page: page},
success: function(data){
console.log(data); // show response from the php script.
}
});
});
setInterval(function(){ $(`#table`).load('info.php #table'); }, 1000);
Note: setInterval(function(){ $("#table").load('info.php #table'); }, 1000); should get the HTML in the table and update the table in the browser with the new table.
So when I click, a page the number is send in the info.php file. This changes my $offset variable and the showUsers($limit, $offset) method will generate new table with different data.
Now this is working because I'm seeing all new HTML that is generated in the javascript console, but setInterval(function(){ $("#table").load('info.php #table'); }, 1000); is not working and my table is not update.
Note: I want to refresh the table in interval, because if multiple users input data I want it to be updated to everyone in real time.
.load('info.php #table') doesn't have the page parameter.
So you load the page ("info.php"), click the next pagination link (url: "info.php",data: {page: page}), and that works, but then the timer loads info.php again, replacing the data.
This will require moving the "var page;" to the top of the Javascript, outside the function call:
//pagination-link handler.
var page=1;
$('.pag-link').click(function(){
page = $(this).attr("id");
console.log(page);
$.ajax({
type: "POST",
url: "info.php",
data: {page: page},
success: function(data){
console.log(data); // show response from the php script.
}
});
});
setInterval(function(){ $(`#table`).load('info.php?page='+page+'#table'); }, 1000);
The PHP that fills $offset will need to respond to both GET and POST, such as $_REQUEST.
I have searched and tested different solutions all day without luck. In the below code I want (when clicked) to set a session on the "open" links I echo in the foreach loop. I tried using AJAX but I am new to AJAX and could not make it work. I know how to do it using GET but it is too risky, so i welcome your suggestion and preferably examples.
$task_array = array_combine($task_id_unique, $task_status);
foreach ($task_array as $card_nr => $card_status) {
?>
<table>
<tr>
<th>card nr.</th>
<th>Status</th>
</tr>
<td><?php
echo $card_nr;?></td>
<td>
<?php
if ($card_status == true) {
echo "<a href=workcard.php>Open</a>";
}
else echo "Done ". $card_nr;?></td>
</table>
What have you tried and what doesn't work, because this looks like what you need...
HTML:
Register Now!
PHP:
if(isset($_GET['a'])){
$_SESSION['link']= 'whatever';
}
And if you need to do it without a page refresh, then use AJAX.
You should use ajax on click of link:
$.ajax({
url: 'test.php',
dataType: 'json',
type: 'post',
data: {name: "value", name2: "value2" /* ... */},
success: function (data) {
}
});
in your test.php, $_POST['name'] is equal to "value". and there you can do everything you want.
first, add html class on "Open" link and custom html5 attribute to store your card data. for example data-card.
Open
next, create Onclick event for a link to send an ajax request.
$( document ).ready(function() {
$(".your-class").click(function() {
var card_nr = $(this).attr('data-card');
$.ajax({
url: "workcard.php",
type: "POST",
data: "card=" + card_nr
}).done(function() {
// do something
});
return false;
});
});