Using `header (" Content-type: application / json ");`

I just created a jQuery ajax function to extract some json-encoded data from PHP , here is 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 arises: when I delete the header("Content-type:application/json"); line header("Content-type:application/json"); in data.php , console.log says that the data type returned by ajax is string .

And when I added dataType : json,, inside ajax in bank.php , the type changes to object

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

+6
source share
1 answer

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

When you use this function, you will see the http Content-Type:application/json header in the response sent from the server. If you are not using it, the server will send a default value, which is most likely Content-type:text/html; charset=UTF-8 Content-type:text/html; charset=UTF-8

Since @Monty stated that you do not need this function if you added dataType: 'json' to your AJAX, since Jquery will process the data even if it is sent with the text / html header.

See also: jQuery AJAX PHP Script Call with JSON Return

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

+7
source

All Articles