Laravel 5 Ajax Post route - laravel

This is my first attempt to use ajax to Post instead of Get. I get a 200 response as if it were working but the function in the controller is never being run.
I used this same concept in my ajax Get requests and they work fine but the Post is not working as expected and sortable('serialize') creates a Post variable so I need to use Post.
The alert in the success: function always runs as if it were successful but the controller function is never hit (I have it making a simple database change just to verify if it is running).
Ajax:
$(function() {
$('[id^="sortable_"]').sortable(
{
connectWith: '.sortable-line-item-list-5',
update : function (event, ui)
{
var items = $(this).sortable('serialize');
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
},
success: function()
{
alert('looks like it is working...');
},
});
}
});
$( '[id^="sortable_"]' ).disableSelection();
});
Route:
Route::post('api/sort_order_item', ['as' => 'api/sort_order_item', 'uses' =>'ApiController#SortOrderItem']);
Controller:
public function SortOrderItem()
{
$this_item = \pmms\Checklist_template_line_item::findOrFail(20);
$this_item->list_position = 1;
$this_item->save();
}

I think your problem is csrf_token,
Put this line in your blade page head section:
<meta name="csrf-token" content="{{ csrf_token() }}" />
then, update your ajax code like this :
$.ajax({
type: 'post',
url: '/api/sort_order_item',
data: {
'items': items,
'_token': $('meta[name="csrf-token"]').attr('content'),
},
success: function()
{
alert('looks like it is working...');
},
});
Let me know if it helps you

Related

Laravel 8 Method Not Allowed 405 Ajax CRUD

I fixed my csrf
I fixed my route , route clear too
but still error show up .
I'm doing ajax form in modal :
My Route
Route::post('increp/store',[\App\Http\Controllers\IncrepController::class,'store'])->name('increp.store');
My ajax
// Create article Ajax request.
$('#submit_increp').click(function(e) {
e.preventDefault();
var data = $("#main-form").serialize();
$.ajax({
url: "{{ route('increp.store') }}",
type: 'POST',
data: data,
dataType: 'json',
beforeSend:function(){
$(document).find('span.error-text').text('');
},
success: function(result) {
if(result.errors) {
console.log(result.errors);
$('.alert-danger').html('');
$.each(result.errors, function(key, val) {
$('span.'+key+'_error').text(val[0]);
});
} else {
$('.alert-danger').hide();
$('.alert-success').show();
}
}
});
});
I doing this for days, i dont have idea how to fix this errors .
Network tab
Console tab

Error 405 (method not allowed) using ajax method post laravel

There is an ajax script to remove comments under posts. When I click the delete button, I get a 405 error.
The console displays this: DELETE http://127.0.0.1:8000/id2/post/582 405 (Method Not Allowed), although the method is different url
My route Route::delete('/id{id}/post/{postId}/comment/{commentId}/delete', 'CommentController#deleteComment')->name('deleteComment');
And script
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e){
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "DELETE",
data: {_token: token, id: id},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});
I need that when I press delete, the record disappears, but it does not disappear. To make the entry disappear, you need to reload the page
Under the hood Laravel actually uses POST request within an _method as parameter when you perform destroy operation, so your JavaScript section should looks like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function () {
$("body").on("click","#deleteComment",function(e) {
e.preventDefault();
var id = $(this).data('id');
var token = $("meta[name='csrf-token']").attr("content");
$.ajax({
url: "{{route('deleteComment', ['id' => $user->id, 'postId' => $post->id, 'commentId' => $comment->id])}}",
type: "POST",
data: {_token: token, id: id, _method: 'DELETE'},
success: function() {
$("div.commentPost[data-id="+id+"]").remove();
},
});
});
});

How to insert data in the database using ajax in laravel?

I'm working on a simple web application in the laravel framework. I have blade, controller and model files and I want to insert the data into the database with the help of ajax. But, I'm not able to insert the data. Below is the code:
Thanks.
<script>
$(document).ready(function(){
$("#button").on("click", function(){
var name=$("#name").val();
var email=$("#email").val();
$.ajax({
url:'insert.php',
method:'POST',
data:{
name:name,
email:email,
},
success:function(data){
alert(data);
}
});
});
});
</script>
There are so many issue with your code:
url:'insert.php', // here you are not working in core php so url is not passed in this way
it will be like:
url:'{{ url("/insert") }}', // This 'insert' will be a route and that will be mapped to a controller function.
And if you are using:
method:'POST',
then you have to set the csrf token like:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
or
headers: {
'X-CSRF-TOKEN': '{{ csrf_token() }}'
}
Resolve the above issues and try again.
at least, you have to call in your script.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
Because it is POST request, your csrf_token is required.

Laravel 5.2 - method [ajax] does not exist

I've been trying to create an upload page for a webapplication. For sending the files to the server I want to use AJAX, as I've been using AJAX GETs for the whole front-end.
My problem is that when trying to use POST, under the circumstances I will provide you with in a moment, I get the error message 'Method [ajax] does not exist'.
My route (the POST one):
Route::group(['prefix' => 'organisatie', 'middleware' => ['web', 'auth', 'ajax'], 'namespace' => 'Organisatie'], function()
{
Route::group(['prefix' => '{organisatie}/documenten'], function ()
{
Route::get('/', 'DriveController#index')->name('drive.index');
Route::post('/upload', 'DriveController#upload')->name('drive.upload');
});
});
The route would come down to organisatie/{organisatie_id}/documenten/upload.
My DriveController#upload:
public function upload(Request $request)
{
$file = $request->file('file[]');
return response()->json($file);
}
My AJAX code:
var formData = new FormData();
utility.foreach(upload.fileArray.array, function (file) {
formData.append('file[]', file);
});
var ajax = {
url: '/organisatie/1/documenten/upload',
type: 'POST',
data: formData,
dataType: 'JSON',
processData: false,
success: function (data) {
console.log(data);
}
};
$.ajax(ajax);
Note:
utility.foreach is my own foreach implementation, and it does just
that.
upload.fileArray is an array wrapper I defined and it works as
expected.
Populating the upload.fileArray works fine and is tested. It's populated from an input[type=file] (multiple)'s FileList.
Any and all help is appreciated. Please ask if anything is unclear.
Thanks for the help. Neat's answer inspired me to check my Route set up, and it appeared that you should still use ?ajax=functionName on POST routes. In my case:
Route:
Route::post('/', 'DriveController#index')->name('drive.upload.post');
AJAX:
var ajax = {
url: '/organisatie/1/documenten?ajax=upload', <--- '/upload' to '?ajax=upload'
type: 'POST',
data: formData,
dataType: 'JSON',
processData: false,
success: function (data) {
console.log(data);
}
};
with DriveController#upload -> DriveController#ajaxUpload
For some reason I couldn't find this answer anywhere, so I hope this helps someone.

Laravel - DELETE Ajax request

I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection

Resources