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>');
}
});
});
Related
good afternoon, have all of you, I have this problem. I am using selectr mobius1 and when I click to edit data, the "Type of Service" field does not show me the value that it should show me.
my select is initialized like this
$selecttSE = new Selectr("#tipo_SAPIE",{});
I use this onchange so that when a product is chosen the list of services changes
$("#tipo_productoE").on('change', function() {
var tipoprod = $("#tipo_productoE option:selected").val();
var select_servapi = $("#tipo_SAPIE");
$.ajax({
url: '<?= base_url('productos/select_servicios') ?>',
type: 'get',
data: {
tipoprod: tipoprod
},
beforeSend: function(){
$selecttSE.removeAll();
},
success: function(response) {
if (response.length >2 ) {
select_servapi.attr('disabled', false);
$.each(JSON.parse(response), function(i, item) {
$selecttSE.add([{
value: item.servicioapiid,
text: item.alias+' '+item.moneda+''+item.costo}])
});
let select = $("#tipo_SAPIE").parents().children('small')[0];
$(select).empty();
$(select).html('Requerido');
$(select).addClass('badge badge-soft-danger');
} else {
select_servapi.attr('disabled', true);
}
},
});
});
And my function to get the data is this
function getProducto(idproducto) {
var idproducto = idproducto;
$.ajax({
url: '<?= base_url('productos/getProducto') ?>',
type: 'GET',
data: {
idproducto: idproducto
},
success: function(response) {
console.log(response)
$selecttSE.removeAll();
$.each(JSON.parse(response), function(i, item) {
document.getElementById("tipo_productoE").value = item.tipoproductoid;
$("#tipo_productoE").trigger('change');
$selecttSE.setValue(item.servicioapiid);
});
},
error: function(errors) {
},
});
}
Thank you for taking the time to see my post have a great afternoon and much success.
I have a form with dynamic rows, after fetching record I want to update status of selected rows by checkbox.
I'm successfully getting each row checkbox values and dynamic row id in console but when trying to update values, it's updating first row only.
HTML:
<button type="button" class="btn btn-info" id="update_status_btn">Update Status</button>
Fetched record:
success: function(data){
var trHTMLr = '';
$.each(data,function(i,row){
trHTMLr += '<tr>' +
'<td><input type="text" name="first_name" class="form-control text-center" value="' + row.first_name + '" /></td>' +
'<td><input type="checkbox" name="status" class="form-control text-center updatestatusclass" data-id="' + row.id + '" value="' + 'YES' + '"/></td>' +
'</tr>';
});
$('#mytable').append(trHTML);
}
Update status:
$("#update_status_btn").click(function(e) {
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var eachrow_value=[];
$('.updatestatusclass').each(function(){
if($(this).is(":checked"))
{
eachrow_value.push($(this).val());
}
});
eachrow_value=eachrow_value.toString();
var row_id = $('.updatestatusclass').attr('data-id');
$.ajax({
url: "{{ url('/updatestatus') }}",
method: 'POST',
data: {id: row_id, status: eachrow_value},
dataType: 'json',
success: function (response) {
alert('Updated Successfully!');
},
error: function (response) {
alert("Not Updated, Try again.");
}
});
});
Controller:
if ($request->ajax()) {
$stat = Services::where('id', $request->get('id'))
->update(array(
'status' => $request->get('status')
));
return Response::json($stat);
}
I want to update status of selected row by checkbox with it's respective row ID.
What you are looking for is to update multiple checkboxes in one go. So, you need to store both selected & unselected checkboxes.
Your jQuery
let checkedIds = [];
let unCheckedIds = [];
$('.updatestatusclass').each(function () {
if ($(this).is(":checked")) {
checkedIds.push($(this).attr('data-id'));
} else {
unCheckedIds.push($(this).attr('data-id'));
}
});
$.ajax({
url: "{{ url('/updatestatus') }}",
method: 'POST',
data: {
checkedIds: checkedIds,
checkedIdStatus: 'active', //do your thing
unCheckedIds: unCheckedIds,
unCheckedIdStatus: 'inactive', //do your thing
},
dataType: 'json',
success: function (response) {
alert('Updated Successfully!');
},
error: function (response) {
alert("Not Updated, Try again.");
}
});
In your Controller
if ($request->ajax()) {
Services::whereIn('id', $request->get('checkedIds'))
->update(array(
'status' => $request->get('checkedIdStatus')
));
Services::whereIn('id', $request->get('unCheckedIds'))
->update(array(
'status' => $request->get('unCheckedIdStatus')
));
}
Hope this helps. Cheers!
I've read similar questions and tried different methods, but nothing seems to work. I have a Liking system. A heart image which switches between liked (filled heart icon) and unliked (Plain bordered heart icon).
The problem is, when I click on the like/heart button, all the other records' heart icon turns to liked state. The same goes with the like count. When I like a post, all the post's like count becomes the same.
Also, I'm running an AJAX request to get the likes count. When I try to output the likes and increment/decrement if they like/unlike, the output is weird. It goes to -1 or 01 etc.
This is my main.blade.php :
<span class="activityLikes">
<input type="hidden" class="activityIdHidden" value="{{ $activity->activity_id }}">
<a class="likeBtn">
#if(Auth::user()->hasLikedActivity($activity))
<img class="likeImg likeTrue" src="IMG/icons/likeTrue.png" alt="likes">
#else
<img class="likeImg likeFalse" src="IMG/icons/like.png" alt="likes">
#endif
</a><span class="likesCount">{{ $activity->likes->count() }}</span>
</span>
This is my main.js file :
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
$('.likeImg').attr('src', 'IMG/icons/like.png');
$('.likesCount').text(likeCount - 1);
} else if(data == "liked"){
$('.likeImg').attr('src', 'IMG/icons/likeTrue.png');
$('.likesCount').text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});
It is because you update every image that has the .likeImg class on the success event.
Can you try the following code ?
$('.likeBtn').on('click', function(e){
e.preventDefault();
var likeCount = 0;
// element to update is `this` (the element that had been clicked)
var elementToUpdate = $(this).children('img');
$.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
success: function(data){
likeCount = data;
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
success: function(data){
if(data == "deleted"){
elementToUpdate.attr('src', 'IMG/icons/like.png');
elementToUpdate.text(likeCount - 1);
} else if(data == "liked"){
elementToUpdate.attr('src', 'IMG/icons/likeTrue.png');
elementToUpdate.text(likeCount + 1);
}
},
error: function(e){
console.log(JSON.stringify("Exception: " + e));
}
});
});
You should chain your Ajax calls, and get the count after updating the "like" status, like this:
function errHandler(e) {
console.log(JSON.stringify("Exception: " + e));
}
$('.likeBtn').on('click', function(e){
var activityId = +$(this).siblings(".activityIdHidden").val(),
$img = $("img", this),
$likes = $(this).siblings(".likesCount");
e.preventDefault();
$.ajax({
type: 'POST',
url: './mainView/postlike',
data: {activityId : activityId, user_id: user_id},
error: errHandler
}).then(function(data){
$img.attr('src', data === "deleted" ? 'IMG/icons/like.png' : 'IMG/icons/likeTrue.png');
return $.ajax({
type: 'GET',
url: './mainView/getLikeCount',
data: {activityId: activityId},
error: errHandler
});
}).then(function(data){
$likes.text(data);
});
});
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 want to do filtration and pagination in one script. I have done filtration and pagination separately. But when I combine this two code snippet pagination is not working. Here I give my code which I have done.
function getusedcarFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
function updateusedcar(opts){
$.ajax({
type: "POST",
url: "filter.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(data){
$('#usedcar1').html(makeTable(data));
displayRecords();
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getusedcarFilterOptions();
updateusedcar(opts);
});
updateusedcar();
// fetching records
function displayRecords(numRecords, pageNum) {
$.ajax({
type: "GET",
url: "getrecords.php",
data: "show=" + numRecords + "&pagenum=" + pageNum,
cache: false,
beforeSend: function() {
$('.loader').html('<img src="loader.gif" alt="" width="24" height="24" style="padding-left: 400px; margin-top:10px;" >');
},
success: function(html) {
$("#usedcar1").html(makeTable(data));
$('.loader').html('');
}
});
}
// used when user change row limit
function changeDisplayRowCount(numRecords) {
displayRecords(numRecords, 1);
}
$(document).ready(function() {
displayRecords(10, 1);
});
</script>
thanks in advance.
You should combine the codes on server side, otherwise the filtered record are not paginated and vice-versa. Otherwise you need to do the pagination on client side but I suppose it would eliminate the main reason of the pagination.