axios response return the whole html rather than data Hi I am new to axios and http request, I am trying to have a get request as below
axios.get('/posts').then(response => console.log(response));
and I have a collection of posts, but on the console I am just getting the whole html.
any idea about that?
and that is my controller
public function index()
{
$posts=Post::all();
return view('posts.index',compact('posts'));
}
and
Route::resource('/posts','PostController');
create another function for ajax call , return only the $posts instead of the view.
public function ajaxcall()
{
$posts=Post::all();
return $posts;
}
this will return only the posts , not the entire view file.
the previous function would return a view file , a whole blade file.....
@AndySong Would you mind explaining how you did the routing for the ajaxcall method? I'm having the same issue right now, but I'm having difficulties making sure the view is loaded along with the the data from the axios call. It's like its only one or the other
@lielvdh - You would need to something like I'll show below. Just switch out the route names and controller methods with what yours are called.
Route::get('posts', 'PostController@index');
Route::get('posts/fetch', 'PostController@fetch');
In your controller
public function index()
{
return view('posts.index');
}
public function fetch()
{
return response()->json(['posts' => Post::all()]);
}
You could also do it all in one function, it just depends on what you think is more readable.
// Your routes
Route::get('posts', 'PostController@index');
// Controller
public function index(Request $request)
{
if ($request->ajax()) {
return response()->json(['posts' => Post::all()]);
}
return view('posts.index');
}
Please sign in or create an account to participate in this conversation.