How i can call controller function using JavaScript !?
Controller:
public function archive($id)
{
$article = Article::find($id);
$article->public = 0;
$article->archive = 1;
$article->save();
}
Route:
Route::post('/archive/{id}', 'HomeController@archive');
I would be grateful for any working options. Thank you!
How i can call controller function using JavaScript !?
Controller:
public function archive($id)
{
$article = Article::find($id);
$article->public = 0;
$article->archive = 1;
$article->save();
}
Route:
Route::post('/archive/{id}', 'HomeController@archive');
I would be grateful for any working options. Thank you!
Share Improve this question asked Mar 6, 2017 at 7:35 user7623256user7623256 4- 3 Use an ajax call to access your rest route. – user4164128 Commented Mar 6, 2017 at 7:36
- if i try to use an ajax call, i get error 405 (Method not allowed). In data i also send csrf_token – user7623256 Commented Mar 6, 2017 at 7:51
- You can send CSRF tokens with your AJAX requests. Read all about it: laravel./docs/5.4/csrf#csrf-x-csrf-token – Arman H Commented Mar 6, 2017 at 8:26
- i send csrf token in request, but in this case nothing happens. I did't get any errors, and function call is not working – user7623256 Commented Mar 6, 2017 at 8:43
1 Answer
Reset to default 1I believe you also need to create response for your controller if you want to access it via api also.
// put this above your class name
use Illuminate\Http\Request;
public function archive(Request $request, $id)
{
$article = Article::find($id);
$article->public = 0;
$article->archive = 1;
$article->save();
return response()->json([
'success' => 'yes',
]);
}
Use jQuery ajax
if you are using jQuery
$.post('/archive/' + {your_id}, function(response) {
// handle your response here
console.log(response);
})