0

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) ?>
1
  • If I remove the data object from the AJAX request I dont get data back - $_POST carries the data you need. So if you remove it how can you get the data ? Commented Feb 8, 2014 at 16:16

1 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.