vaughan-ilogic
vaughan-ilogic

Reputation: 287

Custom PHP "API" JSON response jQuery

Im not quite sure how to explain this but im experimenting with creating my own API. At the moment things are working quite well by doing cURL requests or jQuery AJAX requests.

My problem is I see using other APIs that you specify you want a JSON response in the arguments root of the jQuery object. With my API I have to specify I want a JSON response in the data argument. How exactly are APIs picking up this JSON argument? Example:

$.ajax({
    url: 'url',
    type: 'POST',
    data: {dataType : 'json'}, //I need this for PHP to know I want a JSON response
    dataType: 'json' //how do other APIs grab this on the API side?
}).
done(function(response){
    console.log(response);
});

In PHP I can only pickup the data object VIA $_POST. If I remove the data object from the AJAX request I dont get data back. So what should I do in PHP to pickup the "root" dataType argument to know to return JSON?

<?php echo serialize($_POST) ?>

Upvotes: 0

Views: 146

Answers (1)

chrisguitarguy
chrisguitarguy

Reputation: 2369

When you set dataType, jQuery sends that info as part of the Accept header, it probably looks something like this: Accept: application/json, text/javascript, */*; q=0.01.

On the PHP side of things, you can access it with the $_SERVER superglobal:

$accept = isset($_SERVER['HTTP_ACCEPT']) ? $_SERVER['HTTP_ACCEPT'] : null;
if ($accept && false !== stripos($accept, 'application/json')) {
    // send back JSON
}

If you happen to be using Symfony's HttpFoundation component, it has some nice facilities to deal with Accept headers:

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\AcceptHeader;

$r = Request::createFromGlobals();
$accept = AcceptHeader::fromString($r->headers->get('Accept') ?: '*/*');
if ($accept->has('application/json')) {
    // send json
} elseif ($accept->has('application/xml')) {
    // send xml
} else {
    // send whatever
}

Upvotes: 2

Related Questions