I want to retrieve data from DB to my user Dashboard. User Identify using Contact No.
I run AJAX query to retrieve all adds. its running well.
but I need to retrieve data under his user ID (ContactNo). here I add AJAX code.
user data avaiable in AUTH -> {{ Auth::user()->ContactNo }}
$(document).ready(function($){
//alert("jquery running");
getAll();
});
//getting all rows from the database
function getAll() {
$.ajax({
url: '{{ route('Myadds', app()->getLocale()) }}',
type: 'GET',
})
.done(function(data) {
alert("run")
$.each(data, function(index, val) {
$('#data').append('<tr>')
$('#data').append('<td>'+val.id+'</td>')
$('#data').append('<td>'+val.Sdescription+'</td>')
$('#data').append('<td>'+val.created_at+'</td>')
$('#data').append('<td><button class="btn btn-xs btn-danger" data-id="'+val.id+'">Delete</button><button class="btn btn-xs btn-info" data-id="'+val.id+'">Edit</button></td>')
$('#data').append('</tr>')
});
})
.fail(function() {
alert("fail")
console.log("error");
})
}
</script>
You need to pass de contactNo parameter in your query:
function getAll() {
$.ajax({
url: '{{ route('Myadds', app()->getLocale()) }}',
type: 'GET',
data: {
contact_no: contactNo,
},
})
.done(function(data) {
alert("run")
$.each(data, function(index, val) {
$('#data').append('<tr>')
$('#data').append('<td>'+val.id+'</td>')
$('#data').append('<td>'+val.Sdescription+'</td>')
$('#data').append('<td>'+val.created_at+'</td>')
$('#data').append('<td><button class="btn btn-xs btn-danger" data-id="'+val.id+'">Delete</button><button class="btn btn-xs btn-info" data-id="'+val.id+'">Edit</button></td>')
$('#data').append('</tr>')
});
})
.fail(function() {
alert("fail")
console.log("error");
})
}
So in your controller now you can filter:
public function getData(Request $request){
$contact_no = $request->contact_no;
$query = DB::table('my_table');
if($contact_no){
$query->where('contact_no',$contact_no)
}
return response()->json($query->get());
}
Or directly use the session of the user:
public function getData(Request $request){
$contact_no = Auth::user()->ContactNo;
$query = DB::table('my_table');
$query->where('contact_no',$contact_no)
return response()->json($query->get());
}
public function Myadds(){
try{
return add::where('userID', Auth::user()->ContactNo)->get();
}catch(Exception $e){
return 'false';
}
}
Related
BLADE FILE
<td><button class="deleteuser" data-id="{{ $user->id }}" data-token="{{ csrf_token() }}" >DELETE</button>
</td>
AJAX
$(document).ready( function () {
$(".deleteuser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "user/delete/"+id,
type: 'DELETE',
dataType: "JSON",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
}
});
console.log("It failed");
});
});
CONTROLLER
public function destroyuser($id){
$this->authorize('Admin');
User::find($id)->delete($id);
return response()->json([
'success' => 'Record has been deleted successfully!'
]);
return view('viewuser');
}
If I click on delete button, there is no response. Any suggestion or correction will be appreciated. Thanks in advance
I don't know if the JS is in a different file but to check if the "$( document ).ready()" is working add a console.log() call at the beginning.
$(document).ready( function () {console.log("document is ready")
$(".deleteuser").click(function(){
Refresh the page and check if "document is ready" is logged to the console.
If it isn't then the javascript is not loading
Check if the route is properly defined
You can replace your url as this and check:
var id = data.id;
var url = "{{route('your_route',":id") }}";
url = url.replace(':id', id);
pass url in your ajax url param
Or make above changes:
BLADE FILE
<td>
<button style="background-color: red;" onclick="clickOffConfirmed" title="Delete" class="btn btn-sm btn-clean btn-icon btn-icon-md delete"><i class="la la-trash" style="color: white;"></i></button>
</td>
SCRIPT
<script>
$(document).ready(function() {
$(document).on('click', '.delete', function ()
{
var obj = $(this);
var id=$(this).closest('td').find(".delete_id").val();
var result = confirm("Are you sure want to delete?");
if(result)
{
$.ajax(
{
type: "POST",
url: "{{route('delete_method')}}",
data: {
'_token': $('input[name="_token"]').val(),
'id': id
},
cache: false,
success: function (data)
{
if (data.status === 'success')
{
window.location = "{{route('redirect_route')}}";
toastr["success"]("Deleted Successfully", "Success");
}
else if (data.status === 'error')
{
location.reload();
toastr["error"]("Something went wrong", "Opps");
}
}
});
}
});
});
</script>
Controller
public function delete_method(Request $request)
{
$del = ModelName::findOrFail($request->id)->delete();
if($del)
{
return response()->json(['status' => 'success']);
}
else{
return response()->json(['status' => 'error']);
}
}
Route
Route::post('/test/delete','TestController#delete_method')->name('delete_method');
In your ajax codes, change this:
url: "user/delete/"+id,
To:
url: "{{ url('user/delete') }}/" + id
If your ajax codes are inside of your blade file also you can use this way:
url: "{{ route('YOUR_ROUTE_NAME', $user->id) }}/"
You incorrectly define delete function!
change
User::find($id)->delete($id);
To
User::find($id)->delete();
I have a list of manufacturers with checkbox when i checkbox is checked ajax is called and hit the controller but not return anything
I am using laravel 5.1
#foreach($manufacturers as $leedsManufacturer) {{-- #foreach($leedManufacturers as $leedsManufacturer) --}}
<div class="post" id="post{{$leedsManufacturer['mfgg_id']}}">
<label class=" my-checkbox gry2" id="manufacturer">{{str_limit($leedsManufacturer['mfgg_name'], 300)}}
<input type="checkbox" class="manufacturer common_selector" name="manufacturer[]" value="{{$leedsManufacturer['mfgg_id']}}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<span class="checkmark"></span>
</label>
</div>
#endforeach
#endif
script
$(document).ready(function() {
filter_data();
function filter_data() {
var manufacturer = get_filter('manufacturer');
// var products = get_filter('products');
// var chps_approved = get_filter('chps_approved');
$.ajax({
url: "{{url('ajax1')}}",
method: 'POST',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data:{manufacturer:manufacturer} ,
success:function(data){
console.log(data);
}
});
// alert(manufacturers);
}
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
alert(filter);
// return filter
}
$('.common_selector').click(function(){
filter_data();
});
});
controller
public function ajax1(Request $request){
$data= $request->manufacturer;
return response()->json($data);
}
On checkbox select, it should return the ID so i can use it in controller. but $request->manufacturer show this on console.
try this lets see if you are getting the id from the form. i use javascript alert
$(document).ready(function() {
filter_data();
function filter_data() {
var manufacturer = get_filter('manufacturer');
alert(manufacturer);
// var products = get_filter('products');
// var chps_approved = get_filter('chps_approved');
$.ajax({
url: "{{url('ajax1')}}",
method: 'POST',
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
data:{manufacturer:manufacturer} ,
success:function(data){
console.log(data);
}
});
// alert(manufacturers);
}
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
alert(filter);
// return filter
}
$('.common_selector').click(function(){
filter_data();
});
});
Hi all i am trying to delete my record from datatable with out page refresh in codeigniter i have used ajax i don't know where i have done mistake its not deleting the record
Below is the my view:
<tbody>
<?php
if (!empty($employees)) {
foreach ($employees as $emp) {
?>
<tr>
<td><?php echo $emp->emp_name; ?></td>
<td><?php echo $emp->salary; ?></td>
<td class='text-center'>
<button type="submit" class="btn btn-info btn-xs confirmation" name="login"><i class='fas fa-edit'></i></button>
</td>
<td class='text-center'>
<button type="submit" onClick="return ConfirmDelete()" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
</td>
</tr>
<?php
}
}
?>
</tbody>
<script>
$(document).ready(function(){
$(".empdelete").click(function(e){
alert();
e.preventDefault();
$.ajax({
alert();
type: "POST",
url: "<?=site_url('Employee/delete');?>",
cache: false,
data: {id:$(this).attr("id")}, // since, you need to delete post of particular id
success: function(data) {
if (data){
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
</script>
Here is the my controller:
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete=$this->Emp_model->delete($id);
if($empdelete){
echo true;
} else {
echo false;
}
}
Here is my model's method delete:
function delete($id)
{
$sql = "DELETE FROM employees WHERE id=?";
return $this->db->query($sql,array($id));
}
Can any one help me how can i do that with out page refresh i want to delete my record.
Thanks in advance.
Try this:
$(document).ready(function () {
function ConfirmDelete() {
var x = confirm("Are you sure you want to delete?");
if (x)
return true;
else
return false;
}
$(".empdelete").click(function (e) {
var obj = $(this);
e.preventDefault();
//alert(); what's this do?
if (ConfirmDelete() == false) {
return false;
}
$.ajax({
//alert(); this can't go here
type: "POST",
url: "<?php echo site_url('Employee/delete'); ?>",
cache: false,
data: {id: $(this).attr("id")},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
obj.closest('tr').remove();
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
});
});
and remove HTML onClick:
<button type="submit" class="btn btn-danger btn-xs confirmation empdelete" id="<?php echo $emp->id;?>"><i class='fas fa-times'></i></button>
Hope this will help you :
Your button should be like this :
<button type="button" onClick="return ConfirmDelete(this)" class="btn btn-danger btn-xs confirmation empdelete" data-id="<?=$emp->id;?>"><i class='fas fa-times'></i></button>
Your ajax code should be like this :
function ConfirmDelete(obj)
{
var x = confirm("Are you sure you want to delete?");
if (x == true)
{
var id = $(obj).data('id');
alert(id);
if (id != '')
{
//do you ajax here
$.ajax({
type: "POST",
url: "<php echo site_url('Employee/delete'); ?>",
cache: false,
data: {'id': id},
success: function (data) {
console.log('ajax returned: ');
console.log(data);
if (data) {
alert("Success");
} else {
alert("ERROR");
}
return false;
}
});
}
}
else
{
return false;
}
}
Your controller should be like this :
function delete()
{
$id = $this->input->post('id'); // get the post data
$empdelete = $this->Emp_model->delete($id);
if($empdelete)
{
echo true;
} else
{
echo false;
}
exit;
}
Your delete method should be like this :
function delete($id)
{
$this->db->where('id',$id);
$this->db->delete('employees');
return $this->db->affected_rows();
}
I'm stuck in making a delete method using vue js and laravel. I tried to add a value to the href attribute using laravel resource and pass an id as a second parameter but when I click on it and display the id on console it shows the same id to all data which is incorrect.
Sample blade:
<a id="deleteRecord" data-id="{{$project->id}}" #click.prevent="deleteRecord" class="btn btn-circle btn-icon-only btn-danger" href="{{ route('projects.store', $project->id) }}">
<i class="icon-trash"></i>
</a>
Vue method:
deleteRecord: function(id) {
var dataId = $('#deleteRecord').attr('href')
console.log(dataId);
}
Inside of your method deleteRecord:
this.$http.delete(url)
.success(function(response) {
console.log(response)
})
.error(function(errors) {
console.log(error)
});
Or using axios inside of your method
axios.delete(url)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
I get it now. I'll just post it here to help others also.
deleteRecord: function(id) {
var url = "projects" + "/" + id;
$.ajax({
url: url,
type: 'DELETE',
data: { "_token": "{{ csrf_token() }}" },
success: function(response) {
//do some success stuff here..
}
});
}
i'm new on AngularJS and i spent hours trying ti figure out what wrong whith my code...
var articles = angular.module('Articles', []).config(function($interpolateProvider){
$interpolateProvider.startSymbol('{§').endSymbol('§}');
});
articles.controller('CommentsCtrl', ['$scope', '$http', function($scope, $http) {
this.comments = [];
this.showComments = function (index) {
$http({
method: 'POST',
url: '{{ path ('backend_article_commentaires')}}',
data: {articleID:index}
})
.success(function (data, status, headers, config) {
comments = data;
})
.error(function (data, status, headers, config) {
console.log(data)
});
}
}]);
the problem is that the comments variable dont change...
please how can i solve this ?
Update:
<div class="md-modal md-effect-13" id="modal-comments"
ng-controller="CommentsCtrl as ctrl">
<div class="md-content">
<h3>
<i class="fa fa-comments"></i> Tous les commentaires
</h3>
<div>
<div id="list-comment">
<h4>Cet article n'a aucun commentaires...</h4>
<li ng-repeat="comment in ctrl.comments" class="media">
<a>{{ comment.title }}</a>
</li>
</div>
<div class="button-row">
<button class="btn btn-danger md-close md-yes">Fermer</button>
</div>
</div>
</div>
</div>
Your problem is one of scopes (and not angular scopes) the this in your success function would not be the same as your this in your controller. If you assign "this" to a variable in the controller and then reference that you should be good to go.
articles.controller('CommentsCtrl', ['$scope', '$http', function($scope, $http) {
this.comments = [];
var rootThis = this;
this.showComments = function (index) {
$http({
method: 'POST',
url: '{{ path ('backend_article_commentaires')}}',
data: {articleID:index}
})
.success(function (data, status, headers, config) {
rootThis.comments = data;
})
.error(function (data, status, headers, config) {
console.log(data)
});
}
}]);
As you can see I created a rootThis variable to hold the "this" that way I can use it in the success function