Submit request using jQuery and Laravel

I need to get data from jQuery post request, I think there is some error with routes or controller, here is my javascript request code:

$.post('http://localhost:8000/ajax', { task: "comment_insert", userID: _userID, comment: _comment, name: _name, userName: _userName } ).error( function(data) { alert("Error: "+ data); } ) .success( function( data ) { comment_insert(jQuery.parseJSON( data )); console.log("RESPOND TEXT:" + data); } ); } 

There are also my routes for the Laravel framework:

 Route::post('ajax', ' AjaxController@index '); 

Controller:

 class AjaxController extends Controller { /** * Display a listing of the resource. * * @return Response */ public function __construct() { $this->middleware('guest'); } public function index() { return view('ajax.ajax'); } } 

my ajax.PHP script is in /resource/views/ajax/ajax.php Also, if I put the script in /public/ajax/ajax.php everything works fine .... I am using Laravel 5 ... Please help

EDIT:

I found that the problem, but I do not know how to solve it.

When I disable csrf protection from: working with kernel.php kernel code, does anyone know how to enable csrf protection code?

+6
source share
2 answers

UPDATE: The problem is that the new CSRF protection does not work with ajax requests. Here is what you could do:

In your wizard template add a new meta tag with the current token like this

  <meta name="csrf-token" content="{{ Session::token() }}"> 

Then, when sending your ajax call, you add the token as follows:

 $.post('http://localhost:8000/ajax', { '_token': $('meta[name=csrf-token]').attr('content'), task: 'comment_insert', userID: _userID, comment: _comment, name: _name, userName: _userName }) .error( ... ) .success( ... ); } 
+10
source

It is simple javascript code to send GET, POST, PUT, DELETE methods

declare a title: <meta name="csrf-token" content="{{ Session::token() }}">

  function addCarrito(Urldir,paramt) { $(function(){ $.post(Urldir,{ _token: $('meta[name=csrf-token]').attr('content'), _method : 'PUT', data : }, function(response){ if(response != '') { console.log('good'); } }); }); } 
0
source

Source: https://habr.com/ru/post/982148/


All Articles