Why JQuery code does not work when i click on button? - javascript

What is the problem with my JQuery code when I click on the button it does not work, I searched a lot and tried many ways but my problem not solved. I used this code in other files, on there it works correctly but it not work in this file.
this my table:
<table class="table table-bordered">
<tbody>
<?php
$insideOrders = \App\OutsideModel::where('total_id', '=', $order->order_id)->get();
?>
#foreach($insideOrders as $index => $inside)
<tr>
<td>{{ $index + 1 }}</td>
<td>{{ $inside->menu->name }}</td>
<td>{{ $inside->menu->category->name }}</td>
<td>{{ $inside->order_amount }}</td>
<td>
#if($order->status=='1')
<button id="send_order" class="btn btn-primary btn-xs"
order_id="{{$order->order_id}}">ارسال<i id="send_icon"></i>
</button>
#else
<button class="btn btn-success btn-xs" disabled>ارسال شده</button>
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
This is my js:-.
$('table tbody').on('click', 'button', function () {
var order_id = $(this).attr("order_id");
$.ajax({
url: '{{route('sendOrders')}}',
type: 'GET',
dataType: 'json',
data: {
'id': order_id
},
success: function (response) {
if (response) {
alert('ارسال شد!');
window.location.reload();
}
else {
alert('ارسال نشد!')
}
}, error: function (err) {
}
})
});

I solved my problem, I put my table inside a dive like below, I don't know what happens when I put it inside a dive. but it works now.
<div id="apended_tb">
<table class="table table-bordered">
<tbody>
<?php
$insideOrders = \App\OutsideModel::where('total_id', '=', $order->order_id)->get();
?>
#foreach($insideOrders as $index => $inside)
<tr>
<td>{{ $index + 1 }}</td>
<td>{{ $inside->menu->name }}</td>
<td>{{ $inside->menu->category->name }}</td>
<td>{{ $inside->order_amount }}</td>
<td>
#if($order->status=='1')
<button id="send_order" class="btn btn-primary btn-xs"
order_id="{{$order->order_id}}">ارسال<i id="send_icon"></i>
</button>
#else
<button class="btn btn-success btn-xs" disabled>ارسال شده</button>
#endif
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
Then:-
$('#apended_tb table tbody').on('click', 'button', function () {........}

Replace this
$('table tbody').on('click', 'button', function () {
with following:
$(document).on('click', '#send_order', function () {
And there is a mistake change order_id with
data-order_id

Related

Laravel VueJs store array from axios request in laravel controller

I have a laravel 5.7 application which uses VueJS 2.0 for the front end.
I have two table with many-to-many relation: commandes and produits.I am currently attempting to pass data in to my commandes table but i am getting this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column '0' in 'field list' (SQL: insert into `commande_produit` (`0`, `commande_id`, `produit_id`) values (3, , 0))
If anyone can tell me how to fix or even point me in the right direction it would be much appreciated.
The html template:
<template>
<div class="container">
<div class="row justify-content-center mt-5" v-if="$gate.isAdminOrVendeur()">
<div class="col-md-12">
<form class="" #submit.prevent="envoyer()" >
<table class="table table-bordered table-striped table-responsive">
<thead class="thead-dark">
<tr>
<th class="col-sm-4">Produit</th>
<th class="col-sm-2">Quantité</th>
<th class="col-sm-2">montant</th>
<th class="col-sm-2">Total</th>
<th class="col-sm-1"></th>
<th class="col-sm-1"></th>
</tr>
</thead>
<tbody>
<tr v-for="(commande, index) in commandes" :key="index">
<td>{{ commande.produit_id }}</td>
<td>{{ commande.quantite }}</td>
<td>{{ commande.montant }} F</td>
<td>{{ (commande.quantite * commande.montant).toFixed(2) }} F</td>
<td><a class="btn btn-info btn-block" #click="modifier(index)">Modifier</a></td>
<td><a class="btn btn-warning btn-block" #click="supprimer(index)">Poubelle</a></td>
</tr>
<tr>
<td colspan="3"></td>
<td><strong> F </strong></td>
<td colspan="2"></td>
</tr>
<tr>
<td>
<div class="form-group">
<select v-model="form.produit_id" name="produit_id" class="form-control">
<option v-for="produit in produits.data" :key="produit.id" v-bind:value="produit.id">{{ produit.designation }}</option>
</select>
</div>
</td>
<td><input type="text" class="form-control" v-model="form.quantite"></td>
<td><input type="text" class="form-control" v-model="form.montant"></td>
<td colspan="3"><a class="btn btn-primary btn-block" #click="ajouter">Ajouter</a></td>
</tr>
</tbody>
<tfoot>
<a class="button btn btn-xs btn-warning" #click="toutPoubelle">Tout à la poubelle</a>
<button class="button btn btn-xs btn-success" type="submit">Valider</button>
</tfoot>
</table>
</form>
<div class="panel panel-danger" v-show="poubelle.length">
<div class="panel-heading">Poubelle</div>
<table class="table table-bordered table-striped table-responsive">
<thead>
<tr>
<th class="col-sm-4">Produit</th>
<th class="col-sm-2">Quantité</th>
<th class="col-sm-2">montant</th>
<th class="col-sm-2">Total</th>
<th class="col-sm-1"></th>
<th class="col-sm-1"></th>
</tr>
</thead>
<tbody>
<tr v-for="(commande, index) in poubelle" :key="index">
<td>{{ commande.produit }}</td>
<td>{{ commande.quantite }}</td>
<td>{{ commande.montant }} F</td>
<td>{{ (commande.quantite * commande.montant).toFixed(2) }} F</td>
<td><a class="btn btn-success btn-block" #click="retablir(index)">Rétablir</a></td>
<td><a class="btn btn-danger btn-block" #click="eliminer(index)">Supprimer</a></td>
</tr>
</tbody>
</table>
<div class="panel-footer">
<div class="btn-group">
<a class="button btn btn-xs btn-success" #click="toutRetablir">Tout rétablir</a>
<a class="button btn btn-xs btn-danger" #click="toutEliminer">Tout supprimer</a>
</div>
</div>
</div>
</div>
</div>
</div>
</template>
My vue instance:
<script>
export default {
data () {
return {
commandes: [],
poubelle: [],
produits: {},
form: new Form({
produit_id : '',
quantite : '',
montant: '',
})
}
},
methods: {
ajouter() {
this.commandes.push({produit_id: this.form.produit_id, quantite: this.form.quantite, montant: this.form.montant});
this.form = {};
this.commandes.sort(ordonner);
},
modifier(index) {
this.form.produit_id = this.commandes[index].produit_id;
this.form.quantite = this.commandes[index].quantite;
this.form.montant = this.commandes[index].montant;
this.commandes.splice(index, 1);
},
supprimer(index) {
this.poubelle.push(this.commandes[index]);
this.commandes.splice(index, 1);
this.poubelle.sort(ordonner);
},
retablir(index) {
this.commandes.push(this.poubelle[index]);
this.poubelle.splice(index, 1);
this.commandes.sort(ordonner);
},
eliminer(index) {
this.poubelle.splice(index, 1);
},
toutPoubelle() {
this.poubelle = this.poubelle.concat(this.commandes);
this.poubelle.sort(ordonner);
this.commandes = [];
},
toutRetablir() {
this.commandes = this.commandes.concat(this.poubelle);
this.commandes.sort(ordonner);
this.poubelle = [];
},
toutEliminer() {
this.poubelle = [];
},
loadProduits(){
//if(this.$gate.isAdminOrComptable()){
axios.get("api/produit").then(({ data }) => (this.produits = data));
//}
},
envoyer() {
axios.post('api/commande', {commande: this.commandes});
this.commandes = [];
},
},
mounted() {
this.loadProduits();
console.log('Component mounted.')
}
}
var ordonner = function (a, b) {
return (a.commande.toUpperCase() > b.commande.toUpperCase())
};
</script>
This is the commandes model:
class Commande extends Model
{
protected $fillable = ['commande'];
public function produits()
{
return $this->belongsToMany('App\Models\Produit');
}
}
and the produits model:
class Produit extends Model
{
protected $fillable = ['designation'];
public function commandes()
{
return $this->belongsToMany('App\Models\Commande');
}
}
the commande controller store() method:
public function store(Request $request)
{
$this->validate($request,[
'commande' => 'required',
]);
$commande = new Commande();
$commande->produits()->attach([$request->commande]);
$commande->save();
}
Several things may not work as expected in your code:
You are trying to attach produits on a non-existing model.
By using new Commande you are just preparing the object Commande and not yet saving it to the database. You can't attach anything on it since it doesn't have an id yet.
Solution: use Create instead of New
The method attach() is not used properly
As per the doc (https://laravel.com/docs/7.x/eloquent-relationships#updating-many-to-many-relationships) attach() is expecting an array of ids. You are trying to pass a custom array so the method won't work.
Solution: extract the Ids from your $request->command and then use attach()
Her is the final store() function:
public function store(Request $request)
{
$this->validate($request,[
'commande' => 'required',
]);
$commande = new Commande();
$commande->save();
$produitsId = array_column($request->commande, 'produit_id');
$commande->produits()->attach($produitsId);
}
Hope it help someone.

Delete record in firebase with Javascript - Vuejs

I am able to show all data from my products record in Firebase DB, what i want now is to delete a certain record that i select.
I got a bit of the documentation of Firebase but i'm not so good with VueJs, although i think this is more of a JavaScript problem.
What i get on my console when i click the delete link is:
Error: Firebase.child failed: First argument was an invalid path:
"undefined". Paths must be non-empty strings and can't contain ".",
"#", "$", "[", or "]"
Here is my code:
<template>
<tbody v-for="(key, value, index) in products">
<tr v-for="k, val in key">
<td>{{ k.name }}</td>
<td>{{ k.description }}</td>
<td>{{ k.oldPrice }}</td>
<td>{{ k.price }}</td>
<td>{{ k.prodId }}</td>
<td>{{ k.sellerName }}</td>
<td><span class="glyphicon glyphicon-trash btn-delete-style" v-on:click="removeProduct(k)" title="Delete Product"></span></td>
</tr>
</tbody>
</template>
<script>
removeProduct: function (product) {
console.log("Product:" + product);
productsRef.child(product['.key']).remove();
toastr.success("Product deleted successfully");
}
</script>
Below you can see my DB:
Any help is appreciated, Thank you.
You need to reference first to that record and then call the remove function, here is an example:
<template>
<tbody v-for="(key, value, index) in products">
<tr v-for="k, val in key">
<td>{{ k.name }}</td>
<td>{{ k.description }}</td>
<td>{{ k.oldPrice }}</td>
<td>{{ k.price }}</td>
<td>{{ k.prodId }}</td>
<td>{{ k.sellerName }}</td>
<td><span class="glyphicon glyphicon-trash btn-delete-style" v-on:click="removeProduct(k, k.sellerId, k.prodId)" title="Delete Product"></span></td>
</tr>
</tbody>
</template>
<script>
removeProduct: function (product, sellerID, prodId) {
var currentRef = db.ref('products/' + sellerID + '/' + prodId);
currentRef.remove();
toastr.success("Product deleted successfully");
}
</script>
I think you should take product id from prodid
productsRef.child(product['prodid']).remove()

Refresh div by class using jQuery

i have table render with PHP using foreach loop.
#foreach ($comments as $comment)
<tr>
<td>{{ $comment->lot_date }}
<br>
#if (count($comment->ourcar) >= 1)
<p>Saved</p>
#else
<form method="POST" action="/comments/{{ $comment->id }}/ourcars">
{{ csrf_field() }}
<button type="submit" class="btn btn-xs btn-primary">Our Car</button>
</form>
#endif
</td>
<td>
{{ $comment->bid }}
</td>
<td>{{ $comment->auction_name }}</td>
<td class="block">
#foreach(explode('#', $comment->pics_urls, 3) as $pic)
<a href="{{ $pic }}" class='iframe'>
<img src="{{ $pic }}" class="img-fluid" width="30" height="32">
</a>
#endforeach
</td>
<td>{{ $comment->company }}</td>
<td>{{ $comment->model_name_en }}</td>
<td>{{ $comment->model_type_en }}</td>
<td>{{ $comment->grade_en }}</td>
<td>{{ $comment->model_year_en }}</td>
<td>{{ $comment->color_en}}</td>
<td>{{ $comment->displacement }}</td>
<td>{{ $comment->transmission_en }}</td>
<td>{{ $comment->scores_en }}</td>
<td>{{ $comment->mileage_num }}</td>
<td>{{ $comment->start_price_en }}</td>
<td><div class="comment-body">{{ $comment->body }}</div></td>
<td>{{ $comment->lot->result_en or '---' }}</td>
<td>{{ $comment->user->name }}
<td>
<button data-id="{{ $comment->id }}" class="btn-link editButton"><span class='glyphicon glyphicon-edit'></span></button>
</td>
<td>
<form method="POST" action="{{route('comments.destroy', ['id' => $comment->id]) }}">
{{ method_field('DELETE') }}
{{ csrf_field() }}
<div class="form-group">
<button type="submit" class="btn-link" onclick="return confirm('Are you sure?')"><span class='glyphicon glyphicon-trash' style="color:red"></span></button>
</div>
</form>
</td>
</tr>
#endforeach
I create a modal window to add comment to the row using JS. After i submit comment and modal is closed and i want to refresh content in <td class="comment-body">comment</td>
So i have a problem with refreshing div by class, i can use an id because table is looped:
$(function() {
$('.editButton').click(function (e) {
var button = $(this);
var geturl = '/comments/' + button.data('id') + '/edit';
var posturl = '/comments/' + button.data('id');
$.get(geturl)
.done( (response) => {
bootbox.dialog( {
title : "Add comment",
message : response,
buttons : {
addButton : {
label : 'Add comment',
className : 'btn btn-primary',
callback: () => {
var modalForm = $('#modalForm');
if ($('#commentBody').val()) {
$.ajax({
type : 'POST',
url : posturl,
data : modalForm.serialize(),
success : (response) => {
if (response === "ok") {
bootbox.hideAll();
$('.comment-body').toggle();
}
}
})
}
return false;
}
},
closeButton : {
label : 'Close',
className : 'btn btn-default'
}
}
})
})
.fail( ( errorResponse ) => {
bootbox.alert('Error! Comment is not added');
});
});
});
</script>
My modal view:
<div class="modal-body">
<form action="#" id="modalForm" data-id="{{ $comment->id }}">
<div class="form-group">
{{ csrf_field() }}
{{ method_field('PUT') }}
<textarea name="body" id="commentBody"
placeholder="Add Your Comment Here." class="form-control" required>{{ $comment->body }}</textarea>
</div>
</form>
</div>
This is the result:
I tried to use $('.comment-body').toggle(); but it is not working. How should i refresh that div after editing comment?
If I got your point .. I think its very simple
1st: you need to use after var button = $(this);
var comment_section = button.closest('tr').find('.comment-body');
2nd: on ajax success callback function
comment_section.text($('#commentBody').val());
var old_comment = $('.comment-body').text();
$('.comment-body').text(old_comment + '\n' + new_comment);
I don't really understand about your refresh. The code above is to append a new comment to old ones.
Set the innerHTML of the element to populate it, or use empty string to clear it:
$('.comment-body').html("New Comment") // New contents
$('.comment-body').html("") // Clear contents
If you have a .comment-body in more than one row of your table, and you only want to "refresh" one of them, then you'll need to specify an id so you can pinpoint the row that contains the cell. E.g...
<tr id="row1"><td class="comment-body">..comment..</td><tr>
$("#row1").find(".comment-body").html("New Comment Text")
NB: Instead of .html you may also use .text to prevent html code in users' comments from being injected into your page.
$('.comment-body').('');
Try this or
$('.comment-body').html('');

Unable to call function using infinite-scroll in angularjs

I am trying to implement a scrolling pagination, for this I tried many tutorials at the end found this Tutorial. i wrote the code in a way it was instructed but not getting the desired output.
HTML :
<tbody infinite-scroll="getMoreData()">
<tr ng-repeat="amenitydetail in amenitydetails">
<td class="text-right">{{ currentOffset + $index + 1}}</td>
<td>{{ amenitydetail.name}}</td>
<td>{{ amenitydetail.address}}</td>
<td>{{ amenitydetail.phoneNumber}}</td>
<td>{{ amenitydetail.mobileNumber}}</td>
<td>{{ amenitydetail.city.name}}</td>
<td>{{ amenitydetail.location.name}}</td>
<td>{{ amenitydetail.amenity.name}}</td>
<td>{{ amenitydetail.latitude}}</td>
<td>{{ amenitydetail.longitude}}</td>
<td class="">
<a data-ui-sref="admin.masters_amenity_detail.edit({ amenity_detailId: amenitydetail.id })"
class="btn btn-primary">
<i class="fa fa-pencil"></i>
</a>
<a data-ui-sref="admin.masters_amenity_detail.delete({ amenity_detailId: amenitydetail.id})"
class="btn btn-danger">
<i class="fa fa-trash"></i>
</a>
</td>
</tr>
</tbody>
My JS is as follows :
$scope.amenitydetails = AmenityDetailService.findAmenityDetails(function (amenitydetails) {
angular.forEach(amenitydetails, function (amenitydetail) {
amenitydetail.amenity = AmenityService.get({
'id': amenitydetail.amenityId
});
amenitydetail.location = LocationService.get({
'id': amenitydetail.locationId
});
amenitydetail.city = CityService.get({
'id': amenitydetail.cityId
});
});
});
$scope.data = $scope.amenitydetails.slice(0, 5);
$scope.getMoreData = function () {
console.log("Coming to get more data?");
$scope.data = $scope.amenitydetails.slice(0, $scope.data.length + 5);
}
My log inside getMoreData function is not getting printed.Can anyone let me know where I am getting wrong??

JavaScript click function table cell only applied on the first row

I had a JavaScript click function on a table row, but when I click it, the function only works on the first row. How do I fix this?
<script type="text/javascript">
$(document).ready(function(){
$('#detpanel').hide();
$("#showdet").click(function(){
$('#detpanel').slideDown(500);
});
$("#hidedet").click(function(){
$('#detpanel').slideUp(500);
});
$('#showdet').hover(function(){
$(this).divhover("background-color", "yellow");
});
});
</script>
<tbody>
<?php $i = 0; ?>
#foreach ($auser as $res)
<?php $i += 1; ?>
<tr #if($i%2==0) class="bgcolor dihover" #endif id='showdet' class="dihover">
<td>{{ $res->id }}</td>
<td>{{ $res->name }}</td>
<td>{{ $res->email }}</td>
<td>
<a class="default-btn" href="/pms/admin/user/edit/{{ $res->id }}">Edit</a> |
<a type="submit" class="default-btn del" data-id="admin-user" href="pms/admin/user/delete/{{ $res->id }}">Delete</a>
</td>
</tr>
#endforeach
</tbody>
ID of an element must be unique, since you are creating the elements in a loop use class.
When using ID selector it will return only the first element with the said ID, so in your case the click handler is getting registered to only the first element
<tbody>
<?php $i = 0; ?>
#foreach ($auser as $res)
<?php $i += 1; ?>
<tr #if($i%2==0) class="bgcolor dihover" #endif class='showdet' class="dihover">
<td>{{ $res->id }}</td>
<td>{{ $res->name }}</td>
<td>{{ $res->email }}</td>
<td>
<a class="default-btn" href="/pms/admin/user/edit/{{ $res->id }}">Edit</a> |
<a type="submit" class="default-btn del" data-id="admin-user" href="pms/admin/user/delete/{{ $res->id }}">Delete</a>
</td>
</tr>
#endforeach
</tbody>
then use class selector to register the click handler
$(document).ready(function () {
$('#detpanel').hide();
$(".showdet").click(function () { //use class selector here
$('#detpanel').slideDown(500);
});
$("#hidedet").click(function () {
$('#detpanel').slideUp(500);
});
$('#showdet').hover(function () {
$(this).divhover("background-color", "yellow");
});
});

Categories