Reputation: 605
I am having jquery ajax call as follows.
$("form.form-signin").submit(function (e) {
e.preventDefault();
var $form = $(this);
$.ajax({
url : "scripts/logincontroller.php",
type: "POST",
dataType :"json",
data: {
username : $form.find("input[name='username']").val(),
password : $form.find("input[name='password']").val()
},
success: function(response){
$("div.jumbotron div#error_panel").css("display","block");
var err_msg = '';
if(response.errors != null){
for(i = 0; i<response.errors.length;i++){
err_msg += response.errors[i]+"</br>";
}
$("div.jumbotron div#error_panel div#message").empty().append(err_msg);
return;
}else{
$("div.jumbotron div#error_panel div#message").empty().append("ok");
}
},
error: function(xhr, status, errorThrown){
alert(errorThrown+status);
$("div.jumbotron div#error_panel").css("display","block");
}
});
});
Now I have following classes. This class connects to database and returns db object if success, string error otherwise.
//DBConfiguration.class.php
namespace db;
class DBC{
const username = "root";
const password = "****";
const host = "localhost";
const schema = "mydb";
static function connect(){
try{
$dbh = new \PDO('mysql:host='.self::host.';dbname='.self::schema, self::username, self::password, array(
\PDO::ATTR_PERSISTENT => true
));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
return $dbh;
}catch (\PDOException $e){
return "Failed to connect to database";
}
}
}
This class calls the above connect and returns the result.
//Authenticator.php
namespace db;
include "DBConfiguration.class.php";
class Authenticator{
public function isValidUser($username,$password){
$result = array();
$dbh = DBC::connect();
if(is_string($dbh) && $dbh === "Failed to connect to database"){
$err = array();
$err[] = "Oops! Something went wrong. We are working on it";
$result["errors"] = $err;
}else{
$err = array();
$err[] = "connected successfully";
$result["errors"] = $err;
}
return $result;
}
}
//LOGINCONTROLLER.PHP
header("Content-Type: application/json", true);
include "db\Authenticator.php";
$authenticator = new \db\Authenticator();
echo json_encode($authenticator ->isValidUser($_POST["username"],$_POST["password"]));
When I am intentionally changing the password and could not connect to db I am getting correct error message. But when it is successful (in which case I am returning db object from connect() method), I am getting 'unexpected token <'.
Weird thing is I am able to run the code when I place all these classes in logincontroller.php instead of induvidual namespaces.
Is there any problem with this code?
Upvotes: 1
Views: 299
Reputation: 605
I found the answer. The following line is causing the problem.
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
The above line of code must be
$dbh->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
As I am calling this from a namespaced class PDO must refer to global PDO class.
Upvotes: 1