Browser Displays Ajax Response On Back Button with Vue

The Problem

Do you see a json ajax response instead of the page you were expecting when hitting the back button?

This can happen if you use the the same routes for your html and ajax like so.

public function index(){
    if($request->ajax()){ // do ajax things };
    // do other things 
}

The problem is that the browser (depending on the browser) decides to cache data that is passed over the same route.

The Fix

The solution is to differentiate the route. Craig from Sitepoint explains this well.

Ensure your page and data URLs are never the same. When navigating to http://myapp.com/list/?search=bob&page=42, the Ajax call should use a different URL: it can be as simple as http://myapp.com/list/?search=bob&page=42&ajax=1. This ensures Chrome can cache both the HTML and JSON requests separately, but JSON is never presented, because the Ajax URL never appears within the browser address bar.

Craig Buckler https://www.sitepoint.com/solve-caching-conundrums/

This can be as simple as setting the following on your GET requests.

axios.get(url, {params: {ajax: 1}})

Leave a Comment