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.
Related
So, I have a CRUD and one button to modify that should redirect to another page with the id of the person, I tried to do it with jquery this way
fetchList()
function fetchList() {
$.ajax({
url: 'lista.php',
type: 'GET',
success: function (response) {
let task = JSON.parse(response);
let template = '';
task.forEach(task => {
template +=
`<tr pacienteId="${task.id_pac}">
<td>${task.apellido} </td>
<td>${task.nombre}</td>
<td>${task.dni}</td>
<td>${task.fecha_nacimiento}</td>
<td>${task.fecha_ingreso}</td>
<td>${task.obra_social}</td
// <td <span class="badge pacActivo">Activo</span> </td>
<td>
<div class="btn-group btn-group-toggle d-flex justify-content-center">
<i class="fas fa-edit"></i>
<button class="btn btn-sm butDel darBaja">
<i class="fas fa-trash-alt"></i>
</button>
</div>
</td>
</tr>`
});
$("#listadoPacientes").html(template);
}
});
}
and this is the modify
$(document).on('click', '#modificar', function (e) {
var href = $(this).attr('href');
let element = $(this)[0].parentElement.parentElement.parentElement
let id = $(element).attr('pacienteId')
// Save information
// Check if any ID is aviable
if (id) {
// Save the url and perform a page load
var direccion = href + '&id=' + id;
window.open(direccion);
console.log(id)
} else {
// Error handling
alert('algo salio mal')
}
})
but the problem it that I get this error:
Undefined index: id in
C:\xampp\htdocs\sistema\modulos\Pacientes\modificar.php
where i have the ID from jquery inside a variable
Solution:
You append your href attribute in jQuery with only an "&". You need an "?" instead of an "&".
Solution: You put an GET parameter behinde your jQuery HTML build process href-tag.
Short you are generating an URL like:
modificar.php&id=0
correct is
modificar.php**?**id=0
Example:
if (id) {
// Save the url and perform a page load
var direccion = href + '?id=' + id; // changed the & to an ?
window.open(direccion);
console.log(id)
} else {
// Error handling
alert('algo salio mal')
}
To update the quantity of products in the shopping cart
I use buttons. But I'm doing something wrong. Can you help?
sepet.blade.php CODE
<a href="#" class="btn btn-outline-dark btn-xs azalt"
data-id="{{ $UrunCartItem->rowId }}"
data-adet="{{$UrunCartItem->qty-1}}">-</a>
<span style="padding: 4px 12px">
{{ $UrunCartItem->qty }}
</span>
<a href="#" class="btn btn-outline-dark btn-xs artir"
data-id="{{ $UrunCartItem->rowId }}"
data-adet="{{$UrunCartItem->qty+1}}">+</a>
Javascript CODE
<script>
$(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('.artir , .azalt').on('click' , function () {
debugger;
var id = $(this).attr('data-id');
var adet = $(this).attr('data-adet');
$.ajax({
type:'PATCH',
url:'/sepet/guncelle/' + id ,
data : { adet: adet } ,
success: function () {
window.location.href='/sepet';
}}); }); });
</script>
Page All Code
http://notes.io/8kex
At first, add event.preventDefault() under $('.artir , .azalt').on('click' , function () {.
Of course, you have to pass event like $('.artir , .azalt').on('click' , function (event) {)
Please, Share your Laravel code - maybe there is something not working or you have bug inside routes
PS: You don't need to pass new quantity inside the data-adet, but you can pass e.g. data-operation="plus" and data-operation="minus".
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.
This is the function that is called when button delete is pressed. After confirmation of delete, I want to hide the delete tr :
function delete_confirmation(id) {
var $tr = $(this).closest('tr');
swal({
title: "Are you sure?",
text: "To delete this patient!",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willDelete) => {
if (willDelete) {
$.ajax({
url: localStorage.getItem("base_url") + '' + 'index.php/Patient_ws/delete/',
timeout: 4000,
type: "POST",
data: ({id: id}),
}).done(function () {
$tr.remove();
})
.fail(function () {
swal({
title: ' erreur in server, try later...',
type: 'warning'
})
})
} else {
swal("Patient not deleted");
}
});
}
Html markup:
<a href="#" class="btn btn-danger btn-xs" onclick="delete_confirmation(<?php echo $patient->id_personne;?>)">
<i class="fa fa-trash-o"></i> Delete </a>
I want to hide tr - please help.
There is no explicit this in an onclick function unless you pass it in from the html. Try console.log(this) will see it is probably Window and not the element
Since you are already using jQuery I would suggest also using it for the event listener and moving the php output to a data attribute
HTML
<a class="delete-row-btn btn btn-danger btn-xs"
data-id="<?php echo $patient->id_personne;?>">
JS
$(document).on('click','.delete-row-btn', delete_confirmation)
function delete_confirmation(event) {
event.preventDefault();
// now `this` is the button
var id = $(this).data('id')
var $tr = $(this).closest('tr');
// all else should be same
swal({
.....
}
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();
});
});