I'm trying to delete a table row, my button works and my product deletes from the database, however it doesn't delete on the page until a refresh and I always get "It Failed" even tho it worked... What am I doing so wrong? seems like the "success" isn't being called.
$(".deleteProduct").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "/eventlineitem/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
Here is my html
<tr class="item{{$item->id}}">
<td class="align-center" scope="row">{{$item->product->id}}</td>
<td class="align-center">{{$item->quantity}}</td>
<td>{{$item->product->name}}</td>
<td class="align-center">{{$item->warehouse_id}}</td>
<td class="align-center">{{$item->product->location}}</td>
<td><div class="switch">
<label><input type="checkbox"><span class="lever switch-col-green"></span></label>
</div></td>
<td><i class="material-icons deleteProduct" data-id="{{ $item->id }}" data-token="{{ csrf_token() }}">delete</i></td>
</tr>
Change your success function like this
success: function ()
{
$(".item"+id).remove();
console.log("it Work");
}
I don't know how you expected the html to know you deleted the row?
I think you should create a variable before the Ajax call
var target = $(this).parents("tr");
And then in the ajax.success call
target.remove()
success: function() {
$(this).parent().parent().remove();
console.log("it Work");
}
By the way, if console.log is being fired here then you know success worked.
Can you try with the below code:
$(".deleteProduct").click(function(){
var _selector = $(this);
var id = _selector.data("id");
var token = _selector.data("token");
$.ajax({
url: "/eventlineitem/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token
},
success: function (){
console.log("it Work");
_selector.parents('tr.item' + id).remove();
}
});
});
Let me know if its work for you.
Related
I'm trying to delete items by ajax, so far i can get each item id but somehow when i click on delete button it just getting first item id.
code
controller
public function delqtydisc(Request $request,$id)
{
$dele = QtyDiscount::find($id)->delete();
return response()->json($dele);
}
route
Route::post('/delqtydisc/{id}', 'QtyDiscountController#delqtydisc')->name('delqtydisc');
script
<script>
$(document).ready(function() {
$("#addnewqtydiscmsgsave").click(function(e){
e.preventDefault();
//this adds new items to database (no issue here)
$.ajax({
type: "post",
url: "{{ url('admin/addnewqtydisc') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'amount': $('#amount').val(),
'min': $('.min').val(),
'max': $('.max').val(),
},
success: function (data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>');
var $tr = $('<tr/>');
$tr.append($('<td/>').html(data.min));
$tr.append($('<td/>').html(data.max));
$tr.append($('<td/>').html(data.amount));
// This adds delete button to my table
$tr.append($('<td/>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));
$('.list-order tr:last').before($tr);
$("#min").val('');
$("#max").val('');
$("#amount").val('');
// From this part delete function adds
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $('.qtyitemid').data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
}
});
});
// end of delete fuction
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
PS: I commented each part of my JavaScript code that I thought should
bring your attention
// This adds delete button to my table and // From this part delete function adds
Error
when I hit delete button I get 3 results (if i have 3 inputs) in my network, first one return true the other 2 return
"message": "Call to a member function delete() on null",
Any idea?
Update
with code below my problem is solved some how, the only issue is remained is that i still get my row id's multiple. e.g. when i delete id=1 network show it one time but when after that i delete id=2 network shows two times id=2
<script>
$(document).ready(function() {
$("#addnewqtydiscmsgsave").click(function(e){
e.preventDefault();
$.ajax({
type: "post",
url: "{{ url('admin/addnewqtydisc') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': $('#product_id').val(),
'amount': $('#amount').val(),
'min': $('.min').val(),
'max': $('.max').val(),
},
success: function (data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-success">Discount created successfully.</span>').fadeIn().delay(4000).fadeOut();
var $tr = $("<tr id='" + data.id + "'>");
$tr.append($('<td>').html(data.min));
$tr.append($('<td>').html(data.max));
$tr.append($('<td>').html(data.amount));
$tr.append($('<td>').html("<button class='qtyitemid btn btn-xs btn-danger' data-id='" + data.id + "' type='button'>Delete this</button>"));
$('.list-order tr:last').before($tr);
$("#min").val('');
$("#max").val('');
$("#amount").val('');
//delete item
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $(this).data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>').fadeIn().delay(3000).fadeOut();
$('table tr#'+QtyitemID+'').remove();
}
});
});
//
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
PS: basically most of my problem is solved i'm just looking for answer
to avoid this multiple id in network.
The error occurred in your qtyitemid on click event. Specifically this line: var QtyitemID = $('.qtyitemid').data('id');
This JS code will always return the data of the first qtyitemid class. You must use the keyword this to determine what element is clicked. This code hopefully fix the problem:
$('.qtyitemid').on('click', function() {
e.preventDefault();
var QtyitemID = $(this).data('id');
console.log(QtyitemID);
$.ajax({
type: 'post',
url: '{{ url('admin/delqtydisc') }}/'+encodeURI(QtyitemID),
data: {
'_token': $('input[name=_token]').val(),
'id': QtyitemID
},
success: function(data) {
$('#addnewqtydiscmsg').empty();
$('#addnewqtydiscmsg').append('<span class="text-danger">Discount deleted successfully.</span>');
}
});
});
First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.
I have a table that is being populated dynamically, and a reload script that refreshes it ever 60 seconds.
<script type="text/javascript" language="javascript">
window.setInterval(function () {
$('#divGrid').load('Home/Index #divGrid>table');
}, 60000);
</script>
I also have a Javascript that calls a partial view on table row click:
<script type="text/javascript" language="javascript">
function showOpenTrData() {
$('#OpenTickets tbody tr').click(function () {
$.ajax({
url: 'Home/TicketDetails/' + this.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
function showClosedTrData() {
$('#ClosedTickets tbody tr').click(function () {
$.ajax({
url: 'Home/TicketDetailsClosed/' + this.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
</script>
I had it at first without an onclick function but then upon reload it would stop working so I changed it to onclick function, however first time after reload I have to double click the row and after that for the period of 60 seconds till next reload its all fine, after it reloads I have to double click the first time again. Its driving me up the wall.
Please help!
HTML
<table class="table" id="OpenTickets" style="overflow-y:scroll;width:70%;float:left; margin-top:-25px; display:block;">
<tbody>
#foreach (var item in Model.ticketModel.OrderByDescending(x => x.ticket.ID).Where(x => x.ticket.StatusID == 1))
{
<tr onclick="showOpenTrData()">
<td class="columnID" id="ticketID">
#Html.DisplayFor(modelItem => item.ticket.ID)
</td>
<td class="columnSummary">
#Html.DisplayFor(modelItem => item.ticket.Summary)
</td>
<td class="columnAssignee" id="ajaxTest">
#if (item.ticket.Assigned_to_UserID == null || item.ticket.Assigned_to_UserID == 0)
{
#Html.Label("Unasigned")
}
else
{
#Html.DisplayFor(modelItem => item.assignedUser.First_name)
<text> </text>
#Html.DisplayFor(modelItem => item.assignedUser.Last_name)
}
</td>
<td style="font-size:11px; width:10%" class="columnUpdated">
#if ((item.ticket.updated_at == null))
{
#Html.DisplayFor(modelItem => item.ticket.Created_at)
}
else
{
#Html.DisplayFor(modelItem => item.ticket.updated_at)
}
</td>
</tr>
}
</tbody>
</table>
i got it - if anyone else struggles here is the breakdown.
.load method renders any javascript useless as its not part of the same instance any more, hovever on click is a solution but how do you get the object reference?
you pass this in the on click function.
onclick="showTableData(this)"
then you can use the passed event to acquire data from it
cheers
The basic problem here is that you are mixing onclick=... with jQuery bindings .click(...). It is possible to use both on the same page but it becomes confusing and is harder to maintain: Pick one.
The easiest thing (based on your current code) is to kill the jQuery bindings. Try this:
<script type="text/javascript" language="javascript">
function showOpenTrData(ptr) {
$.ajax({
url: 'Home/TicketDetails/' + ptr.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
}
function showClosedTrData(ptr) {
$.ajax({
url: 'Home/TicketDetailsClosed/' + ptr.cells.ticketID.innerText,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
}
</script>
Each time the showOpenTrData or showClosedTrData was running, it was adding another jquery bind. If you open your console and check the networks tab you'll see that the ajax functions are then being run multiple times with one click (after the second click).
If you want to just use jQuery, then use this:
<script type="text/javascript" language="javascript">
$(document).ready(function(){
$('#OpenTickets tbody tr').click(function () {
var ticketId = $(this).find('td').text();
$.ajax({
url: 'Home/TicketDetails/' + ticketId,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
$('#ClosedTickets tbody tr').click(function () {
var ticketId = $(this).find('td').text();
$.ajax({
url: 'Home/TicketDetailsClosed/' + ticketId,
data: {},
type: 'GET',
datatype: 'json',
success: function (response) {
$("#TicketDetails").html(response)
},
error: {}
});
});
}
</script>
Also, delete the onclick=... section in the html or you'll get javascript errors because it is looking for a function that doesn't exist.
EDIT:
I added in the ticketId you needed.
I wonder why its not working, here is the code
View
<input type="button" value="Delete" onclick="deletefunction(#item.PhotoId)"/>
Controller
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return null;
}
JQUERY/AJAX
<script type="text/javascript">
$(document).ready(function () {
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
};
});
</script>
im new to jquery and ajax, im trying to delete the photo without refreshing the page, am i in the correct path?
I would suggest to attach click event to your button instead of writing javascript in markup. Consider the below markup:
<input type="button" class="delete" value="Delete" data-picid="#item.photoId"/>
Now attach a click event to .delete as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
//access message from server as result.message and display proper message to user
alert: ("Success")
},
error: {
alert: ("Error")
}
});
});
Your Controller then:
[HttpPost]
public ActionResult Delete(int photoid)
{
var imgDelete = db.Photos.Where(x => x.PhotoId == photoid).FirstOrDefault();
if (imgDelete == null)
{
return Json(new{ message=false},JsonRequestBehavior.AllowGet);//return false in message variable
}
db.Photos.Remove(imgDelete);
db.SaveChanges();
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ImagePath);
System.IO.File.Delete(AppDomain.CurrentDomain.BaseDirectory + imgDelete.ThumbPath);
return Json(new{ message=false},JsonRequestBehavior.AllowGet); //return true if everything is fine
}
Once photo is deleted based on the success or failure your can do it as below in success of ajax, but before that store a reference to yourbutton` as below:
$('.delete').on('click',function(){
var photoId=$(this).attr('data-picid');//gets your photoid
var $this=$(this);
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
data: JSON.stringify({ photoid: photoId }),
contentType: "application/json; charset=utf-8",
dataType: "json", //return type you are expecting from server
success: function (result) {
if(result.message)
{
$this.closest('yourrootparentselector').remove();
//here yourrootparentselector will be the element which holds all
//your photo and delete button too
}
},
error: {
alert: ("Error")
}
});
});
UPDATE
Based on your given mark up you I suggest to add one more root parent for your each image and delete button as below:
<div style="margin-top: 17px;">
<div id="links">
#foreach (var item in Model.Content)
{
<div class="rootparent"> <!--rootparent here, you can give any classname-->
<a href="#item.ImagePath" title="#item.Description" data-gallery>
<img src="#item.ThumbPath" alt="#item.Description" class="img-rounded" style="margin-bottom:7px;" />
</a>
<input type="button" class="delete" value="Delete" data-picid="#item.PhotoId" />
</div>
}
</div>
</div>
Now you can write this in success
$this.closest('.rootparent').remove()
Try this.
<script type="text/javascript">
$(document).ready(function () {
});
function deletefunction(photoid) {
$.ajax({
url: '#Url.Action("Delete")',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: { photoid: photoid },
success: function (result) {
alert: ("Success")
},
error: {
alert: ("Error")
}
});
}
</script>
I have this code and, if everything is okay, the result should be a thank you page.
Here is the code:
<a class="large red button round" onclick="$.ajax({ type: 'POST', data:$('#newsletter').serialize(), url: 'http://www.stress-free-life.co.il/lists/?p=subscribe& amp;id=1', success: function (msg) { openWin(); $('#Name').val(''); $('#email').val(''); }, failure: function (msg) { alert('Sorry, we were unable to process your subscription.'); } }); return false;" href="javascript; return false;">לחץ כאן</a>
I have tried several options but can't get the thank you page to display.
Um... let's clean this up, onclick handlers are really hard to read and are generally considered bad practice
Your HTML:
<a class="large red button round my-button" href='#'>לחץ כאן</a>
And in a separate JS file you should have:
$(function(){
$('.my-button').on('click', function(e){
e.preventDefault();
$.ajax({
type: 'POST',
data: $('#newsletter').serialize(),
url: 'http://www.stress-free-life.co.il/lists/?p=subscribe&id=1',
success: function(msg){
window.location = "/my-thank-you-page.html";
//openWin(); // No idea what this function is...
//$('#Name').val('');
//$('#email').val('');
},
failure: function(msg){
alert('Sorry, we were unable to process your subscription.');
}
});
});
});
Perhaps something like this...
<a id="ajaxpost" class="large red button round" href="javascript:void(0)">לחץ כאן<a>
<script>
$("#ajaxpost").click(function () {
$.ajax({
type: 'POST',
data: $('#newsletter').serialize(),
url: 'http://www.stress-free-life.co.il/lists/?p=subscribe&id=1',
success: function (msg) {
openWin();
$('#Name').val('');
$('#email').val('');
window.location = "url of thank-you page";
},
failure: function (msg) {
alert('Sorry, we were unable to process your subscription.');
}
});
});
</script>