I've created a restful API using laravel controllers. I have a PhotosController which has a destroy($id) method for resource deletion. also I have a piece of javascript code that sends a DELETE request to my app. the result should be the deletion of the photo with $id id. but laravel doesn't route my request to destroy method. instead it sends an 401 Unauthorized error.
the thing is that I want to send DELETE request to my app via Ajax, but laravel doesn't let my request to be routed!
routes.php file :
Route::resource('photos', 'PhotosController');
destroy method :
public function destroy($id)
{
try{
unlink($_SERVER["DOCUMENT_ROOT"].'/uploads/doctors/' . $id);
Session::forget('photo');
$msg = Notification::where('flag', 's')->where('code', 'user-update-delete-photo-gallery')->first()->msg;
return Response::json(array('success' => $msg));
}catch (Exception $e){
App::abort(500, $e->getMessage());
}
}
my Ajax request :
$.ajax(
{
url: "/photos/" + name,
method : "DELETE", // Or POST : result is the same
data :{
_token : $("input[name=_token]").val(),
_method : 'DELETE'
},
success: function(data, textStatus, jqXHR ){
parent.replaceWith("");
toastr.success(data['success']);
$("#overlay").hide();
},
beforeSend : function(jqXHR, settings ){
$("#overlay").show();
},
error : function(jqXHR, textStatus, errorThrown ){
toastr.error(jqXHR.responseText);
$("#overlay").hide();
}
}
);
Thanks for your help.
I do this sort of thing all the time in my Laravel Apps with no issues. This code allows the user to delete a resource through AJAX while presenting a bootstrap confirmation dialog first. The code is laid out in the order the events would occur.
VIEW WITH RESOURCE TO DELETE
<a class="delete-plan" href="{{ route('admin.plans.destroy', $plan['id']) }}" data-redirect="{{ route('admin.plans.index') }}" data-plan-name="{{ $plan['name'] }}" data-lang="billing.plans">
<i class="fa fa-trash fa-lg"></i>
</a>
JQUERY TO PROMPT CONFIRMATION MODAL
$('.delete-plan').on('click', function(e) {
e.preventDefault();
var data = {
'route': $(this).attr('href'),
'redirect': $(this).data('redirect'),
'modal_title': 'Delete Plan',
'content_view': 'Are you sure you want to delete plan: <strong>' + $(this).data('plan-name') + '</strong>?',
'lang': $(this).data('lang')
};
loadDestroyModal(data);
});
function loadDestroyModal(data) {
$.get('/ajax/destroy-modal', { data: data }, function(modal) {
$('body').append(modal);
$('#destroy-modal').modal('show');
});
}
AJAX CONTROLLER
// routed by /ajax/destroy-modal
public function destroyModal() {
$data = Input::get('data');
$params = [
'route' => $data['route'],
'redirect' => $data['redirect'],
'title' => $data['modal_title'],
'content' => $data['content_view'],
'lang' => $data['lang']
];
return View::make('_helpers.modal-destroy', $params);
}
DESTROY CONFIRMATION MODAL (_helpers.modal-destroy)
<div id="destroy-modal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">
<span aria-hidden="true"><i class="fa fa-times"></i></span>
<span class="sr-only">Close</span>
</button>
<h4 class="modal-title">{{ $title }}</h4>
</div>
<div class="modal-body">
{{ $content }}
</div>
<div class="modal-footer">
<button id="modal-confirm" type="button" class="btn btn-primary" data-route="{{ $route }}"
data-redirect="{{ $redirect }}" data-lang="{{ $lang }}">Confirm</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
JQUERY TO PROCESS DESTROY METHOD AND REDIRECT FLASH MESSAGE
$('body').on('click', '#destroy-modal #modal-confirm', function(e) {
var redirect = $(this).data('redirect');
var lang = $(this).data('lang');
$(this).html('<i class="fa fa-spinner fa-spin"></i> Please Wait');
$.ajax({
'url': $(this).data('route'),
'type': 'DELETE',
'success': function(response) {
if (response) {
redirectWithFlashMessage(redirect, 'destroy', 'success', lang);
} else {
redirectWithFlashMessage(redirect, 'destroy', 'errors', lang);
}
}
});
});
PLANS CONTROLLER
public function destroy($id)
{
try
{
Stripe::plans()->destroy(['id' => $id]);
return Response::json(TRUE);
}
catch (Exception $e)
{
return Response::json(FALSE);
}
}
JQUERY FOR REDIRECTION
function redirectWithFlashMessage(redirect, type, status, lang) {
var params = {
type: type,
status: status,
lang: lang
};
$.get('/ajax/flash', params, function(response) {
window.location.href = redirect;
});
}
AJAX CONTROLLER (Redirect with Flash)
public function flashData() {
$message_type = 'success' == Input::get('status') ? 'success' : 'failure';
$message = Lang::get(Input::get('lang'))[Input::get('type') . '_' . $message_type];
Session::flash($message_type, $message);
return ['status' => $message_type, 'message' => $message];
}
It's a lot of code but once setup it's extremely easy to replicate.
I think your system's requiring the authentication for controller action "destroy" method. So you need to login before calling that method.
If you're using the middleware "auth" (app\Http\Middleware\Authenticate.php), you can easy find the "handle" function that returning "Unauthorized" error.
Hope this will help.
Related
I am trying to take amount from the html tags and store the amount into database but the about here
ajax code is not working and data is not stored in the database. And how to know if ajax code is redirected it's control to the laravel controller
#include('layouts.students.header')
<meta name="csrf-token" content="{{csrf_token()}}">
<body>
<div class="col">
<p class="text-right" style="font-size: 18px;">
<i class="fa fa-rupee"></i><strong
class="amount">299</strong>
</p>
</div>
<div class="form-group text-right">
<button class="btn btn-warning btn-block btn-lg
buy_now">Proceed</button>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('button').click(function(event){
e.preventDefault();
var amount = $('.amount').html();
$.ajax({
url : '{{route('razorpay')}}',
method : 'POST',
dataType : 'jason',
data : {amount :amount * 100},
success : function (Response) {
console.log(Response);
}
});
});
});
</script>
</body>
</html>
controller :
public function dopayment(Request $request)
{
$data = $request->all();
$result = Payment::insert($data);
echo "inserted";
}
In ajax method can you use dataType : 'json', instead of jason
I am creating commenting system. Now, I want to post a new comment, but when I send a comment, I got an error in http://127.0.0.1:8000/comments/51.
The GET method is not supported for this route. Supported methods:
POST.
I want to post a comment in this URL http://127.0.0.1:8000/results/51.
In my chrome dev tool console, I have this error
Failed to load resource: the server responded with a status of 500
(Internal Server Error)
web.php
Route::middleware(['auth'])->group(function(){
//post a comment
Route::POST('comments/{post}', 'CommentController#store')->name('comment.store');
});
//comment area
Route::get('results/{post}/comments', 'CommentController#index');
Route::get('comments/{comment}/replies', 'CommentController#show');
comments.vue
<template>
<div class="commentarea" >
<div class="comment-posts" >
<div v-if="!auth" class="user-comment-area" >
<div class="user-post">
<!---<img src="{{asset('people/person7.jpg')}}" class="image-preview__image">--->
<input v-model="newComment" type="text" name="comment">
</div>
<div class="comments-buttons">
<button class="cancel-button">Cancel</button>
<button #click="addComment" class="comment-button" type="submit">Comment</button>
</div>
</div>
<h4>Comments ()</h4>
<div class="reply-comment" v-for="comment in comments.data" :key="comment.id">
<div class="user-comment">
<div class="user">
<!---<img src="{{ $comment->user->img }}" class="image-preview__image">--->
<avatar :username="comment.user.name"></avatar>
</div>
<div class="user-name">
<span class="comment-name">{{ comment.user.name }}</span>
<p>{{ comment.body }}</p>
</div>
</div>
<div class="reply">
<button class="reply-button">
<i class="fas fa-reply"></i>
</button>
</div>
<replies :comment="comment"></replies>
</div>
</div>
<div>
<button v-if="comments.next_page_url" #click="fetchComments" class="load">Load More</button>
</div>
</div>
</template>
<script>
import Avatar from 'vue-avatar'
import Replies from './replies.vue'
export default {
props: ['post'],
components: {
Avatar,
Replies
},
mounted() {
this.fetchComments()
},
data: () => ({
comments: {
data: []
},
newComment: '',
auth: ''
}),
methods: {
fetchComments() {
const url = this.comments.next_page_url ? this.comments.next_page_url : `/results/${this.post.id}/comments`
axios.get(url).then(({ data }) => {
this.comments = {
...data,
data: [
...this.comments.data,
...data.data
]
}
})
.catch(function (error) {
console.log(error.response);
})
},
addComment() {
if(! this.newComment) return
axios.post(`/comments/${this.post.id}`, {
body: this.newComment
}).then(( {data} ) => {
this.comments = {
...this.comments,
data: [
data,
...this.comments.data
]
}
})
}
}
}
</script>
commentsController.php
public function store(Request $request, Post $post)
{
return auth()->user()->comments()->create([
'body' => $request->body,
'post_id' => $post->id,
'comment_id' => $request->comment_id
])->fresh();
}
comment.php
protected $appends = ['repliesCount'];
public function post()
{
return $this->belongsTo(Post::class);
}
public function getRepliesCountAttribute()
{
return $this->replies->count();
}
I am glad if someone helps me out.
your URL is : http://127.0.0.1:8000/results/51.
your routes should be :
Route::group(['middleware' => 'auth'],function () {
Route::post('comments/{post_id}', 'CommentController#store')->name('comment.store');
});
your controller will be :
public function store(Request $request,$post_id)
{
return auth()->user()->comments()->create([
'body' => $request->body,
'post_id' => $post_id,
'comment_id' => $request->comment_id
])->fresh();
}
Thank you, I put catch method, and the issue was I did not include protected $fillable ['body','post_id', 'comment_id'] in comment model.
Guys I just created like/dislike buttons for every service! so I set a default grey color for each one of them, once the user click " like" it turns to green and for the opposite case it turns to red..
so I've created an ajax method for that...
I wanted to check if everything works fine with a simple alert()
but I got an error which is :
message: "Undefined property: Illuminate\Database\Eloquen\Builder::$like",…}
exception : "ErrorException"
— file : "C:\xampp\htdocs\dawerelzirou\app\Http\Controllers\ServiceController.php"
— line:164
message: "Undefined property: Illuminate\Database\Eloquent\Builder::$like"
trace : [
— { file: "C:\xampp\htdocs\dawerelzirou\app\Http\Controller\ServiceController.php", line: 164 }
]
This is like.js
$('.like').on('click', function() {
var like_s = $(this).attr('data-like');
var service_id = $(this).attr('data-serviceid');
$.ajax({
type: 'POST',
url: url,
data: {
like_s: like_s,
service_id: service_id,
_token: token
},
success: function(data) {
alert('ok');
}
});
});
This is the script:
<script type="text/javascript" src="{{ asset('js/like.js') }}"></script>
<script type="text/javascript">
var url="{{ route('like') }}";
var token="{{ Session::token() }}";
</script>
Here is the blade page :
#php
$like_count=0;
$dislike_count=0;
$like_statut="grey";
$dislike_statut="grey";
#endphp
#foreach ($services->likes as $like)
#php
if ($like->like ==1){
$like_count++;
}
else {
$dislike_count++;
}
if($like->like == 1 && $like->user_id==Auth::user()->id){
$like_statut="green";
}
else{
$dislike_statut="red";
}
#endphp
#endforeach
<div class="row">
<div class="col s12">
<button type="button"
data-like="{{$like_statut}}"
data-serviceid="{{$services->id}}"
class="like waves-effect waves-light btn {{$like_statut}}">
<i class="material-icons left">thumb_up</i>({{$like_count}})
</button>
</div>
</div>
<br>
<div class="row">
<div class="col s12">
<button type="button"
data-dislike="{{$dislike_statut}}"
class="dislike waves-effect waves-light btn {{$dislike_statut}}">
<i class="material-icons left">thumb_down</i>({{ $dislike_count}})
</button>
</div>
</div>
</div>
</div>
The route:
Route::post('/like','ServiceController#like')->name('like');
The "like" method in the controller:
public function like(Request $request)
{
$like_s = $request->like_s;
$service_id = $request->service_id;
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
if (!$like) {
$new_like = new Like;
$new_like->service_id = $service_id;
$new_like->user_id = Auth::user()->id;
$new_like->like = 1;
$new_like->save();
} elseif ($like->like == 1) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->delete()
;
} elseif ($like->like == 0) {
Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id,])
->update(array('like' => 1))
;
}
}
This row:
$like = Like::where(['service_id' => $service_id, 'user_id' => Auth::user()->id, ]);
seems incomplete, as it returns a query builder and not an object. The query builder has not a "like" property. If you want an object you should do: A first() at the end (or a get() followed by a foreach) seems to be missing.
I want to terminate a employee from the system. When clicks on terminate button it will popup a moadal asking whether wants to terminate or cancel. If terminate database value resign should be updated as 0, but right now button does not working.
Here is my code
controller
public function ajax_list()
{
$list = $this->employees->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $emp) {
$no++;
$row = array();
$row[] = $emp->employee_id;
$row[] = $emp->name;
$jid = $emp->job_title;
$desigdata = $this->employees->GetJobTitlebyID($jid);
$row[] = $desigdata->desc;
$did = $emp->department;
$deptdata = $this->employees->GetDepartmentbyID($did);
$row[] = $deptdata->title;
$secid = $emp->section;
$secdata = $this->employees->GetSectionbyID($secid);
$row[] = $secdata->desc;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void()" onclick="terminate_emp('."'".$emp->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Terminate</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->employees->count_all(),
"recordsFiltered" => $this->employees->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
public function ajax_terminate()
{
$this->_validate();
$data = array(
'resign' => $this->input->post('resign'),
);
$this->employees->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE, "id" => $this->input->post('id')));
}
Model
function terminate_emp($data)
{
$this->db->where('resign', 0);
$this->db->update('employees', $data);
}
View
function terminate_emp(id)
{
save_method = 'update';
$('#form')[0].reset();
$('.form-group').removeClass('has-error');
$('.help-block').empty();
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('employees_con/ajax_terminate/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
if(data.resign == 1)
{
//$('[name="resign"]').val(data.resign);
$('#resign').prop('checked', true);
}
$('[name="resign"]').val(data.resign);
$('#modal_formterminate').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Terminate Employee'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
<div class="modal fade" id="modal_formterminate" role="dialog">
<div class="modal-dialog modal-full" style="max-width: 600px">
<div class="modal-content">
<div class="modal-header bg-blue-steel bg-font-blue-steel">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title bold uppercase">Person</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div id="empWizard">
<p style="color: #0000cc"><b>Are You sure to Terminate this employee</b></p>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSaveterminate" onclick="save()" class="btn btn-primary">Terminate</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
In controller
$this->employees->update(array('id' => $this->input->post('id')), $data);
You are passing two parameters to update function of your model, one is an array and the other one $data that is also an array.
But In Model,
function terminate_emp($data)
{
$this->db->where('resign', 0);
$this->db->update('employees', $data);
}
you are just accepting one parameter in the update function.
First of all you are making GET request through AJAX and on Controller function ajax_terminate() you are accessing variables using POST. You resign value is not passing through ajax and you are trying to get on controller function ajax_terminate(). See below code:-
function terminate_emp(id)
{
save_method = 'update';
$('#form')[0].reset();
$('.form-group').removeClass('has-error');
$('.help-block').empty();
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('employees_con/ajax_terminate/')?>/",
type: "POST",
dataType: "JSON",
data: {id:id,resign:YOUR_RESIGN_VALUE}
success: function(data)
{
$('[name="id"]').val(data.id);
if(data.resign == 1)
{
//$('[name="resign"]').val(data.resign);
$('#resign').prop('checked', true);
}
$('[name="resign"]').val(data.resign);
$('#modal_formterminate').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Terminate Employee'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
Change Model to
function terminate_emp($where,$data)
{
$this->db->where($where);
$this->db->update('employees', $data);
}
I need to edit the data to db and make it a view on instant and using angular xeditables, but i am unable to pass the data to process.php (to update the db and retrieve back the data)
How can I pass the data using $http.post
Code snippet
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>
<script src="http://code.angularjs.org/1.0.8/angular-mocks.js"></script>
<link href="angular-xeditable-0.1.8/css/xeditable.css" rel="stylesheet">
<script src="angular-xeditable-0.1.8/js/xeditable.js"></script>
<script>
var app = angular.module("app", ["xeditable", "ngMockE2E"]);
app.run(function(editableOptions) {
editableOptions.theme = 'bs3';
});
app.controller('Ctrl', ['$scope','$filter','$http', function($scope, $filter,$http) {
$scope.user = {
name: 'awesome user',
status: 2,
group: 4
};
$scope.statuses = [
{value: 1, text: 'status1'},
{value: 2, text: 'status2'},
{value: 3, text: 'status3'},
{value: 4, text: 'status4'}
];
$scope.groups = [
{value: 1, text: 'user'},
{value: 2, text: 'customer'},
{value: 3, text: 'vip'},
{value: 4, text: 'admin'}
];
$scope.errors = [];
$scope.msgs = [];
$scope.saveUser = function()
{ // $scope.user already updated!
return $http.post('/saveUser', $scope.user).error(function(err) {});
$scope.errors.splice(0, $scope.errors.length); // remove all error messages
$scope.msgs.splice(0, $scope.msgs.length);
$http.post('include/process.php', {'name': $scope.name, 'status': $scope.status, 'group': $scope.group}
).success(function(data, status, headers, config) {
if (data.msg != '')
{
$scope.msgs.push(data.msg);
}
else
{
$scope.errors.push(data.error);
}
}).error(function(data, status) { // called asynchronously if an error occurs
// or server returns response with an error status.
$scope.errors.push(status);
});
};
}]);
app.run(function($httpBackend) {
$httpBackend.whenPOST(/\/saveUser/).respond(function(method, url, data) {
data = angular.fromJson(data);
});
});
</script>
HTML
.....
<div ng-app="app" ng-controller="Ctrl">
<form editable-form name="editableForm" >
<ul>
<li class="err" ng-repeat="error in errors"> {{ error}} </li>
</ul>
<ul>
<li class="info" ng-repeat="msg in msgs"> {{ msg}} </li>
</ul>
<div class="pull-right">
<!-- button to show form -->
<button type="button" class="btn btn-default btn-sm" ng-click="editableForm.$show()" ng-show="!editableForm.$visible"> Edit </button>
<!-- buttons to submit / cancel form -->
<span ng-show="editableForm.$visible">
<button type="submit" class="btn btn-primary btn-sm" ng-disabled="editableForm.$waiting" onaftersave="saveUser()"> Save </button>
<button type="button" class="btn btn-default btn-sm" ng-disabled="editableForm.$waiting" ng-click="editableForm.$cancel()"> Cancel </button>
</span> </div>
<div>
<!-- editable username (text with validation) -->
<span class="title">User name: </span> <span editable-text="user.name" e-id="myid" e-name="name" e-required>{{ user.name || 'empty' }}</span>
</div>
<div>
<!-- editable status (select-local) -->
<span class="title">Status: </span> <span editable-select="user.status" e-name="status" e-ng-options="s.value as s.text for s in statuses"> {{ (statuses | filter:{value: user.status})[0].text || 'Select' }} </span> </div>
<div>
<!-- editable group (select-remote) -->
<span class="title">Group: </span> <span editable-select="user.group" e-name="group" e-ng-options="g.value as g.text for g in groups"> {{ (groups | filter:{value: user.group})[0].text || 'Select' }} </span> </div>
</form>
</div>
....
PROCESS.PHP
<?php
$data = json_decode(file_get_contents("php://input"));
$name = mysql_real_escape_string($data->name);
$status = mysql_real_escape_string($data->status);
$group = mysql_real_escape_string($data->group);
if ($group == 'vip') {
if ($qry_res) {
$arr = array('msg' => "User Created Successfully!!!", 'error' => '');
$jsn = json_encode($arr);
print_r($jsn);
} else {
$arr = array('msg' => "", 'error' => 'Error In inserting record');
$jsn = json_encode($arr);
print_r($jsn);
}
} else {
$arr = array('msg' => "", 'error' => 'User Already exists with same email');
$jsn = json_encode($arr);
print_r($jsn);
}
?>
I don't know if it would be useful to you or someone else.
Afaik, you cannot use http.post with angular to update a database (at least in my case, with php and mysql). You need to use $http() like follows:
var request = $http({
method: "post",
url: "include/process.php",
data: {
name: $scope.name,
status: $scope.status,
group: $scope.group
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});
Then, in PHP, retrieve it like:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
#$name = $request->name;
#$status = $request->status;
#$group = $request->group;
...
?>
With the values at $name, $status and $group you'll be able to update your database.
UPDATE: Your process.php is not called because you have a "return $http.post('/saveUser', $scope.user)" line first in $scope.saveUser = function(), which immediately ends execution of the saveUser function. See return statement in Javascript:
When a return statement is called in a function, the execution of this function is stopped. If specified, a given value is returned to the function caller. If the expression is omitted, undefined is returned instead.