Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

407
Views
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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The function header("Content-type:application/json") sends the http json header to the browser to inform him what the kind of a data he 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

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!