14

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?

januaryananda
  • 397
  • 1
  • 5
  • 15
  • If you are using dataType : Json. then there is no need to use header function, it will give you json result. you just have to parse or stringify – Monty Feb 09 '16 at 06:12
  • 1
    Side note: headers come **before** body. If your code doesn't crash it's because you've enabled output buffering. – Álvaro González Feb 09 '16 at 08:45

1 Answers1

23

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

ksav
  • 20,015
  • 6
  • 46
  • 66
A.Essam
  • 1,094
  • 8
  • 15