Search code examples
phppostgresqlphp-pgsqlxajax

How to send HTTP request with PHP to connect PostgreSQL db using Jaxon?


I'm trying to connect to a PostgreSQL database when I click on a button and display a message to notify success or fail connection.

It's my first time doing such operation in web interface and using Jaxon (PHP lib to do AJAX, fork of XAJAX).

<?php
include "vendor/autoload.php";
use Jaxon\Response\Response;
use Jaxon\jaxon;

class Db_connection
{
    public function test() {
        $host = "host = localhost";
        $port = "port = 5432";
        $dbname = "dbname = test";
        $user = "user = test";
        $password = "password = test";
        $response = new Response();
        $textFail = "Error : Unable to open database";
        $textValid = "Opened database successfully";

        $db = pg_connect("$host $port $dbname $user $password" );
        if(!$db){
          $response->alert($textFail);
           return $response;
        }else {
            $response->alert($textValid);
            return $response;
        }
    }
}

$jaxon = jaxon();
$jaxon->register(Jaxon::CALLABLE_OBJECT, new Db_connection());
$jaxon->processRequest();

?>

<!doctype html>
<html>
<head>
    <title>Jaxon Simple Test</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="/favicon.ico">
</head>
<body>
<input type="button" value="Submit" onclick="JaxonDb_connection.test()" />
</body>
<?php

echo $jaxon->getJs();
echo $jaxon->getScript();

?>
</html>

When I click the button from my browser I get nothing.

I want to learn from this, so, if possible, explain to me what I'm doing wrong here, or if my approach is lacking insight.


Solution

  • Checkout the pg_connect() documentation at https://www.php.net/manual/fr/function.pg-connect.php. You need to fix its parameters.

    You may also want to use the developer mode of your browser to see when your application return an HTML error instead of the expected json, which in this case explains why you get nothing in your web page.

    Thierry