masonite
masonite copied to clipboard
Add is_ajax to request class
Is your feature request related to a problem?
Scope: in Controller
How do I check if a request was made via ajax or not?
The underlying request object from the requests module has a .is_ajax()
Scenario:
I want to make POST requests via ajax from my page.
if the POST requests IS NOT ajax I want to redirect the response otherwise return a json data block.
This provides security and specific availability of responses to only certain types of calls.
example code: Assume this Controller has the following Routes
- GET : SomeController@show
- POST : SomeController@check_data
class SomeController(Controller):
def show(self, view: View):
return view.render("path.to.show.template")
def check_data(self, request: Request, response: Response):
# this stops normal post requests getting some random json data response
# which doen not look good to the end user and increases security to an extent
if not request.is_ajax():
return response.redirect("/")
# create some payload that is to be returned to the ajax call
return {"some": {"data": ["for", "the", "page", "to", "do", "stuff", "with"]}}
What do we currently have to do now?
No ability to access any methods/attributes on the underlying request object that are not wrapped in the Request class
eg is_ajax()
Describe the solution you'd like
Just something simple like an is_ajax() method on the Request class to increase
usage flexibility.
Describe alternatives you've considered
I could check it like this
if request.environ.get('HTTP_X_REQUESTED_WITH'], "") !== 'XMLHttpRequest':
# do redirect
but this feels fragile to me and requires an understanding of the header names and the values assigned to this header attributes
Would this be a breaking change ?
- [ ] Yes
Anything else ?
No response
Will have to check the environ with things like Axios and fetch and see if we can make a method in the request class to check values against the environ