1

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!

4
  • 3
    Use an ajax call to access your rest route. 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 Commented Mar 6, 2017 at 7:51
  • You can send CSRF tokens with your AJAX requests. Read all about it: laravel.com/docs/5.4/csrf#csrf-x-csrf-token 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 Commented Mar 6, 2017 at 8:43

1 Answer 1

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);
})
Sign up to request clarification or add additional context in comments.

11 Comments

in response i get this: Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Could you check if that your_id is existed in your database. Or check your error log for more detail error.
Yes, it exists. I use this construction for tests $.post('/archive/2', but the error is the same
Check my edit also, maybe the problem is you don't have response? Could you check your error_log?
Tell me please where i can check error_log ? I'm new to laravel. If i use Route::get.... and window.location... it works for me , but i need update without refresh the page
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.