Sawad Sawad - 1 month ago 14
Ajax Question

Unable to pass ajax to controller function

I am trying to update my database using ajax in laravel. When i click the button (toggle button) it should update the database enable column from 1 to 0.

Here is the script written in the view

$(".toggle-btn").change(function() {
var id = $(this).attr('name'); // $(this) refers to button that was clicked

$.ajax({
url: '/adminpanel/dviulaan/stt',
method: "post",
data: {'id' : id} ,
dataType: "json",

});
});


Here is my route

Route::post('adminpanel/dviulaan/stt', 'AdminDvAnnouncement@status');


And here is the controller function

public function status()
{
$id = Input::all();

if (Request::ajax()) {
DvAnnouncement::where('announcement_id', $id)->update(
[
'enable' => '0',
'user_updated' => Auth::user()->id,
'updated_at' => new DateTime,
]);
}

$response = array(
'status' => 'success',
'msg' => 'Option created successfully',
);

return Response::json( $response );

}


When i click the button it shows the following error in the consol

POST http://localhost/adminpanel/dviulaan/stt 500 (Internal Server Error)


Please help me to find the error.

I have even changed the controller method as below

public function status(Request $request)
{
$id = Input::get('id');

if (Request::ajax()) {
DvAnnouncement::where('announcement_id', $id)->update(
[
'enable' => '0',
'user_updated' => Auth::user()->id,
'updated_at' => new DateTime,
]);
}

$response = array(
'status' => 'success',
'msg' => 'Option created successfully',
);

return Response::json( $response );

}

Answer

$id = Input::all(); => $id = Input::get('id');

UPD after logs

include in head

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

then change in function

$(".toggle-btn").change(function() {
  var id = $(this).attr('name'); // $(this) refers to button that was clicked

  $.ajax({
    url: '/adminpanel/dviulaan/stt',
    method: "post",
    data: {'id' : id, '_token': $('meta[name="csrf-token"]').attr('content')} ,
    dataType: "json",

  });
});
Comments