最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - How to call Laravel controller function from JavaScript - Stack Overflow

programmeradmin0浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 1

I 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);
})
发布评论

评论列表(0)

  1. 暂无评论