I'm really new in Ajax with PHP and JavaScript. I have to do some simple project as a workshop for my training and I created js script:
$(function() {
$('#bookAdd').submit(function (e) {
e.preventDefault();
var title = $('#title').val();
var description = $('#description').val();
// console.log(title + '\n');
// console.log(description);
$.ajax({
url: "../rest/rest.php/book",
data: {
'title': title,
'description': description
},
type: 'POST',
dataType: 'json',
success: function (response) {
console.log(response);
//console.log(response['success']);
},
error: function (xhr, status, error) {
console.log('error');
}
});
});
});
Where #bookAdd is form to add new book and rest.php is php script where proper class is added and book is saving to DB. It looks like this:
<?php
//load DB config
require_once __DIR__.'/config/db.php';
$response = [];
//connect to DB
try {
$conn = new PDO(
"mysql:host=".DB_HOST.";dbname=".DB_DB.";charset=utf8"
, DB_LOGIN, DB_PASSWORD,
[PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
);
} catch (PDOException $e) {
$response = ['error' => 'DB Connection error: '.$e->getMessage()];
}
######### Dynamic load php class file depend on request #########
//parsing url
//if request URI is rest.php/book/1
//we will parse part book/1 and explode it
//to get name of class (book) and optional id from db (1)
$uriPathInfo = $_SERVER['PATH_INFO'];
//explode path info
$path = explode('/', $uriPathInfo);
$requestClass = $path[1];
//load class file
$requestClass = preg_replace('#[^0-9a-zA-Z]#', '', $requestClass);//remove all non alfanum chars from request
$className = ucfirst(strtolower($requestClass));
$classFile = __DIR__.'/class/'.$className.'.php';
require_once $classFile;
######### END DYNAMIC LOAD #########
$pathId = isset($path[2]) ? $path[2] : null;
if (!isset($response['error'])) {//process request if no db error
include_once __DIR__.'/restEndpoints/'.$className.'.php';
}
header('Content-Type: application/json');//return json header
if (isset($response['error'])) {
header("HTTP/1.0 400 Bad Request");//return proper http code if error
}
echo json_encode($response);
The thing I can't find out is success function in my js file - why console log doesn't display anything?