Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

401
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda