I need to fetch some data from a mysql database. For that I created get_data.php on the server and a js function to retrieve that data on the client. Is this the proper way to do it? What would you change?


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

    if ($_SERVER['REQUEST_METHOD'] != 'POST' || !isset($_POST['entryID'])){
        exit('Bad request data');

    $db = db_connect();

    $stmt = $db->prepare("SELECT `data` FROM `entries` WHERE `id` = ? LIMIT 1;");
    $stmt->bind_param('i', $_POST['entryID']);
    $res = $stmt->get_result();

    if ($res->num_rows > 0){
        $arr = $res->fetch_assoc();
        $json = array('status'=> 1, 'data'=>$arr['data']);
        $json = array('status'=> 0);

    echo json_encode($json);

Code to fetch that data in javascript:

function getRemoteData(entryID) {
    const defaultErrorMessage = '## This page isn\'t ready (yet)';

    const form = new FormData();
    form.append('entryID', entryID);

    const d = fetch(requestUrl + '/get_data.php',
            method: 'POST',
            body: form,
        .then(response => response.json())
        .then(json => {
            if (json.status == 1 && json.data != "")
                return gunzipString(json.data);

            return defaultErrorMessage;

    return d;

It works fine but I'm not sure I'm doing things properly.


2 Answers 2


If I'm not wrong, you're missing header("Content-Type: application/json");. If you don't do this, most of the clients will work but some low-level clients might fail.

Also, you can optionally add Access-Control-Allow-Methods header to increase your backend's security level.

Plus, you should return a JSON response and set the HTTP status to 400 Bad Request instead of just exiting out (line 6) like this:

header("HTTP/1.1 400 Bad Request");
echo json_encode(['status' => -1, 'message' => "Bad request"]);

I hope this helps you.


I wouldn't change much. As was suggested by ArRakin using more headers is a good idea. The sample code in that answer uses the short array syntax introduced in PHP 5.4. There isn't anything wrong with using the longer syntax but the short syntax can make line length shorter overall, and may be more comfortable for anyone working with JSON and/or JavaScript.

One minor point to consider is spacing. Compare the spacing on the arrays in the following lines:

$json = array('status'=> 1, 'data'=>$arr['data']);


$json = array('status'=> 0);

Some developers follow the PSRs like PSR-12, which recommends:

6.2. Binary operators

All binary arithmetic, comparison, assignment, bitwise, logical, string, and type operators MUST be preceded and followed by at least one space.

For the sake of readability, use a space before and after operators including =>.

In the JavaScript code, the variable d is only used once - i.e. when returned. Single-use variable often can be eliminated - e.g. instead of assigning the return from fetch() just return it:

return fetch(requestUrl + '/get_data.php',

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.