Laravel: Jquery on click function issue - php

I am trying to alert something but on click function is running only once on the first button. but I have buttons on many rows.
I am fetching Data through Laravel from Database in a table. Only one button runs a function, then nothing happens with other buttons.
Jquery:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
var val = $("#thisr").attr('value');
alert(val);
});
});
View:
<table id="recover-table" class="table" >
<thead>
<tr class="bg-info">
<th>Teacher Name</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($trashs as $trash)
<tr id="thisr" value="{{$trash->id}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap "><button type="submit" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
</tr>
#endforeach </tbody></table>
Right now even alert is not working, but I want to achieve Refresh table after a record is deleted from Table.
Update: Now Alert is working fine, but when I delete a record by pressing a button, only one row is deleting. the function runs once.
Complete Js:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
let teacher_id=$(this).attr('value');
console.log('Restore button clicked!')
e.preventDefault();
$.ajax(
{
url: "/teachers/recover/" + $('#restore-data').attr("value"),
type: 'GET', // Just delete Latter Capital Is Working Fine
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: teacher_id,
success: function (data) {
console.log(data.msg);
console.log(teacher_id);
if(data.msg){
$('#thisr').remove();
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
},
error: function (xhr) {
console.log("Error Restoring Record");
//console.log(xhr.responseText);
},
});
});
});

You can try to use class 'restore-data'
$(document).ready(function(e) {
$(document).on('click', '.restore-data', function(e) {
var val = $('#thisr').val();
alert(val);
});
});
As id should be unique for each element.
You can try something like
#foreach($trashs as $trash)
<tr>
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" data-trash-id="{{$trash->id}}" class="restore-data">Delete</button>
</td>
</tr>
#endforeach
and JS as
$(document).on('click', '.restore-data', function(e) {
var trash_id = $(this).attr('data-trash-id');
alert(trash_id);
});

Change this line.
var val = $("#thisr").attr('value');
to (since you have value attribute in button):
var val = $(this).attr('value');
or (since you have value attribute td):
var val = $(this).parent('tr#thisr').attr('value')
To remove a row.
$('#restore-data').on('click', function(e) {
var _this = $(this);
...
if(data.msg){
_this.parent('tr#thisr').remove();
....
Also change button type to button.
<button type="button" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>

You gave same id to all button and id must be unique of particular button so you can define unique id with key of array and pass it to Function
#foreach($trashs as $key=>$trash)
<tr id="thisr{{$key}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" class="" name="id" value="{{$trash->id}}" id="restore-data{{$key}}" onclick="restoreData({{$key}})">Delete</button>
</td>
</tr>
#endforeach
function restoreData(key){
var val = $("#restore-data"+key).attr('value');
alert(val);
// you can use either
$("#restore-data"+key).closest('tr').remove();
// OR
$('#thisr'+key).remove();
}

Related

How to display data in its row table?

let's say I have 5 rows of data, is there a way where I can display the data on its row? how?
in my code, when I hit the button on row 5 the result displays in data column.
<table>
<th>action</th><th>data</th>
<tr>
<td>
<button class="getdata" type="button" data-id="1">
</td>
<td>
<i class="data"></i>
</td>
</tr>
<tr>
<td>
<button class="getdata" type="button" data-id="2">
</td>
<td>
<i class="data"></i>
</td>
</tr>
<tr>
<td>
<button class="getdata" type="button" data-id="3">
</td>
<td>
<i class="data"></i>
</td>
</tr>....
</table>
$('.getdata').click(function(){
var id = $(this).attr('data-id');
$.ajax({
url: 'log.php',
method: 'GET',
data:{id:id},
success:function(){
$('.data').html(id)
}
})
})
In your AJAX success / done handler, traverse up from the current button to a sensible parent (<tr>) then down to the .data element
$('.getdata[data-id]').on("click", function() {
const btn = $(this)
$.get("log.php", { id: btn.data("id") }).done(data => {
btn.closest("tr").find(".data").html(id) // or data ¯\_(ツ)_/¯
})
})
See .closest()
Did you know, you might not need jQuery
// using event delegation at the <table> level
document.querySelector("table").addEventListener("click", async e => {
const btn = e.target.closest("button.getdata[data-id]")
if (btn) { // the click came from a button
const id = btn.dataset.id
const params = new URLSearchParams({ id })
const res = await fetch(`log.php?${params}`)
const data = await res.text()
if (res.ok) {
btn.closest("tr").querySelector(".data").innerHTML = id // or data
} else {
console.error(res.status, data})
}
}
})

How to send multiple same name input fields value via ajax post method

I have two same name multiple input fields. I want to send all fields value from another page using jquery ajax post method but i am not getting all rows input fields value. Please review my code.
Javascript code
<script type="text/javascript">
function getValue()
{
$.post("paidamt.php",
{
paidamt : $('#paidamt').val(),
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Html Code
<div>
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) {
?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" id="paidamt"></td>
<td><input type="checkbox" name="uid[]" id="uid"
value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<input type="button" name="submit" id="submit"
onclick="getValue(1)" value="Save Amt.">
</form>
</div>
<div id="divShow">
</div>
Try this one
var paidamt = $("input[name=paidamt]").map(function(){
return $(this).val();
}).get().join(",");
var uid = $("input[name=uid]").map(function(){
return $(this).val();
}).get().join(",");
$.ajax(
{
type: "POST",
url: 'paidamt.php',
data:
{
paidamt:paidamt,
uid:uid
}
});
Firstly you have given the input elements the same id which is repeated in the loop. This will end up in your HTML being invalid, you should change the id to class:
<form method="post">
<table border="1">
<tr>
<th>Product</th>
<th>Price</th>
<th>Paid Amount</th>
<th>Check</th>
</tr>
<?php
$sql = mysql_query("SELECT * FROM `tbldemo`");
while ($result = mysql_fetch_array($sql)) { ?>
<tr>
<td><?php echo $result['pname']; ?> </td>
<td><?php echo $result['price']; ?></td>
<td><input type="text" name="paidamt[]" class="paidamt"></td>
<td><input type="checkbox" name="uid[]" class="uid" value="<?php echo $result['id']; ?>"></td>
</tr>
<?php }
?>
</table><br>
<button type="submit" name="submit" id="submit">Save Amt.</button>
</form>
To actually send the input values in the AJAX request you can simply serialize() the containing form when the form is submit:
$(function() {
$('form').submit(function(e) {
$.ajax({
url: "paidamt.php",
type: 'POST',
data: $(this).serialize(),
success: function(data) {
$("#divShow").html(data);
});
});
});
});
I suggest to add class instead of id, since identically class can be repeated but id should not.
<script type="text/javascript">
function getValue()
{
var paidamtval = [];
$('#paidamt').each(function(){
paidamtval.push($(this).val());
});
$.post("paidamt.php",
{
paidamt : paidamtval,
uid : $('#uid').val()
},
function( data){
/*alert(data);*/
$("#divShow").html(data);
});
}
</script>
Since you will have many of these, id - needs to be unique, which in your case isn't, so remove "id="paidamt"
<td><input type="text" name="paidamt[]" id="paidamt"></td>
That's your first mistake. And secondly don't use $.post, to submit this form. Either remove AJAX submit, or bind form using something like jQuery Form plugin.
You try this code
$('document').ready(function(){
$('#submit').click(function(){
jQuery.ajax({
type: "POST",
url: "paidamt.php",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(html){
try{
$("#divShow").html(data);
}catch (e){
alert(JSON.stringify(e));
}
},
error : function(e){alert("error "+JSON.stringify(e)); }
});
});
});
in you paidamt.php file
$paidamt=$_POST['paidamt'];// its can array values
print_r($paidamt);// result display

jQueryUI.Sortable update without using Ajax as normal form submit to PHP

I would like to sort a table with data row from MySQL then change the order and submit it.
I used jQueryUI.sortable to make those tr tag (row) draggable.
But when I submitting the form, some of them didn't changed order.
Why? I tried to figure it out, I var_dump the data I submitted and I found a problem:
The tr tag (row) I moved from the original order, won't pass to PHP so var_dump will not show the row ID.
To make it easier to understand, I post my code here:
HTML Code
<table>
<thead>
<tr>
<th>Subject</th>
<th>Content</th>
</tr>
</thead>
<tbody id="sortable">
<tr>
<td>
Hello World
<input name="displayorder[]" type="hidden" value="1" />
</td>
<td>I come from Mars!</td>
</tr>
<tr>
<td>
Hello Mars
<input name="displayorder[]" type="hidden" value="2" />
</td>
<td>I come from Jupiter!</td>
</tr>
<tr>
<td>
Hello StackOverflow
<input name="displayorder[]" type="hidden" value="3" />
</td>
<td>I come from North Korea ...</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="2"><input type="submit" value="Submit!" />
</tr>
</tbody>
</table>
I omitted the form content cause it is not important
JavaScript (Sortable Library loaded)
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.6,
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
$displayorder = $_POST["displayorder"];
if($displayorder != "") {
$order = 1;
foreach($displayorder as $value) {
mysql_query("UPDATE message SET displayorder=$order WHERE announcementid=$value");
$order++;
}
}
I will prefer not using Ajax to do this because I have dozens of similar page to do the same task.
Thanks in advance.
Well I decided to code it every page.
The code now:
JavaScript
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.4,
update: function(event, ui){
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: '/update.php?action=displayorder'
});
},
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
foreach($_POST["displayorder"] as $i => $value) {
mysql_query("UPDATE message SET displayorder=$i WHERE announcementid=$value");
$i++;
}

How update model after inserting entry to database? And refresh a view

I shyly trying to make friends Angular and backend database.
Simple operations. Get database to angular model. Save entry in database, and delete entry.
I'm stacked on DELETE action. When i delete entry that loaded from database it's ok. But when i delete newly created row by push method, i got error.
This occurs because in the model absent id. After inserting entry to database, i trying repeatedly refresh Angular model from database.($http.get) But in this case, a view didn't refresh (only blinks). I saw new entry only refresh page F5.
Help!
Books
<div ng-app="App" ng-controller="MyCtrl">
<table class="">
<th>
<tr style="font-size: 20px">
<td>ID</td>
<td>Name</td>
<td>Price</td>
<td>Action</td>
</tr>
</th>
<tr ng-repeat="book in books">
<td style="width: 200px">{{book.id}}</td>
<td style="width: 200px">{{book.name}}</td>
<td style="width: 50px">{{book.price |currency}}</td>
<td>
<button ng-click="removeItem($index)">Удалить</button>
</td>
</tr>
<tr>
<td></td>
<td><input type="text" ng-model="name"/></td>
<td><input type="number" ng-model="price"/></td>
<td>
<button ng-click="addBook()">Добавить книгу</button>
</td>
</tr>
</table>
</div>
<script>
var App = angular.module('App', []);
App.controller('MyCtrl', function ($scope, $http) {
$http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
$scope.books = data;
});
$scope.removeItem = function (index) {
var id = $scope.books[index].id;
$scope.books.splice(index, 1);
$http.post('http://ang:8888/index.php?r=site/del2', {id: id});
}
$scope.addBook = function () {
var newBook = ({name: $scope.name, price: $scope.price});
$scope.books.push(newBook);
$http.post("http://ang:8888/index.php?r=site/post2", {name: $scope.name, price: $scope.price})
.success(function (data, status, headers, config) {
console.log("inserted Successfully");
});
$http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
$scope.books = data;
});
}
})
The problem is due to async nature of all remote calls. You call the post and get methods in sequence without realizing that both are sync in nature. So your post is immediately followed by get.
Change the code for post to
$http.post("http://ang:8888/index.php?r=site/post2", {
name: $scope.name,
price: $scope.price
}).success(function (data, status, headers, config) {
console.log("inserted Successfully");
$http.get('http://ang:8888/index.php?r=site/api2').success(function (data) {
$scope.books = data;
});
});
In the above code you only do get when post is done.

Error when using function deleteRow after load ajax jquery?

<a class="checkModelButton" href="check.php">Check</a>
<div id="model_list"></div>
include jquery and function deleteRow():
jQuery('.checkModelButton').click(function(event){
event.preventDefault();
var url = jQuery(this).attr('href');
jQuery.ajax({
type: 'get',
cache: false,
url: url,
success: function(html){
jQuery('#model_list').html(html);
}
});
});
function deleteRow(id) {
try {
var table = document.getElementById('model_list');
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
jQuery("input[type=checkbox]:checked").each(function() {
jQuery(this).parents("tr").remove();
});
} catch(e) {
alert(e);
}
}
in check.php return html is:
<input type="button" value="Delete Row" onclick="deleteRow('model_list')" />
<table id="model_list">
<thead>
<tr>
<th>#</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="model_id[]" class="item"></td>
<td>Nokia N71</td>
</tr>
</tbody>
</table>
After loadding ajax, I checked on form input and click button Delete Row, but error can't delete this row And error is alert(Table model_list is empty), how to fix it ?
jQuery has really simplified the selection process for us and also provided a lot of fail-safes that JavaScript doesn't offer without a try/catch block.
Since you're already using jQuery, you can really simplify your deleteRow() function by doing the following:
function deleteRow(id) { // the id variable is unnecessary and can be removed
// Grab all the rows in the table (the > sign targets the elements directly inside the current one (not cascading)
var rows = jQuery("#model_list > tbody > tr");
// Iterate through the rows
jQuery(rows).each(function(key, value) {
// Look inside each row for a checked checkbox
if (jQuery(this).find("input:checkbox[checked='checked']").length > 0) {
// If one is found, then remove the whole row (jQuery(this) refers to the current row
jQuery(this).remove();
}
});
}
To make the example above work, I created a temporary table in the same file. Since you are dynamically loading the table rows with data, this should function similar to the static sample below:
<input type="button" value="Delete Row" onclick="deleteRow('model_list')" />
<table id="model_list">
<thead>
<tr>
<th>#</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="model_id[]" class="item"></td>
<td>Nokia N71</td>
</tr>
<tr>
<td><input type="checkbox" value="2" name="model_id[]" class="item"></td>
<td>Nokia N72</td>
</tr>
<tr>
<td><input type="checkbox" value="3" name="model_id[]" class="item"></td>
<td>Nokia N73</td>
</tr>
</tbody>
</table>
Please let me know if this is helpful or if you have any other questions. :)

Categories