Hi im building laravel app, i have a tables with messages and i want to display the data with datatables. In my index view the data are visible and the sort, pagination e searchbar of datatables work fine, i also added the edit and delete button, i started working on the delete button but i have a route problem.
this my route file web.php
Route::middleware('auth')
->namespace('Admin')
->name('admin.')
->prefix('admin')
->group(function () {
Route::get('/', 'HomeController#index')->name('home');
Route::resource('/user', 'UserController');/* ->except(['edit', 'update']); */
Route::resource('/user/{user:id}/messages', 'MessagesController');
});
Route::get('messages', 'Admin\MessagesController#getMessages')->name('get.messages');
Auth::routes();
the function in the MessagesController who return me the messages in the datatables
public function getMessages()
{
$user = Auth::user();
return DataTables::of(Message::query())
->addColumn('action', function ($message) use ($user) {
return '<i class="glyphicon glyphicon-edit"></i> Modifica
<i class="glyphicon glyphicon-trash"></i> Elimina
';
})
->setRowClass('{{$id % 2 == 0 ? "alert-success" : "alert-danger"}}')
->setRowId(function ($message) {
return $message->id;
})
->setRowAttr(['align' => 'center'])
->make(true);
}
and this is my jquery code for delete the record in the datatables
$('body').on('click', '.deleteMessage', function() {
var id = $(this).data("id");
confirm("Are You sure want to delete this Post!");
$.ajax({
type: "DELETE",
url: "{{ route('admin.messages.destroy', ['user' => auth()->user()->id]) }}/" +
id,
success: function(data) {
table.draw();
},
error: function(data) {
console.log('Error:', data);
}
});
});
i want the code to delete the record i choose in the datatables but i get this error
Illuminate\Routing\Exceptions\UrlGenerationException
Missing required parameters for [Route: admin.messages.destroy] [URI: admin/user/{user}/messages/{message}]. (View: C:\Users\ficus\Desktop\Progetti\ArgostudioADV\resources\views\layouts\app.blade.php)
http://127.0.0.1:8000/admin/user/1/messages
someone can find out how i can build the url in the delete function?
i did the change #aynber suggest to me and its worked, i have the vista with the record now, but now i have another problem, when i press the delete button the pop up show i submit but it give me 405 error and the message still there, but if i reload the page the view give me the successful message of record delete and it disappear in the db too, any clue for this?
it is like the function never go in the success but it delete the record because we call the destroy route
First you need to define the resource route correctly.
resource route
Route::resource('user.messages', MessagesController::class);
message delelte link
<i class="glyphicon glyphicon-trash"></i> Elimina
#js code
$('body').on('click', '.deleteMessage', function() {
var route = $(this).data("route");
confirm("Are You sure want to delete this Post!");
$.ajax({
headers: { 'X-CSRF-TOKEN': "{{csrf_token()}}" },
type: "DELETE",
url: route,
success: function(data) {
table.draw();
},
error: function(data) {
console.log('Error:', data);
}
});
});
Related
I'm trying to create a new service option while creating a bill (a bill can have many services), it's like creating a new tag, or category while writing post without reloading, but i have this internal server error 500, i think the problem is in the Controller because it works fine when i comment the create in controller, route and csrf and stuff are checked, thanks for helping me !
In my javascript :
var max_service_id = {{$max_service_id}};
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("#add_service_button").on("click",function(e){
e.preventDefault();
var service_name = $("input[name=service_name]").val();
var service_category = document.getElementById('service_category').value;
var service_description = $("input[name=service_description]").val();
$.ajax({
type:'POST',
url:'/service/add-in-bill',
dataType: 'json',
data:{
name : service_name,
category_id : service_category,
description : service_description
},
success:function(data){
if (data.message) {
//This is error message
alert(data.message);
}
if (data.success) {
alert(data.success);
var newService = new Option(service_name, max_service_id, false, true);
$('.multipleSelect').append(newService).trigger('change');
max_service_id++;
$("#add_service_div").hide("fast");
}
}
});
})
});
In my controller :
$validator = Validator::make($request->all(), [
'name' => 'required|unique:services',
'category_id' => 'required',
]);
if ($validator->fails()) {
return response()->json(['message'=>$validator->errors()->all()]);
} else {
// It works fine when i comment this, so i think the problem is something about variables from javascript to php stuff
Service::create($request->all());
return response()->json(['success'=>'Create service success !']);
}
//
// I think the problem is in the Controller because it works fine when i comment the "Service::create($request->all());"
I'm trying to make a DOM event where the user clicking a table row's header (th) cell will delete the corresponding row from the database that supplies the table's data.
This code worked as intended framework-less, by just POST'ing an AJAX containing the row's id info from index.php to delete.php which then ran a sql query.
However, after moving the site to Laravel I ran into an error:
POST http://sandbox.app/delete 419 (unknown status)
The JavaScript piece responsible for attaching the delete event and posting the id through AJAX:
function attachDelete() {
$("#mainTable tbody tr th").on("click", function(e){
console.log(e.target.innerText + " was clicked");
var token = $('meta[name="csrf-token"]').attr('content');
var id_to_delete = e.target.innerText;
$.ajax({
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
type: 'POST',
dataType: 'text',
url: 'delete',
data: {
'id_to_delete': id_to_delete,
"_method": 'POST',
"_token": token
},
success: function () {alert("Deleted!"); },
failure: function() {alert("Error!");}
});
});
}
attachDelete();
The console.log(e.target.innerText + " was clicked"); goes off.
However, the success / error messages do not appear.
Going to http://sandbox.app/delete directly brings up a Laravel error window with lots of text, and this part highlighted:
protected function methodNotAllowed(array $others)
{
throw new MethodNotAllowedHttpException($others);
}
I've added the token variables after reading answers to related questions on StackOverflow. This didn't help.
In case it matters, the route:
Route::post('/delete', 'TasksController#delete');
The controller :
class TaskController extends Controller
{
public function delete()
{
include 'config.php';
$stmt = $pdo->prepare('DELETE FROM food WHERE id = :id');
$stmt->execute(['id' => $_POST['id_to_delete']]);
}
}
The code inside delete() used to just be the contents of a delete.php file in the old, framework-less site, where everything worked.
I've tried doing it without the controller by creating a delete.php view (with the same code as the delete() function). It didn't make a difference though:
Route::post('/delete', function () {
return view('delete');
});
Well, it seems if you are communicating with POST at the backend. So, you should be configuring your routes on the api.php instead of web.php
Place your route associated with controller
Route::post('/delete', 'TasksController#delete');
Inside api.php file.
so here is my delete button
<button class="btn btn-danger btn-xs btn-delete delete" value="{{$post->id}}">Delete</button>
then the ajax request
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "DELETE",
url: "{{route('delete_post')}}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
the route
Route::get('delete_post','PostController#getDeletePost');
then the controller:
public function getDeletePost($post_id)
{
$post = Post::where('id', $post_id)->first();
$post->delete();
return redirect()->route('dashboard')->with(['message' => 'Successfully deleted!']);
}
so please help me identfy why nothing really happens when i press the delete button
I have modified you javascript, first issue in your code is,you must either use get request or post request, second issue you are not using named route in order call url for ajax like {{ route() }} , it should be {{ url('path') }} or name your route..
<script type="text/javascript">
$(document).ready(function(){
$('.delete').click(function(){
var id = $(this).val();
alert(id);
$.ajax({
type: "get",
url: "{{ url('/') }}",
data: { id: 1 },
success: function (data) {
console.log(data);
$("#task" + id).remove();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
You are sending a DELETE request type in your Ajax call, which would require a _method parameter with a value of DELETE added to your AJAX data. Your route is a GET route, so that is why you are seeing no action
Another problem is in your blade syntax you are referencing a named route 'delete_post', but that is your URL, not the route name. You have not named the route from what you have posted
Try updating this line in your routes file and that should allow the request to make it to your controller method.
Route::post('delete_post','PostController#getDeletePost')->name('delete_post');
Now you have to change your Ajax request type to
type: "POST"
I have forms with id's formularregister and formularadresa and one button to submit with id comanda.
I want to submit both forms with one button (<a type="submit" id="comanda" class="btn btn-default" onclick="submitForms()">Finalizare comanda</a>) and go back to controller action (zend framework 2) to validate the values from post.
My JS function is this:
function submitForms() {
$(document).ready(function() {
$("#comanda").click(function() {
$.post($("#formularregister").attr("afisarecos.phtml"), $("#formularregister").serialize() + $("#formularadresa").serialize(), function() {
});
});
});
}
You need to make an AJAX request to your controller action. You'll find a lot of examples on the Web, but the most important parts to know for using Ajax in ZF2 are:
Enable ViewJsonStrategy in your /module/Application/config/module.config.php
'view_manager' => array(
// ....
'strategies' => array(
'ViewJsonStrategy',
),
),
Ajax request in your view
$.ajax({
url : 'url/to/yourController/action',
type: 'POST',
dataType: 'json',
data : fromData,
async: true,
success:function(data, textStatus, jqXHR)
{
//success function
}
error : function(xhr, textStatus, errorThrown)
{
// error function
}
});
In your controller action
if ($request->isXmlHttpRequest()) { //ajax call
// your logic here
$jsonModel = new JsonModel(
//...
);
return $jsonModel;
}
Please see this simple example (Code + Demo) for more details.
I am implementing an Ajax call to the server to delete a post from a li. The delete is working fine, but I need to manually get out from the list page and when I get back the list is updated. What I am trying to achieve, is that when the button that deletes the item, also refreshes the list. I added the following code but is not refreshing :(.
function deleteThisPost() {
//alert($('#myPostIDStorage').val())
$.ajax({
type: 'GET',
data: 'myPostIDValue=' + $('#myPostIDStorage').val(),
url: 'http://wander-app.org/deletePosts.php',
timeout: 5000,
success: function (data) {
alert('Post Deleted!');
},
error: function () {
alert('Error Deleting Post');
}
});
return false;
$('#myPost').listview("refresh");
};
Your ajax call works fine as you can see there. You should take a notice that if you return anything from a function it is no longer executed. The code that you provided below $( '#myPost' ).listview( "refresh" ); will be never examined.
What you probably want to do is
function deleteThisPost() {
//alert($('#myPostIDStorage').val())
$.ajax({
type: 'GET',
data: 'myPostIDValue=' + $('#myPostIDStorage').val(),
url: 'http://wander-app.org/deletePosts.php',
timeout: 5000,
success: function (data) {
alert('Post Deleted!');
},
error: function () {
alert('Error Deleting Post');
}
});
$('#myPost').listview("refresh");
return false;
};
According to your question if you want a dialog box with cancel and confirm button you can do
if(confirm('Do you want to delete?') == true) {
alert('Deleted');
}