0

I'm making an Ajax call from a default Blade layout, shared by all the pages. The Ajax call is handled in AjaxController and the controller needs to know "what" is calling it.

Normally, I would do the following to check the current route:

$request->route()->getActionName(); // => e.g. "AjaxController@index"

But how do I retrieve the action name of a page from which the ajax call was made? So:

  1. Ajax call is made from page A to controller X
  2. Controller X checks what the route name of page A is

In the end, I can always pass the caller route name with the Ajax call, but I'm wondering if there's a way to know the caller from within the AjaxController.

lesssugar
  • 15,486
  • 18
  • 65
  • 115
  • unless you can add some way of indentification to `your client?` you cannot, except for maybe the source IP, but not the url from which the call was made, because there does not have to be any. Try for yourself in postman. – online Thomas Jan 12 '17 at 10:21
  • or I lied and you can try this: http://stackoverflow.com/questions/26754129/jquery-ajax-referer-url – online Thomas Jan 12 '17 at 10:35
  • @Thomas Thanks for the effort. Sure I can use the referer property but this would give me a URI. What I would prefer is the name of the route action in Laravel, which would be less problematic to handle or parse. Route actions are unique, URI-s can be tricky. – lesssugar Jan 12 '17 at 10:41
  • I understand, but ajax is client sided, so why should the client be aware of the route action etc? You can write your js in a way it tells the current page and make some kind of dictionary with routes and controllers like in routes/api & routes/web, but you can't *trust* this route from the client of course! – online Thomas Jan 12 '17 at 10:44
  • Your best bet would be to pass the current action name through the URL you're calling, by outputting it in your view and then accessing it on the server side by checking this URL: `https://yourdomain.com/ajax-url?action={{ urlencode(request()->route()->getActionName()) }}` and `request()->get('action');` – Jonathon Jan 12 '17 at 12:23
  • @Jonathon Yep, that's what I'm currently doing. Leaving the post in case someone finds a way to get the referer action name via `Request ` or `Router` in the future. – lesssugar Jan 12 '17 at 12:44
  • Yeah, with it being client side, you'll essentially have to pass the data yourself. The only other option would be to try and take the URI from the referer and attempt to kind of look up the route backwards, which I'm sure will be possible somehow – Jonathon Jan 12 '17 at 13:03

0 Answers0