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.
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 designing CI application and is stuck in ajax query. Basically the function which i have written is taking id as null when save button is pressed even though when i click on edit button it shows its picking up the correct id. Looks like I have some error in function. BELOW IS THE FUNCTION WHICH i HAVE WRITTEN :
public function ajax_update()
{
$this->_validate();
$data = array(
//'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
//'gender' => $this->input->post('gender'),
//'address' => $this->input->post('address'),
//'dob' => $this->input->post('dob'),
//'tid' => $this->input->post('tid'),
'name' => $this->input->post('tname'),
);
$this->transport->update(array('tid' => $this->input->post('tid')), $data);
var_dump( $this->input->post());
echo json_encode(array("status" => TRUE));
}
the update function is
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
View is
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><html lang="en">
<head>
<?php include_once("header.php"); ?>
</head>
<body class="fixed-nav sticky-footer bg-dark">
<!-- Navigation-->
<?php include_once("sidebar.php"); ?>
<div>
<div class="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
Home
</li>
<li class="breadcrumb-item active">Manage Transport</li>
</ol>
<!--Button to add Client
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal2"><i class="fa fa-plus" style="color:white"></i> Add Transport</button>-->
<button class="btn btn-success" onclick="add_transport()"><i class="glyphicon glyphicon-plus"></i> Add Transport</button>
<br>
<br>
<!-- Example DataTables Card-->
<div class="card mb-3">
<div class="card-header">
<i class="fa fa-table"></i> View Transport Details</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th style="width:90%;">Transport Detail</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Transport Detail</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid-->
<!-- /.content-wrapper-->
</div>
<!-- Modal to add Transport-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Transport Details</h4>
<button type="button" class="close" data-dismiss="modal">x</button>
</div>
<div class="modal-body">
<!--<form role="form" name="form1" action="<?php echo base_url('search/add_trans'); ?>" method="post" autocomplete="on">-->
<form action="#" id="form" class="form-horizontal">
<div class="row">
<div class="col-md-2">
<label>Transport Details</label>
</div>
<div class="col-md-10" id="new_data">
<textarea name="tname" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<!--<input type="submit" name="submit" class="btn btn-primary" value="Submit">-->
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal Finishes-->
</div>
<?php include_once 'footer.php'; ?>
<script type="text/javascript">
var save_method; //for save method string
var table;
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
function add_transport()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#myModal').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Transport'); // Set Title to Bootstrap modal title
}
function edit_transport(id)
{
//var table = $('#dataTable').DataTable();
// console.log( table.row( id ).data() );
// $("#tid").val(data.tname);
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('transport/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
// $('[name="id"]').val(data.id);
//$('[name="tid"]').val(data.tid);
$('[name="tname"]').val(data.tname);
// $('[name="firstName"]').val(data.firstName);
//$("#tid").val(data.tname);
//alert(data.tname);
// $('[name="lastName"]').val(data.lastName);
// $('[name="gender"]').val(data.gender);
// $('[name="address"]').val(data.address);
// $('[name="dob"]').datepicker('update',data.dob);
// $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('#myModal').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Transport'); // Set title to Bootstrap modal title
// new_data
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> <input type="text" name="row_id" value="'+id+'" readonly hidden >');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
//function reload_table()
//{
// table.ajax.reload(null,false); //reload datatable ajax
//}
function reload_table() {
table.api().ajax.reload(null, false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('transport/ajax_add')?>";
} else {
url = "<?php echo site_url('transport/ajax_update')?>";
}
// console.log($('#form').serialize());
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#myModal').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> ');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>');
}
});
}
function delete_transport(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('transport/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#myModal').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
function reload_table()
{
//console.log(table);
table.api().ajax.reload( null, false );
}
$(document).ready(function() {
//datatables
table = $('#dataTable').dataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('transport/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
</script>
</body>
</html>
Any pointers please ?
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'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.