Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

AndySong's avatar

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?

0 likes
6 replies
AndySong's avatar

and that is my controller

 public function index()
    {
        $posts=Post::all();
        return view('posts.index',compact('posts'));
    }

and

Route::resource('/posts','PostController');

MaverickChan's avatar

create another function for ajax call , return only the $posts instead of the view.

MaverickChan's avatar
Level 47
 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.....

LielvdH's avatar

@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

rawilk's avatar

@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');
}
1 like

Please or to participate in this conversation.