Skip to content
Advertisement

The usage of `header(“Content-type:application/json”);`

I just created an JQuery ajax function to retrieve some json-encoded data from PHP, here’s my code :

file name : bank.php

$('form').on('submit', function(){

        var datatobesent  = $(this).serialize();
        $.ajax({
            data: datatobesent,
            url:'data.php',
            type:'GET'
        })
        .done(function(data){
            console.log(typeof(data));
        });
        return false;
})

and in data.php I wrote

if(isset($_GET)){
    $data = $_GET;
    echo json_encode($data);
    header("Content-type:application/json");
}

the question is, when I delete the line of header("Content-type:application/json"); in data.php the console.log tell that the type of data returned by ajax is string.

And when I added dataType :json“ inside the ajax function in bank.php the type changes into object

so what is the function of header("Content-type:application/json"); actually?

Advertisement

Answer

The function header("Content-type:application/json") sends the http json header to the browser to inform it what kind of data it expects. You can see all the http headers for each request in your browser (If you are using chrome open developer tools, go to network, adjust the view and reload the page, you will see all requests made by your browser, if you click on any on any of these requests then click on headers you will see the headers of each request).

When you use this function you will notice the http header Content-Type:application/json in the response sent from the server. If you don’t use it the server will send the default which most likely is Content-type:text/html; charset=UTF-8

As @Monty stated you don’t need this function if you added dataType: 'json' to your AJAX as Jquery will handle the data even it is sent with text/html header.

See Also: jQuery AJAX Call to PHP Script with JSON Return

To read more about headers : http-headers-for-dummies

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement