[FIXED] Returning HTML View vs. JSON Object with HTML using Flask & AJAX

Issue

I’m developing a single page Flask app that uses AJAX to navigate a route. For example, when a user clicks a navigation link, using AJAX to invoke a route such as “/profile” he makes a GET request and returns her JSON with HTML to be substituted on screen.

When I type an existing route into the browser without invoking an AJAX request, the HTML is returned as JSON as expected and pasted as text to the screen. I’d like to be able to allow users to load the page by typing the route into the address bar, rather than just pasting the JSON into the HTML. If no AJAX request was made (someone just typed “/profile” into their browser without clicking the profile navigation link), what is the proper way to simply return a view instead of JSON from a Flask endpoint? ?

My first thought is to pass some type of parameter as part of every AJAX request and have the backend check if the parameter exists when called. In this case it returns a view instead of JSON. This is very inefficient and makes your code more complicated by adding more if statements. Additionally, for each route he has to create two HTML files.

What is the proper way to do this?

Solution

If you are making an ajax request, you can add this into your route.

_xhr_key = request.headers.get('X-Requested-With')
if _xhr_key and _xhr_key == 'XMLHttpRequest': # if true this means that its an AJAX call
    #return data for AJAX function
else:
    #return data for regular request
    #render HTML template to the user over here since its a regular request

Ajax Requests make an XMLHttpRequest object
So if XMLHttpRequest object is present in the header then it means that it is an AJAX request. This is how you can load a webpage when a use normally loads it thus, you are able to render page using AJAX and when someone normally types the link in the browser

Answered By – SimbaOG

Answer Checked By – Gilberto Lyons (Easybugfix Admin)

Leave a Reply

(*) Required, Your email will not be published