Jquery Updated table view after successfull operation - php

I have a table in a page for example:-
<tr>
<th>no</th>
<th>name</th>
<th>age</th>
<th>actions</th>
</tr>
<tr>
<td>$i</td>
<td>$name</td>
<td>$age</td>
<td>Delete</td>
</tr>
on the click of the delete it will go the controller through jquery and successfully delete the row, after that I want to show the updated table means without that deleted row. for this now I'm using another page and with the table data, on success I'm doing like this:
$(.updated_table_view).html(data.view);
is there any other simple way to do this like without an another page?

Presumably "...will go the controller through jquery..." means via Ajax, so if you want it to just do a simple removal, just hide the row:
jsFiddle: https://jsfiddle.net/842x2wuc/
<script>
$(document).ready(function(){
$('.delete').click(function(e) {
e.preventDefault();
var thisBtn = $(this);
$.ajax({
url: '/link/to/delete.php',
type: 'post',
data: { id: thisBtn.attr('href') },
success: function(response) {
// This will fade out the row
thisBtn.closest('tr').fadeOut('fast');
}
});
});
});
</script>

Related

ajax is loading data twice from database using laravel php

hi i am trying to load data from database using ajax . but the data is loading twice on the html page.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('button').click(function(){
$.ajax({
url:"{{route('zaeemajax')}}",
method:"get",
datatype:"json",
success:function(response){
console.log(response);
var tabledata="";
$.each(response,function(key,value){
tabledata +="<tr>";
tabledata +="<td>"+value.name+"</td>";
tabledata +="<td>"+value.price+"</td>";
tabledata +="<td>"+value.category+"</td>";
tabledata +="</tr>";
});
$('#show tbody').append(tabledata);
}
});
});
</script>
in my controller i am return product data as json
public function showallpro()
{
$product=Product::all();
return response()->json($product);
}
there are only two fields right now in the products table but wheneever i try to fetch data from database it is showing the same data twice
here is the html code where i am trying to show the fecthed data from the data base
<table id="show" style="border: 1px solid black;">
<tr>
<th>name</th>
<th>Price</th>
<th>Category</th>
</tr>
<tbody>
</tbody>
</table>
<button type="">Show Data</button>
the only problem i was having that data was loading twice so i made the following changes and it worked
i changed this
$('#show').append(tabledata);
instead of
$('#show tbody').append(tabledata);

I want to grab the UID of clicked row using ajax from foreach loop php but getting all UID

I'm trying to get the UID from an anchor tag which is the value of ID attribute of the anchor tag from a foreach loop PHP in ajax. But it only work once a time, when I click the anchor tag again then all the UIDs are grabbed in the ajax!
When I click on anchor tag then 1st I'm displaying a bootstrap 4 modal and in modal a textarea tag is present with a button and when I click button then I've to send uid and message again to the action.php page
This is my action.php code
if(isset($_POST['action']) && $_POST['action'] == 'fetchAllFeedback'){
$feedback = $admin->fetchFeedback();
$output = '';
if($feedback){
$output .= '<table class="table table-striped table-bordered text-center">
<thead>
<tr>
<th>FID</th>
<th>UID</th>
<th>User Name</th>
<th>User E-Mail</th>
<th>Subject</th>
<th>Feedback</th>
<th>Sent On</th>
<th>Action</th>
</tr>
</thead>
<tbody>';
foreach ($feedback as $row) {
$output .= '<tr>
<td>'.$row['id'].'</td>
<td>'.$row['uid'].'</td>
<td>'.$row['name'].'</td>
<td>'.$row['email'].'</td>
<td>'.$row['subject'].'</td>
<td>'.$row['feedback'].'</td>
<td>'.$row['created_at'].'</td>
<td>
<i class="fas fa-reply fa-lg"></i>
</td>
</tr>';
}
$output .= '</tbody>
</table>';
echo $output;
}
else{
echo '<h3 class="text-center text-secondary">:( No any feedback written yet!</h3>';
}
}
This is feedback.php ajax code
$("body").on("click", ".feedbackReplyIcon", function(e){
let uid = $(this).attr('id');
$("#feedback-reply-btn").click(function(e){
if($("#feedback-reply-form")[0].checkValidity()){
let message = $("#message").val();
e.preventDefault();
$("#feedback-reply-btn").val('Please Wait...');
$.ajax({
url: 'assets/php/admin-action.php',
method: 'post',
data: {uid:uid,message:message},
success:function(response){
console.log(response);
$("#feedback-reply-btn").val('Send Reply');
$("#showReplyModal").modal('hide');
$("#feedback-reply-form")[0].reset();
}
});
}
});
});
Here is what I believe happens: Since you declare a click method inside another click method, the uid variable turns empty after the first use. It's generally a bad practice to stack events like this inside one another. Try changing your javascript to this:
var uid;
$("body").on("click", ".feedbackReplyIcon", function(e){
uid = $(this).attr('id');
});
$("#feedback-reply-btn").click(function(e){
if($("#feedback-reply-form")[0].checkValidity()){
let message = $("#message").val();
e.preventDefault();
$("#feedback-reply-btn").val('Please Wait...');
$.ajax({
url: 'assets/php/admin-action.php',
method: 'post',
data: {uid:uid,message:message},
success:function(response){
console.log(response);
$("#feedback-reply-btn").val('Send Reply');
$("#showReplyModal").modal('hide');
$("#feedback-reply-form")[0].reset();
}
});
}
});
This might still be less than optimal, I'm a bit unclear on how your elements are laid out, and I can't really test it out. Let me know on what happens - if it still doesn't work, try dumping out the variables in admin-action.php , and see what's in there.

How do I stop duplication in <p> tag? I am trying to load data from my JSON file and display in the website with .html() function

Here is a screen shot of the problem
The original file has some hard coded data and I am suppose to replace this data with the one I have in my JSON file, I tried that with this code, made some progress but every time I click on the other e mail header the same data gets placed in the tag of my html file (index). I need to find a way to stop data from duplicating. Can somebody help me?! I am new in AJAX/JSON
$(document).ready(function() {
$.getJSON("email_list.js",
{format: "json"}).done(function(data){
console.log(data);
for (key in data) {
emailID = "#" + data[key].id;
$(".email-header")
.eq(key).attr("id", data[key].id);
$(emailID).find('td')
.eq(0).attr("id", "sender" + data[key].id)
.html(data[key].sender);
$(emailID).find('td')
.eq(1).attr("id", "subject" + data[key].subject)
.html(data[key].subject);
$(emailID).find('td')
.eq(2).attr("id", "datetime" + data[key].datetime)
.html(data[key].datetime);
}
});
// show/hide emails when click on headers
$("tr.email-header").click(function(){
id = "#body " + $(this).attr("id");
//creates the name for each file
fileID = $(this).attr("id") + ".js";
//console.log(id);
$.ajax({
url: fileID,
dataType: "JSON",
success: function(data) {
console.log(data);
//I need to replace the contents in the HTML file with
//my JASON file contents.
fElement = $("tr.email-body").find("p");
fElement.eq(0).html(data.recipient);
fElement.eq(1).html(data.body);
fElement.eq(2).html(data.recipient);
fElement.eq(3).html(data.body);
fElement.eq(4).html(data.recipient);
fElement.eq(5).html(data.body);
}}).fail(function() {
console.log(id + " - HAS AN ERROR!");
});
$(this).next().eq(0).toggle();
});
// hide email on click
$("tr.email-body").click(function(){
$(this).hide();
});
});
Here's an updated snippet that is pulling ajax data from your github repo. Just trace through to see how we are accessing the elements in the js file.
Some additional notes:
Try to use classes for repetitive elements like sender subject and datetime rather than ids. Then it is even easier to access them. I didn't change that.
You have it set to reload the email every time it's header is clicked. Might want to ensure to only load once.
You should clear out the existing html right away so the placeholder text isn't shown for a split second before the real content gets loaded.
$(document).ready(function() {
$.getJSON("https://raw.githubusercontent.com/checonunez74/AJAX-JSONproject/master/email_list.js", {
format: "JSON"
}).done(function(data) {
for (key in data) {
emailID = "#" + data[key].id;
$(".email-header")
.eq(key).attr("id", data[key].id);
f_el = $(emailID).find('td');
f_el.eq(0).attr("id", "sender")
.html(data[key].sender);
f_el.eq(1).attr("id", "subject")
.html(data[key].subject);
f_el.eq(2).attr("id", "datetime")
.html(data[key].datetime);
}
});
// show/hide emails when click on headers
$("tr.email-header").click(function() {
let id = $(this).attr("id"),
emailBody = $(this).next(".email-body"),
emailRecipient = emailBody.find('p').first(),
emailContent = emailBody.find('p').last();
//make the AJAX call here
$.ajax({
url: 'https://raw.githubusercontent.com/checonunez74/AJAX-JSONproject/master/' + id + '.js',
dataType: "JSON",
success: function(data) {
emailRecipient.text('To: ' + data.recipient);
emailContent.text(data.body);
}
}).fail(function() {
console.log(id + " - HAS AN ERROR!");
});
emailBody.toggle();
});
// hide email on click
$("tr.email-body").click(function() {
$(this).hide();
});
});
.email-body {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="email.js"></script>
<link rel="stylesheet" href="email.css">
</head>
<body>
<h1>Email Inbox</h1>
<table class="table table-hover" id="inbox">
<thead>
<tr class="active">
<th>Sender</th>
<th>Subject</th>
<th>Received</th>
</tr>
</thead>
<tbody>
<tr class="warning email-header">
<td>Bob</td>
<td>Re: Your brains</td>
<td>01/03/2014 9:56pm</td>
</tr>
<tr class="email-body">
<td colspan="3">
<p>To: Tom#tom.tom</p>
<p>Heya Tom, it's Bob, from the office down the hall...</p>
</td>
</tr>
<tr class="warning email-header">
<td>Your only friend</td>
<td>I've been shockingly nice</td>
<td>04/07/2011 12:34pm</td>
</tr>
<tr class="email-body">
<td colspan="3">
<p>To: want#you.gone</p>
<p>That's what I'm counting on.</p>
</td>
</tr>
<tr class="warning email-header">
<td>Mr. Fancy Pants</td>
<td>Chances are...</td>
<td>10/21/2005 4:16am</td>
</tr>
<tr class="email-body">
<td colspan="3">
<p>To: dancing#the.parade</p>
<p>You thought you had some fancy pants and now you know it's true.</p>
</td>
</tr>
</tbody>
</table>
</body>
</html>

Ajax not firing inside Modal Popup

Currently I have a button to view cart contents as such:
SHOW CART
data-target is for my modal
data-targets is for the body of my modal after the ajax endpoint returns a response
My Ajax code is as follows:
$('a[data-async="true"]').click(function(e){
e.preventDefault();
var self = $(this),
url = self.data('endpoint'),
target = self.data('targets'),
cache = self.data('cache');
$.ajax({
url: url,
cache : cache,
success: function(data){
if (target !== 'undefined'){
$('#'+target).html( data['response'] );
}
}
});
});
(courtesy of jQuery and data-attributes to handle all ajax calls?)
Now once the modal dialog popup has appeared I have some grid items inside a table such as:
<table id="itemstable" class="table table-striped table-bordered">
<thead class="fixed-header">
<tr>
<th>QTY</th>
<th>SKU</th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>' . $v->qty . '</td>
<td>' . $v->sku . '</td>
<td> X
</tr>
</tbody>
</table>
The problem I'm running into is I have another ajax endpoint call for each table line item but this time when I click it, the Ajax isn't firing at all. I looked at my browsers inspector but not even an error or attempt.
Am I missing something here because it's practically the same code I ran to get the popup and show the response in the body but now the only difference is I'm doing it inside the modal.
Your help is appreciated!
Change it to this and it should work.
$(document).on('click', 'a[data-async="true"]', function (e) {
e.preventDefault();
// your code here
});

Deleting users from the database using AJAX and Codeigniter

I'm trying to delete users from the database using AJAX and Code Igniter. When I click the delete link, the user gets deleted but the page gets redirected and success message is displayed. AJAX does not seem to work in my code.
Here's HTML:
<table class="table table-hover">
<thead>
<tr>
<th>#</th>
<th>First Name</th>
<th>Last Name</th>
<th>Email</th>
<th>Username</th>
<th>Password</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<?php foreach($users as $u){?>
<tr>
<td><?php echo $u['id']; ?></td>
<td><?php echo $u['firstname']; ?></td>
<td><?php echo $u['lastname']; ?></td>
<td><?php echo $u['email']; ?></td>
<td><?php echo $u['username']; ?></td>
<td><?php echo $u['password']; ?></td>
<td>
<a href="#" >Edit</a> |
<?php $id=$u['id'];?>
Delete
</td>
<?php }?>
</tr>
</tbody>
</table>
and here's AJAX:
$(document).ready(function(){
$(".delete").click(function(){
alert("Delete?");
var href = $(this).attr("href");
var btn = this;
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
})
});
and lastly the controller function to delete the user in Codeigniter
public function delete($id)//for deleting the user
{
$this->load->model('Users_m');
$delete=$this->Users_m->delete_user($id);
if($delete)
{
echo "Success";
}
else
{
echo "Error";
}
}
Where am I making the mistake?
Just to expand on the correct answers already given here.
Basically, your JS code should look like:
$(document).ready(function(){
$(".delete").click(function(event){
alert("Delete?");
var href = $(this).attr("href")
var btn = this;
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
event.preventDefault();
})
});
The event.preventDefault() part is important here. As it prevents the browser from taking the default action it takes if you click on an element.
In the case of a link, that would be redirecting you to the url that is defined in the href parameter. Which is what you see happening.
Your manually defined event is always triggered first, so the ajax request is indeed started, but right after that your event handler, the browser starts handling the default action, breaks off the ajax request, and navigates to the clicked link.
Make sure you are setting the correct object to the 'btn' var:
var btn = $(this);
See if this is the issue!
by the way you are missing a semicolon in:
var href = $(this).attr("href")
the default action of the event should not be triggered.
For this use event.preventDefault()
$(".delete").click(function(e){
e.preventDefault();
...
You are not preventing the default behavior of the anchor so it will redirect you and make the ajax request
$(document).ready(function(){
$(".delete").click(function(e){
alert("Delete?");
e.preventDefault();
var href = $(this).attr("href");
var btn = this;
$.ajax({
type: "GET",
url: href,
success: function(response) {
if (response == "Success")
{
$(btn).closest('tr').fadeOut("slow");
}
else
{
alert("Error");
}
}
});
})
});
I hope this can help :)
First you change the href attribute another attribute like name or value because first time it loads and another time it stores the value in href and after that write this for refreshing page
window.reload('true');
this will surely help you

Categories