I tried to get an success response from my ajax recall but it failed.
When I open the dev tool in chrome I can see the response and it is composed of my json response and also the class name which is triggered in my .php file. This throwns then an exception in my console.
This are the script how I made the call, triggering by a click of a button.
jquery.backend.js
$('#save-config-map').on('click', function () {
$.ajax( {
url: '../../ajax/ajax_config_map.php',
success: function (response) {
console.log(response.error);
}
});
});
ajax_config_map.php
require_once($_SERVER['DOCUMENT_ROOT'] . 'loader.php');
use DbDatabaseConfigMap;
$insertDataConfigMap = new DatabaseConfigMap();
$result = $insertDataConfigMap->insertConfigDataAllDB();
$results = array(
'error' => $result
);
echo json_encode($results);
DatabaseConfigMap.php
namespace Db;
use PDO;
use PDOException;
class DatabaseConfigMap extends DatabaseMain {
public function __construct() {
parent::__construct();
}
public function insertConfigDataAllDB()
return 'Test';
}
}
DatabaseMain.php
namespace Db;
use PDO;
require_once(DATABASE_DIR);
class DatabaseMain
{
protected string $servername;
protected string $dbname;
protected string $username;
protected string $password;
public function __construct() {
$dsn = sprintf("mysql:host=%s;dbname=%s;charset=%s", DB_HOST, DB_DATABASE, DB_CHARSET);
$this->conn = new PDO($dsn, DB_USERNAME, DB_PASSWORD);
$this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
}
loader.php <– loading all my classes
$rootDir =CLASSES_DIR;
$autoload = function($className) use($rootDir){
var_dump($className);
$fileName = '';
if($lastNameSpacePosition = strpos($className,'\')){
$namespace = substr($className, 0,$lastNameSpacePosition);
$className = substr($className,$lastNameSpacePosition+1);
$fileName = str_replace('\',DIRECTORY_SEPARATOR,$namespace).DIRECTORY_SEPARATOR;
}
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className);
if(is_file($rootDir.$fileName.'.php')){
require_once $rootDir.$fileName.'.php';
}
};
spl_autoload_register($autoload);
I cut some code where I insert the data in my database. This code works very well but as I said, the response is:
string(20) "DBDatabaseConfigMap"...{error: 'Test'}
error: "Test"
Thanks for all the help
Marcus
I used the dev tool from chrome to analyse the error and checked the board and google for solution.
2
Answers
specify the dataType: ‘json’ in
put this before your echo json_encode($x) for 200 response
You need to specify in ajax that the response will be in json format