Lars-Janssen's avatar

On page back I only see JSON

Hi,

I've got a controller method:

public function index()
{
    if (request()->ajax()) {
        // Here I have a long query.....
        
        return request()->page ? $query->paginate(15) : $query->get();
    }
    
    return view('ads.ads');
}

So when the request is ajax I return json, otherwise I return a view. But when I want to visit the previous page I see a white page with only json, instead of the view!

How do I fix that?

Thanks!

0 likes
4 replies
click's avatar

I also had this once, I solved it by always apending ?json or &json to all of my ajax requests with the use of an interceptor so it is done automatically. This prevents the browser returning you the wrong cached page when you click 'back'.

But I suppose there is a more elegant solution to the problem. But this was a quick fix that worked for me and I never looked for another solution.

bwrice's avatar

Have you tried the 'expectsJson' method instead?

request()->expectsJson()
click's avatar
click
Best Answer
Level 35

@Lars-Janssen I've used it in a project with vue-resource (an ajax helper for vue which is abandoned now). I don't know what you are using but the axios library also has intercepters so the idea would be the same I guess.

Vue.http.interceptors.push(function (request, next) {
    // prepend request url with a parameter to prevent caching issues
    let glue = request.url.indexOf('?') === -1 ? '?' : '&';
    request.url = request.url + glue + 'json';
});

More about vue-resource interceptors: https://github.com/pagekit/vue-resource/blob/master/docs/http.md#interceptors

Axios interceptors: https://github.com/axios/axios#interceptors

update the axios version:

axios.interceptors.request.use(function (config) {
        let glue = config.url.indexOf('?') === -1 ? '?' : '&';
        config.url = config.url + glue + 'json';
        return config;
    },
    function (error) {
        return Promise.reject(error)
    }
);
1 like

Please or to participate in this conversation.