Laravel: weird behavior when I try to execute ajax and non-ajax request on the same route (caching)

I registered a GET route for laravel.dev/test . The appropriate route controller will distinguish whether the request is ajax or not.

When I type laravel.dev/test in the browser, Laravel discovers that it is not an ajax request and uses return View::make() to create the page. Then the Backbone.js code on the page makes an ajax request for laravel.dev/test , and Laravel uses return Response::json to return JSON.

Everything is fine until I try to navigate from the page and then use the browser button to return to laravel.dev/test so that it prints json as an answer, which I don't expect since I'm not making an ajax request .

+4
source share
3 answers

Definitely a caching issue. To try and get some results, add this to your controller (ajax and non-ajax) to force caching to be disabled:

 header("Cache-Control: no-cache, must-revalidate"); // HTTP/1.1 header("Expires: Sat, 26 Jul 1997 05:00:00 GMT"); // Date in the past 

And see if the chrome will still be retrieved from the cache on the back.

+1
source

This is not a laravel or spine, but a chrome issue ! Check it out too .

The solution that worked for me is to put

 return Response::json($this->data)->header("Vary", "Accept"); 

Good luck

+2
source

This is in Laravel 5.1, but the principle should work for all previous versions.

The way I handled this was with two routes pointing to the same method, but with one end in the .json extension:

 get('items', ['as' => 'items', 'uses' => ' ItemsController@index ']); get('items.json', ['as' => 'items', 'uses' => ' ItemsController@index ']); 

Then inside my index() method:

 $data = []; // your collection if ($this->request->ajax()) { return response()->json($data); // replace with actual JSON data } return view('items.index', compact('data')); 

This allows you to use a dedicated URL for JSON responses, uses the same method and data, and never interferes with my return button.

+1
source

Source: https://habr.com/ru/post/1489893/


All Articles