Laravel: sending data to controller via AJAX without form

I need to send data via JS to a Laravel controller when a button is clicked. I do not use any form because data is created dynamically. Every time I try to send data, I get an internal server error (500), but I can not catch this exception in the controller or laravel.log file.

That's what I'm doing:

Route:

Route::post('section/saveContactItems', ' SectionController@saveContactItems '); 

Controller:

 public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... } 

JS:

 $('button').on("click", function (evt) { evt.preventDefault(); var items = []; var id = $("#id").val(); var languageID = $("#languageID").val(); var data = { id: id, type: type, items: JSON.stringify(items), languageID: languageID }; $.ajax({ url: "/section/saveContactItems", type: "POST", data: data, cache: false, contentType: 'application/json; charset=utf-8', processData: false, success: function (response) { console.log(response); } }); }); 

What am I doing wrong? How can i do this?

UPDATE: Thanks to @ShaktiPhartiyal answer (and @Sanchit help) I was able to solve my problem. In case some other problem arises in a similar problem, after @Shakti's answer, I could not access the data in the controller. Thus, I had to format the data before sending it to the server:

 data: JSON.stringify(data), 
+5
source share
1 answer

You do not need to use

 public function saveContactItems($id, $type, $items, $languageID = "PT"){ ... } 

You should do the following:

 public function saveContactItems() { $id = Input::get('id'); $type = Input::get('type'); $items = Input::get('items'); $languageID = Input::get('languageID'); } 

and yes, since @Sanchit Gupta suggested you send a CSRF token with the request:

Ways to send a CSRF token to AJAX:

 $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); 

If you use this approach, you need to set the meta tag as follows:

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

or

 data: { "_token": "{{ csrf_token() }}", "id": id } 

UPDATE

as @Sanchit Gupta pointed out that the input facade looks like this:

 use Input; 
+5
source

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


All Articles