bcosca / fatfree

A powerful yet easy-to-use PHP micro-framework designed to help you build dynamic and robust Web applications - fast!

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Ajax / Fetch API

AndrewMarkUK opened this issue · comments

I am testing using AJAX and Routes. I have a route set like so.

$f3->route('GET /example [ajax]','ExampleController->test')

For the purpose of testing the controller simply outputs 'Received' (php echo function).

If I use jquery ajax like the following (only a basic setup here) the Hive [AJAX] variable shows as 1 (true, and the controller can therefore determine it was an AJAX request..

$.ajax({
url:'/example,
dataType:'text',
success:function(response){
console.log(response)
}
})

However, if I use Fetch API (so I can remove the jquery library), like so (again, just a basic example).

fetch('/example')
.then(response => response.json())
.then(data => console.log(data));

The Hive [AJAX] variable is empty.

I am assuming that either my basic Fetch example requires another element (an AJX header??) OR testing for an AJAX request on the controller will not work when sent with Fetch API?

My aim really is to remove the requirement for jQuery/AJAX and instead use the Fetch API...is there a way of doing such?

Hints, tips, examples...or a simple yes or no, all gratefully received.

Thank you!

Hello,
In order for the framework to understand the request was made asynchronously, you need to set the X-Requested-With header.

fetch('/example', {headers: {'X-Requested-With': 'XMLHttpRequest'}}) .then(response => response.json()) .then(data => console.log(data));

All the [ajax] flag on your route does is check if the request was sent with this header.

It does look weird, and it's erroneous (the fetch API doesn't use XMLHttpRequest as far as I'm aware), but as of now, this is the closest to a standard way to indicate a request was done asynchronously.

You'll notice that this issue isn't specific to the Fat-Free framework, but is shared in various ways across most PHP frameworks.

Hi

Thanks for this pointer and yep, I understood it was not a FF issue but more about how the request sent, which is what I couldn't figure, although it would seem some (additional) header was required.

I took for granted that given I was using Fetch, it would have (built in) the XMLHttpRequest header and so yes, I agree...it is a little weird.

A massive thank you for this tip...really appreciated!