Laravel 4 Ajax validation to enable XMLHttpRequest (from Magnific Popup)

Using the code from this question ,

@extends('layouts.' . isset($ajax) ? 'ajax' : 'master') 

to check Ajax. It works for regularly loading Ajax pages, but not when using a popup.

In this case, I use Magnific Popup Ajax mode, the request header is XMLHttpRequest, but Laravel returns a non-axial (extended) layout.

+2
ajax php laravel magnific-popup
Nov 23 '13 at 18:41
source share
1 answer

First of all, I don’t know how the $ajax variable ( isset($ajax) ) is set, but the correct way to check the ajax request in Laravel is

 if(Request::ajax()) { // ... } 

Or short form (using a three-dimensional operator in one expression)

 $ajax = Request::ajax() ? true : false; 

So, according to your link of another answer, this should work

 @extends(((Request::ajax()) ? 'layouts.ajax' : 'layouts.master')) 

How it works?

In vendor\laravel\framework\src\Illuminate\Http there is a Request.php class that you can see

 /** * Determine if the request is the result of an AJAX call. * * @return bool */ public function ajax() { return $this->isXmlHttpRequest(); } 

Here isXmlHttpRequest() is an extended method from the Request.php Symphony class, because the Laravel Request class extends Symfony\Component\HttpFoundation\Request.php , and there is a main method in this class that defines the ajax request

 public function isXmlHttpRequest() { return 'XMLHttpRequest' == $this->headers->get('X-Requested-With'); } 

So, if an X-Requested-With request header is given, then it is an ajax request and if this header is not sent, then this is not an ajax request. So, the question is how isset($ajax) installed, and if it is installed by you, then the jQuery library that you use does not do this, but sends the X-Requested-With request header instead, in which case you should use Laravel Request::ajax() to determine the ajax request.

By the way, I would prefer to use a completely different view request for ajax , which does not extend the master layout. You may like Ajax-Request-Php Detection and Framework .

+9
Nov 23 '13 at 20:39
source



All Articles