Current Location: Home> Latest Articles> Setting up JSON response header with AJAX calls

Setting up JSON response header with AJAX calls

M66 2025-05-18

How to set the JSON response header with the header function and return data with the AJAX call?

In web development, it is often necessary to handle asynchronous request data interaction with the front-end, especially when data is returned when using AJAX calls. To ensure that the browser can correctly process the returned data format, we need to set the correct response header information. If we want the data we return is in JSON format, PHP provides the header() function to set the HTTP response header. This article will explain how to use the header() function to set up the JSON response header and return JSON data with AJAX.

Setting up JSON response header

To return JSON format data to the client, first make sure that Content-Type is correctly set to application/json in the HTTP response header. This way the browser will know that it will receive data in JSON format, not HTML or other formats.

 <?php
// Set the response header,Specify the return data type as JSON
header('Content-Type: application/json');

// Create an associative array,Indicates the data to be returned
$response = array(
    'status' => 'success',
    'message' => 'Data has been successfully processed.'
);

// use json_encode() Function converts array to JSON Format
echo json_encode($response);
?>

Combined with AJAX calls

When the correct JSON response header is set, the returned JSON data can be obtained through the AJAX call. Suppose the front-end uses JavaScript's fetch() function or jQuery's $.ajax() to send requests and receive data. Here is an example of sending a request using fetch() and processing a JSON response:

Send AJAX request using fetch()

 fetch('http://m66.net/api/data.php', {
    method: 'GET'
})
.then(response => response.json()) // Analysis JSON data
.then(data => {
    console.log(data);  // 在控制台输出返回的data
})
.catch(error => console.error('Error:', error));

Send request using jQuery's $.ajax()

 $.ajax({
    url: 'http://m66.net/api/data.php',
    type: 'GET',
    dataType: 'json',  // 指定返回的data类型为 JSON
    success: function(data) {
        console.log(data);  // 在控制台输出返回的data
    },
    error: function(xhr, status, error) {
        console.error('Error:', error);
    }
});

Complete example

Here is a complete PHP and AJAX example showing how to set up the JSON response header using the header() function and get data through AJAX on the front end:

PHP (data.php)

 <?php
// Set the response header,Specify the return data type as JSON
header('Content-Type: application/json');

// Create an associative array,Indicates the data to be returned
$response = array(
    'status' => 'success',
    'message' => 'Data has been successfully processed.',
    'data' => array('item1', 'item2', 'item3')
);

// use json_encode() Function converts array to JSON Format
echo json_encode($response);
?>

JavaScript (front-end)

 fetch('http://m66.net/api/data.php', {
    method: 'GET'
})
.then(response => response.json()) // Analysis JSON data
.then(data => {
    console.log(data);  // 在控制台输出返回的data
})
.catch(error => console.error('Error:', error));

Things to note

  1. Make sure that JSON is formatted correctly : The data returned in PHP should be in a valid JSON format. You can use the json_encode() function to convert PHP arrays to strings in JSON format.

  2. CORS Problem : If the front-end and back-end are not under the same domain name, you may encounter cross-domain resource sharing (CORS). You need to set the Access-Control-Allow-Origin response header in PHP to allow cross-domain requests:

     header('Access-Control-Allow-Origin: *');
    

    This will allow any domain requests to access your API.

  3. Error handling : When handling JSON responses, ensure that the front-end can correctly handle the returned error information, such as if the HTTP status code is not 200.

By setting the correct response header and using AJAX, we can efficiently pass JSON data between the front and back ends.