Jump to content

Detecting an ajax call from AngularJS


adrian
 Share

Recommended Posts

Just a bit of a head's up in case it useful for you guys. I discovered this when I installed Tracy on a live site which makes heavy use of Angular with ajax calls to get data from the PW backend.

Tracy was breaking the site because the returned JSON response had the Tracy debugger bar code appended. 

The thing is I don't really think this is a Tracy bug. Have a read here:

https://laracasts.com/discuss/channels/requests/laravel-5-doesnt-behave-to-angularjs-like-ajax-request

Angular decided to remove the AJAX header.

I feel like this might also affect those of you using if($config->ajax) checks. The fix is pretty easy - just add the headers like this:

.controller('HealthController', ['$scope', '$sce', '$http', function($scope, $sce, $http) {

    //to allow Tracy to know it's an ajax call and therefore not add code to call
   $http.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest";

   $http.get("/data/health-data.php?rc=" + document.getElementById("rc").getAttribute("data-name"))
   .success(function (response) {

I have also posted an issue for the Tracy guys: https://github.com/nette/tracy/issues/167 but I am not sure whether they can do anything about this, or even if they should try. The same goes for PW and its $config->ajax check.

Hope that's helpful to someone!

  • Like 1
Link to comment
Share on other sites

AFAIK this header was only popularized by jquery and never part of any standard, therefore there are a lot of javascript tools out there, which do not automatically set this header. 

Very good point - I don't think I ever realized this. It doesn't look like there is anyway to detect an AJAX call without this header being sent, or by perhaps sending a get/post variable that you can manually check.

Kinda makes it a bit of pain if you're not using something like jquery. So it looks like if you want to use PW's $config->ajax, or you have TracyDebugger running, you'll need to make sure that header is sent. DG from the Tracy core has asked me to write something for their Readme along these lines. Perhaps PW should also have a note in the $config->ajax section?

Link to comment
Share on other sites

True, this might be a good addition to the docs. And I'd think it's probably a good thing that ajax calls are not distinguishable by default from other request, as both are simply requests for a web resource. Any differentiation should be triggered by the specific request and not by the method of triggering it. 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...