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),
source share