Search code examples
phphttp-status-codes

Retrieving and Storing Response (Status Code) - PHP


So, I'm trying to understand HTTP status codes and I want to connect to a database. My problem is getting the correct response from my php function.

test.php

<?php
// try catch statement to connect to database through getConnection() function in dbConn.php file

try {
    require_once("dbConn.php");
    $dbConn = getConnection();
    // if getConnection() returned $conn (a connection), then $response_array["status"] = "success"
    // if getConnection() returned 503 status code from the catch block, then $response_array["status"] = "failed"
    // $response_array["status"] = "success";
} catch (Exception $e) {
    // if the file does not exist, then $response_array["status"] = "notFound"
    // http_response_code(404);
    // $response_array["status"] = "notFound";
}

header("Content-type: application/json");
echo json_encode($response_array);

dbConn.php

<?php
function getConnection()
{
    try {
        $conn = new PDO(
            "localhost=localhost;dbname=dbname",
            "username",
            "password"
        );
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $conn;
    } catch (Exception $e) {
        //throw new Exception("Connection error " . $e->getMessage(), 0, $e);
        http_response_code(503);
    }
}

I recently altered my getConnection() function in dbConn.php to return the 503 status code if it failed to connect to the database, but I am having trouble getting that status code in my test.php file. I wish to retrieve whether or not the connection was valid to store a success or failed message into $response_array["status"], which would then be sent back to an ajax handler to trigger a success or error method. I also want to do the same for the 404 status code if the file is not found.


Solution

  • The initial question was asked here: Ajax - Database Connection Handling

    AJAX part:

    $.ajax({
      type: "post",
      dataType: "text",
      url: "test.php",
    
      statusCode: {
        404: function(message) {
          alert(message);
        }
      } 
    
      success: function(data) {
        alert('Success');
      }
    });
    

    PHP part:

    // sent a 404...
    http_response_code(404);
    echo 'File not found';
    exit;