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')
}
Related
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({
.....
}
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'm trying to remove the record in database via ajax. In the same time I want to delete also the record from the page. So I have this in my HTML
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<a href="?delete='.$row['id'].'" class="del">
<i class="fa fa-trash "></i>
</a>
</div>
</div>
</div>
</li>
</ul>
This is inside the loop which display all records on page. This is the ajax function
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
var parent = $(this).parent();
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + parent.attr('id').replace('record-',''),
beforeSend: function() {
parent.animate({'backgroundColor':'#fb6c6c'},300);
},
success: function() {
parent.slideUp(300,function() {
parent.remove();
});
}
});
});
});
And my delete.php is simple delete query
$stmt = $pdo->prepare("DELETE FROM comment where id = :id");
$stmt->bindParam(':id', (int)$id, PDO::PARAM_INT);
$stmt->execute();
Current error is from the ajax when I click on delete on this line index.php:183 Uncaught TypeError: Cannot read property 'replace' of undefined
Uncaught TypeError: Cannot read property 'replace' of undefined
The ajax part is from tutorial since I'm very unfamiliar with js/ajax.
What can be the problem here?
In your function $(this) = <a href="?delete='.$row['id'].'" class="del">.
var parent = $(this).parent(); = <div class="comment-head">
which has no ID. Thus attr('id') returns undefined.
You can select the ul element this way:
var parent = $(this).closest('ul.comments-list.record');
How about this code: (make full use of jquery)
<ul id="comments-list record-'.$row['id'].'" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">'.$row['author'].''</h6>
<i onclick="del(<?=$row['id']?>)" class="fa fa-trash "></i>
</div>
</div>
</div>
</li>
your jquery becomes:
function del(i)
{
$.ajax({
type: 'get',
url: 'delete.php',
data: {'ajax':1,'delete':i},
success: function() {
get_list();
}
});
}
function get_list()
{
//make ajax call to get data from php
}
You are getting undefined because the parent you are fetching is this one:
<div class="comment-head">
As you can see that does not have an id. That is why you are getting undefined.
For reference, I do not believe that there is a replace() method in jQuery. What you might be looking for is a replaceWith() method. Please refer to the documentation for more information.
I do not believe that you need to do a replace anywhere. From what I can understand, you want to pass the row[id] as a parameter on your AJAX call. Instead of trying to do a replace, use data as shown below:
<script
src="https://code.jquery.com/jquery-2.2.4.js"
integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI="
crossorigin="anonymous"></script>
<style>
#comments-list {
border: 1px solid black;
}
</style>
<ul id="comments-list" data-id="1" class="comments-list record">
<li>
<div class="comment-main-level">
<div class="comment-box">
<div class="comment-head">
<h6 class="comment-name by-author">Me</h6>
<a href="?delete=1" class="del">
click here
</a>
</div>
</div>
</div>
</li>
</ul>
<script>
$(document).ready(function() {
$('.del').click(function(e) {
e.preventDefault();
// Grab the id
var commentsBlock = $('#comments-list');
var id = commentsBlock.data('id');
console.log(id);
$.ajax({
type: 'get',
url: 'delete.php',
data: 'ajax=1&delete=' + id,
success: function() {
commentsBlock.slideUp(300,function() {
commentsBlock.remove();
});
}
});
});
});
</script>