Laravel angularjs Request :: ajax () is always false

I am building an application with angularjs and laravel 4. Everything is fine, but now I only need to allow XHR requests.

This is what I have at the beginning of my controller. But this statement is always incorrect.

if (!\Request::ajax()) { return Response::json(array('halt'=>Request::ajax())); }; 

In angular, I am using the standard $ http service.

 angular.module('APP') .factory("API", ($http,$q,appClient,apiURL) -> class FB constructor:-> this.deferredData = $q.defer(); info: (reload)-> $http( method: "get" url: apiURL+'game/'+appClient+"/info" ).success((res)-> dostuff() ) 
+26
angularjs ajax php coffeescript laravel-4
Dec 09 '13 at 16:22
source share
3 answers

When making AJAX calls, the X-Requested-With header is often set to XMLHttpRequest . The Laravel Request::ajax() method is built on top of the Symfony2 method, which simply checks for the presence of this header.

In October 2012, Angular.js removed this header because it felt that it was rarely used.

Like @Thrustmaster and you mentioned in the comments, you need to install:

 $httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest" 
+35
Jul 25 '14 at 4:05
source share
— -

If you prefer not to modify the external angular application (or you cannot) and rather change your Laravel code to distinguish between angular JS AJAX requests and other requests, you can also use Request::wantsJson() :

 if(Request::wantsJson()) { // Client wants JSON returned } else { // Client does not want JSON returned } 

The wantsJson method wantsJson based on the standard Accepts HTTP header (and not on the non-standard X-Requested-With header) for application/json . As long as angular JS leaves this by default, and you don't delete it on purpose, this method should be reliable.

+21
Feb 19 '15 at 12:29
source share

For beginners, AngularJs is looking for where to add $httpProvider.defaults.headers.common["X-Requested-With"] = "XMLHttpRequest"

Here is an example:

 var angularApp = angular .module('angularApp', [ 'ngResource', ]) .config(['$httpProvider', function($httpProvider) { $httpProvider.defaults.headers.common["X-Requested-With"] = 'XMLHttpRequest'; }]); 
+13
Jul 10 '15 at 2:23
source share



All Articles