Hello I'm trying to delete a row in the database using ajax post but the problem is that the row gets deleted only once per page load. The row get detach from the HTML DOM everything I press the delete button, but the database only deletes one record. I want to delete therecord in the database every time I press the delete button. How can I achieve this ?
My view
<tbody id="tbody"><?php
$count = 1;
foreach($rows as $row):?>
<tr>
<td><?=$count?></td>
<td><a href="basic_table.html#">
<?=$row->FirstName." ".$row->LastName?></a>
</td>
<td class="hidden-phone"><?=$row->Email?></td>
<td><?=$row->Password?></td>
<td><span class="label label-warning label-mini">
<?=date("m/d/Y", strtotime($row->Created))?></span>
</td>
<td>
<button class="btn btn-success btn-xs">
<i class="fa fa-check"></i></button>
<button class="btn btn-primary btn-xs">
<i class="fa fa-pencil"></i>
</button>
<button id="delete" data-id="<?=$row->id?>"
data-url="<?=base_url()?>" class="btn btn-danger
btn-xs"><i class="fa fa-trash-o "></i>
</button>
</td>
</tr><?php
$count++;
endforeach?>
</tbody>
script
$(document).ready(function()
{
$("#tbody").on('click','#delete', function()
{
var id = $("#delete").data("id");
var url = $("#delete").data("url");
$.post(url + "users/delete", { id : id, cache: false } , function()
{
},"json");
$(this).closest('tr').detach();
});
});
Please give the codeigniter controller script
You must change to anchor tag and add preventDefault() to prevent reloading page
$(document).ready(function(){
$("#tbody").on('click','#delete', function(e){
//You must add e.preventDefault() to avoid reloading page
e.preventDefault();
var id = $("#delete").data("id");
var url = $("#delete").data("url");
$.post(url + "users/delete", { id : id, cache: false } , function(){
},"json");
$(this).closest('tr').detach();
});
});
Related
When I click on the delete modal of first row, the modal pops up and the data is getting deleted. If I click on the row other than the first row, it shows the error as id undefined.
Controller:
public function project_show(){
$this->load->view('project_show',$data);//page where delete button is present
$this->load->view('project_del');//modal page which opens on delete button
}
public function delete_get_id($pcode){
if($this->input->post('deleteproj'))
{
$this->project_model->delete_project($pcode);
}
}
ajax:
$('#deletebutton').click(function(){
var pcode = $(this).data('id');
$('#deleteproject').data('id', pcode);
});
$('#deleteproject').click(function(){
var pcode = $(this).data('id');
$('#deletemodal').modal('hide');
$('body').removeClass('modal-open');
$('.modal-backdrop').remove();
console.log(pcode);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "index.php/project/delete_get_id/"+ pcode,
data: {
pcode: pcode,
deleteproj: 1,
},
success: function (data) {
$("#deletemodal").modal('hide');
showproject();
}
});
});
view page of button:
<button id="deletebutton" class="btn btn-danger btn-xs" data-toggle="modal" data-target="#deletemodal" data-id="<?php echo $row->project_code;?>"><span class = "fa fa-trash-o"></span> Delete</button>
view page of modal:
<div class="modal fade bs-example-modal-sm" id="deletemodal" ...>
.....
<button class="btn btn-danger btn delete" id="deleteproject"><span class="glyphicon glyphicon-trash"></span>Delete</button>
How will I pass the id along with "data-target" tag from page where button is present to modal page so that the particular row gets deleted
Please note that ID selector is supposed to be unique in a HTML document. And jQuery expects that to be true. So instead of using ID, you should use class name for the delete button
$('.deletebutton').click(function(){
var pcode = $(this).data('id');
$('#deleteproject').data('id', pcode);
});
//...
<button
class="deletebutton btn btn-danger btn-xs"
data-toggle="modal"
data-target="#deletemodal"
data-id="<?php echo $row->project_code;?>"
>
<span class = "fa fa-trash-o"></span> Delete
</button>
Assuming your showproject() function won't accidentally remove / recreate your #deleteproject button, things should work for you.
I have a problem in getting the POST data from a page using ajax. In the jquery code the data is running smoothly and it will display when i alert the data. In the ajax request code the data from jquery has been successfully pass into showpercent.php file. Now the problem about showpercent.php, the data POST index percentage_id is unidentified. How can i fix this problem in getting the value of POST?
Below is the table list with button when the data is coming from.
<table>
<tr>
<td>
<button class="btn btn-info show-percentage" title="Click to add view percentages!" data-percentage_id="'.$row['hidden_id'] .'" data-toggle="show-percentage"><i class="glyphicon glyphicon-time"></i></button>
</td>
</tr>
</table>
Below is the ajax request sending the data into showpercent.php file. When I alert the percentage_id from button click the data will show in the alert and the ajax was successfully pass into specific php file which is showpercent.php.
<script>
$(document).ready(function(){
$(".show-percentage").click(function(){
var percentage_id = $(this).data('percentage_id');
alert("Ajax Landing ID "+landing_id);
$.ajax({
url: 'ajax/showpercent.php',
type: 'POST',
cache: false,
data: { percentage_id : percentage_id },
success: function(data) {
alert(data);
$('#add-percentage').modal('show');
readRecords();
},
error: function(request, status, error){
alert("Error!! "+error);
}
});
// READ recods when the button is click
readRecords();
});
function readRecords() {
$.get("ajax/showpercent.php", {}, function (data, status) {
$(".display_percentage").html(data);
});
}
});
</script>
Below is the modal having a tab will display the data from ajax request. The class display_percentage will display the current data from showpercentage.
<div id="add-percentage" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Fish Landing Percentage</h4>
</div>
<div class="modal-body">
<ul class="nav nav-tabs">
<li class="active"><a data-toggle="tab" href="#menu1">Add Percentage</a></li>
</ul>
<div class="tab-content">
<div id="menu1" class="tab-pane fade in active">
<br>
<div class="display_percentage"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" id="primary" class="btn btn-primary" onclick="AddPercentage()"> Add Percentage </button>
<button type="button" id="danger" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
showpercent.php
This file will read by readRecords() function to display into the modal with tab class display_percentage when the button click is triggered.
This is now the problem comes, when the data was successfully pass from ajax request the data POST in the showpercent.php is not properly set and cannot proceed to the mysql process because the POST is not set.
<?php
include 'db.php';
$data = '
<table">
<thead>
<tr class="success">
<th ><center>No.</center></th>
<th ><center>Percentage ID</center></th>
<th ><center>Landing ID</center></th>
<th><center>Percentage</center></th>
<th><center>Date Added</center></th>
</tr>
</thead>';
if(isset($_POST['percentage_id'])){
$landing_id = $_POST['percentage_id'];
$query = mysqli_query($conn, "SELECT
percentage.percent_id,
percentage.landing_id,
percentage.percentage,
percentage.date_recorded
FROM
percentage
WHERE percentage.landing_id = '$landing_id'");
$number = 1;
while($row = mysqli_fetch_array($query)) {
$data .= '
<tr>
<td><center>' . $number . '</center></td>
<td><center>' . $row['percent_id'] . '</center></td>
<td><center>' . $row['landing_id'] . '</center></td>
<td><center>' . $row['percentage'] . '%</center></td>
<td><center>' . date("M. d, Y", strtotime($row['date_recorded'])) . '</center></td>
</tr>';
$number++;
}
}else{
echo 'Percentage id is not set!';
}
$data .= '
</table>';
echo $data;
?>
But in the console the ajax passing data will run smoothly.
I wish anybody will help me to fix this problem.
I read your code your showpercent.php, javascript and html and soo far and notice this
<button class="btn btn-info show-percentage" title="Click to add view percentages!" data-percentage_id="'.$row['hidden_id'] .'" data-toggle="show-percentage"><i class="glyphicon glyphicon-time"></i></button>
and check this
data-percentage_id="'.$row['hidden_id'] .'"
you're doing it wrong this is not how you put php value into html value, this will return undefined in javascript if you try to get its value so
This is why
var percentage_id = $(this).data('percentage_id');
returns undefined in javascript and php
So replace it with this
data-percentage_id="<?php echo $row['hidden_id']; ?>"
So replace your button into like this
<button class="btn btn-info show-percentage" title="Click to add view percentages!" data-percentage_id="<? echo $row['hidden_id']; ?>" data-toggle="show-percentage"><i class="glyphicon glyphicon-time"></i></button>
thanks to #Keval Mangukiya
try:
add this in your html
<button id="percentage_id" class="btn btn-info show-percentage" title="Click to add view percentages!" data-percentage_id="<?=$row['hidden_id'] ?>" data-toggle="show-percentage"><i class="glyphicon glyphicon-time"></i></button>
set the value of your percentage_id before getting it
add to your JavaScript with
$("#percentage_id]").data('percentage_id',loading_id); //setter
var percentage_id = $(this).data('percentage_id'); //getter
I'm working on a laravel app, and I'm performing CRUD with JQuery Ajax. What happens is that when I try to first edit a record after insertion or page reload it works fine. But if I try to edit that record which have just been edited, the edit works but the changes isn't shown on the page or that particular row isn't replace.
To accomplish this I'm assigning every row a unique id when record is inserted into the table. This is how my code looks:
Table:
<tbody id="subjects">
#foreach($subjects as $subject)
<tr id="row{{$subject->id}}">
<td>{{$subject->name}}</td>
<td>{{$subject->level}}</td>
<td>
<a data-id="{{$subject->id}}" data-name="{{$subject->name}}" data-level="{{$subject->level}}" data-toggle="tooltip" title="Edit" id="edit-modal" href="#" role="buton">
<i class="glyphicon glyphicon-edit text-info"></i>
</a>
</td>
<td>
<a id="delete" data-id="{{$subject->id}}" data-toggle="tooltip" title="Delete" href="#" role="button">
<i class="glyphicon glyphicon-trash text-danger"></i>
</a>
</td>
</tr>
#endforeach
</tbody>
Script to insert record:
$(".box-footer").on('click', '.add-subject', function(event) {
event.preventDefault();
/* Act on the event */
var name = $('#name').val();
var level = $('#level').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: "/subjects",
data: {name: name, level: level},
success: function(data) {
if (data.errors) {
$('.errors').removeClass('hidden');
var errors = '';
for(datum in data.errors){
errors += data.errors[datum] + '<br>';
}
$('.errors').show().html(errors); //this is my div with
} else {
$('#subject-modal').modal('hide');
var html;
html += '<tr id="row"'+data.id +'">';
html += '<td>'+data.name+'</td>';
html += '<td>'+data.level+'</td>';
html += '<td><a id="edit-modal" data-id="'+data.id+'" data-name="'+data.name+'" data-level="'+data.level+'" data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-edit text-info"></i></a></td>';
html += '<td><a id="delete" data-id="'+data.id+'" data-toggle="tooltip" title="Delete" href="#" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a></td>';
html += '</tr>';
$("#subjects").append(html);
}
},
error: function(data) {
// body...
$('#subject-modal').modal('hide');
// display error
$('.errors').removeClass('hidden');
$('.errors').text('Ooops! There was an error. Please try again, and if error persits contact administrator');
}
});
});
Script to edit record:
$(".box-footer").on('click', '.edit-subject', function(event) {
event.preventDefault();
/* Act on the event */
// id of the row to be deleted
var id = $('#id').val();
var name = $('#name').val();
var level = $('#level').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/subjects/update/'+id,
type: 'PUT',
data: {name: name, level: level},
success: function (data) {
// body...
if (data.errors) {
var errors = '';
for(datum in data.errors){
errors += data.errors[datum] + '<br>';
}
// removing the errors class and displaying errors
$('.errors').removeClass('hidden');
$('.errors').show().html(errors);
} else {
$('#subject-modal').modal('hide');
var html;
html += '<tr id="row"'+data.id +'">';
html += '<td>'+data.name+'</td>';
html += '<td>'+data.level+'</td>';
html += '<td><a id="edit-modal" data-id="'+data.id+'" data-name="'+data.name+'" data-level="'+data.level+'" data-toggle="tooltip" title="Edit" href="#" role="button"><i class="glyphicon glyphicon-edit text-info"></i></a></td>';
html += '<td><a id="delete" data-id="'+data.id+'" data-toggle="tooltip" title="Delete" href="#" role="button"><i class="glyphicon glyphicon-trash text-danger"></i></a></td>';
html += '</tr>';
$('#row'+data.id).replaceWith(html);
console.log(data);
}
},
error: function(data) {
// display error
$('.errors').removeClass('hidden');
$('.errors').text('Ooops! There was an error. Please try again, and if error persits contact administrator');
}
});
});
Am I missing something in my code? Are there better ways I can do this? Please Help!
I suggest you do it as following:
Give each input a unique id, ex: id="name{{$subject->id}}".
The edit function should pass variable [ID] in your edit button like this: onclick="editModel({{$subject->id}});"
On function the code should work as following:
function editModel(id){
var name = $('#name'+id).val();
....
}
Now you can select each input with ease.
also you can send data including [ID] to edit in your backend.
Table is not not reachable by DOM when created after DOM ready, so you should give each input and Id to select.
i want to make a button click counter. When you click the button the text from it changes, when the button is clicked i want to write to the database but i can't manage this.
<button type="button" class="btn btn-info" style="width:90%;" id="textChanger" onclick="counter;"><h4><i class="glyphicon glyphicon-earphone" aria-hidden="true"> </i> XXXX XXX XXX <h6>Show Number</h6></h4></button>
document.getElementById("textChanger").onclick= function(){
document.getElementById("textChanger").innerHTML="<h4><i class=\"glyphicon glyphicon-earphone\" aria-hidden=\"true\"> </i> <?php echo $nrTelefonAnunt ?> </h4>";
}
this is the code that i manage the text change, now what can i do to write to the database, i tried some methods but none worked
Thanks everybody for the answers i manged by adding this:
$('#textChanger').click(function(){
$.ajax({
url : 'rate.php?idanunt="<?php echo $idAnunt ?>"',
type : 'post',
success : function(data){
}
});
});
Try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-info" style="width:90%;" id="textChanger" onclick="counter;">1</button>
<script>
document.getElementById("textChanger").onclick= function(){
var count = document.getElementById("textChanger").innerHTML;
count = parseInt(count) + 1;
document.getElementById("textChanger").innerHTML=count;
}
</script>
Try this
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<button type="button" class="btn btn-info" style="width:90%;" id="textChanger" onclick="counter;"><h4><i class="glyphicon glyphicon-earphone" aria-hidden="true"> </i> <span>XXXXX</span> <h6>Show Number</h6></h4></button>
<script>
count=0;
$(document).on("click","button",function(){
count++;
$('span').text(count);
});
</script>
I have a view which shows a table with rows of data from a local wamp database. Each row has a View, Edit and Delete button which allows a user to View, Edit and Delete records respectively.
Clicking on a row's Delete button will bring up a confirmation modal and is deleted when the modal's Delete button is clicked.
Right now, clicking on the Delete button throws up these errors:
Warning: setState(...): You passed an undefined or null state object; instead, use forceUpdate().
Uncaught TypeError: this.setState(...) is not a function
I also get a warning when trying to bind a variable:
Warning: bind(): React component methods may only be bound to the component instance. See GamePlatformTable
I've tried using forceUpdate in place of setState from stuff I've been searching, but I get the same 2nd errors. If it helps, I'm using php, CodeIgniter 3.0.3 and native React 0.14.3. I'm still relatively new to React, and thanks for helping.
Here's my code:
View:
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php
$this->load->view("templates/meta_common");
$this->load->view("templates/css_common");
?>
<title>Video Game Portal Admin</title>
</head>
<body>
<div class="container">
<?php $this->load->view("admin/admin_navbar"); ?>
<div class="page-header">
<h1>
<i class="text-info fa fa-file-text-o"></i> Browse Game Platforms
<span class="badge">REACT JS</span>
<button onclick="window.location.replace('<?= site_url("admin/game_platform/add_game_platform/") ?>')" type="button"
class="btn btn-danger"><i class="fa
fa-plus"></i> Add Game Platform
</button>
</h1>
</div>
<?php $this->load->view("admin/template_user_message"); ?>
<div id="GamePlatformTable">
</div>
<?php $this->load->view("admin/admin_footer"); ?>
</div>
<?php $this->load->view("templates/js_common"); ?>
<script src="<?=RESOURCES_FOLDER?>js/react.js"></script>
<script src="<?=RESOURCES_FOLDER?>js/react-dom.js"></script>
<script src="<?=RESOURCES_FOLDER?>js/JSXTransformer.js"></script>
<script src="<?=RESOURCES_FOLDER?>jsx/BrowseGamePlatform.js" type="text/jsx;harmony=true"></script>
<script type="text/jsx">
var gamePlatforms = <?=json_encode($game_platforms)?>;
ReactDOM.render(
<GamePlatformTable
gamePlatforms = {gamePlatforms}
siteUrl = "<?=site_url()?>"
/>,
document.getElementById("GamePlatformTable")
);
</script>
External React:
The error occurs in the deleteButtonClicked function of GamePlatformTable.
var rowIndex = 0;
var GamePlatformRow = React.createClass({
render: function () {
++rowIndex;
var developer = !this.props.gamePlatform.developer || this.props.gamePlatform.developer == "none" ?
<span className="text-placeholder">none</span> : this.props.gamePlatform.developer;
var year_intro = !this.props.gamePlatform.year_intro || this.props.gamePlatform.year_intro == "0" ?
<span className="text-placeholder">0</span> : this.props.gamePlatform.year_intro;
var logo_img = this.props.gamePlatform.logo_url ?
<img className="img-rounded" src={this.props.siteUrl + "/uploads/" + this.props.gamePlatform.logo_url}
alt={this.props.gamePlatform.abbr} width="50px" height="50px"/> :
<span className="text-placeholder">no logo</span>;
var view_action = <a
href={this.props.siteUrl + "/admin/game_platform/view_game_platform/" + this.props.gamePlatform.platform_id}
type="button" className="btn btn-default"><i className="fa fa-eye"></i> View</a>;
var edit_action = <a
href={this.props.siteUrl + "/admin/game_platform/view_game_platform/" + this.props.gamePlatform.platform_id}
type="button" className="btn btn-default"><i className="fa fa-file-text-o"></i> Edit</a>;
return (
<tr>
<td>{rowIndex}</td>
<td>{this.props.gamePlatform.platform_name}</td>
<td><span className="badge">{this.props.gamePlatform.abbr}</span></td>
<td>{logo_img}</td>
<td>{developer}</td>
<td>{year_intro}</td>
<td>
{view_action}
{edit_action}
<button type="button" className="btn btn-default"
onClick={this.props.deleteButtonClicked.bind(this, this.props.gamePlatform.platform_id)}><i
className="fa fa-trash"></i> Delete
</button>
</td>
</tr>
);
}
}); //end GamePlatformRow
var GamePlatformTable = React.createClass({
getInitalState: function () {
return {
gamePlatforms: this.props.gamePlatforms,
deletePlatformId: null
};
},
refreshTableData: function () {
var data = {
"gamePlatforms": this.props.gamePlatforms
};
$.ajax({
url: this.props.siteUrl + "game_platform/json_get_all_platforms",
dataType: "json",
data: data,
cache: false,
success: function (data) {
this.setState({gamePlatforms: data.gamePlatforms});
}.bind(this),
error: function (xhr, status, err) {
console.error(this.props.siteUrl + "game_platform/json_get_by_platform_id", status, err.toString());
}.bind(this)
});
},
confirmDeleteClicked: function () {
var data = {
"platform_id": this.state.deletePlatformId
}
$.ajax({
type: "POST",
url: this.props.siteUrl + "game_platform/json_delete_by_platform_id",
dataType: "json",
data: data,
success: function (data) {
this.refreshTableData();
}.bind(this),
error: function (xhr, status, err) {
this.refreshTableData();
}.bind(this)
});
},
deleteButtonClicked: function (platform_id) {
console.log("GamePlatformTable.deleteButtonClicked\nplatform_id: " + platform_id);
$("#ConfirmDeleteModal").modal("show");
this.setState()({
deletePlatformId: platform_id
}).bind(this);
},
render: function () {
var rows = [];
this.props.gamePlatforms.forEach(
function (gamePlatform) {
rows.push(<GamePlatformRow gamePlatform={gamePlatform} key={gamePlatform.platform_id}
siteUrl={this.props.siteUrl}
deleteButtonClicked={this.deleteButtonClicked}/>);
}.bind(this)
);
return (
<div className="table-responsive">
<table className="table table-hover" id="GamePlatformTable">
<thead>
<tr>
<th>#</th>
<th>Platform Name</th>
<th>Platform Abbr</th>
<th>Platform Logo</th>
<th>Platform Developer</th>
<th>First Release Year</th>
<th> </th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
<div className="modal fade" id="ConfirmDeleteModal">
<div className="modal-dialog">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-label="Close"><span
aria-hidden="true">×</span></button>
<h4 className="modal-title">Delete Game Platform</h4>
</div>
<div className="modal-body">
<p>Are you sure?</p>
<p>This action <strong className="text-danger">cannot</strong> be undone.</p>
</div>
<div className="modal-footer">
<button type="button" onclick={this.confirmDeleteClicked} className="btn btn-danger"
data-dismiss="modal"><i className="fa fa-trash"></i> Delete
</button>
<button type="button" className="btn btn-default" data-dismiss="modal"><i
className="fa fa-ban"></i> Cancel
</button>
</div>
</div>
</div>
</div>
</div>
);
}
}); // end GamePlatformTable
Edit 1:
Removing the .bind(this) removed the bind warning.
Edit 2:
I forgot to add, the console.logs() are showing the correct IDs.
Eh, I solved the prob.
I had parenthesis in front of setState.... like setState()({}) instead of setState({}).