Reputation: 4927
I'm totally new to wordpress/php I'm trying to use Angular with the rest API to do basic CRUID on custom table professor_schedule
.
To query the table everything works. This is what I have.
PHP
// get all schedules
function getAllProfessorSchedule( $data ) {
global $wpdb;
$query = "SELECT nom FROM `professor_schedule`";
$list = $wpdb->get_results($query);
return $list;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'professor-schedule/v2', '/all', array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'getAllProfessorSchedule'
));
});
JS
function getAllSchedules(){
$http({
method: 'GET',
url : 'http://localhost/structurecours/index.php/wp-json/professor-schedule/v2/all'
}).then(function (response) {
console.log(response.data)
$scope.data = response.data
}, function (response) {
console.error("error !! ", response)
});
}
Below is the code to insert data into the DB. The server respond with a 403 (Forbidden)
I'm logged in with an administrator account I have tried with the Basic Auth plugin but I always get the 403 error. I'm struggling for hours now. I would get any advices. Thanks
PHP
function addNewSchedule( WP_REST_Request $request ) {
// $args = array(
// 'headers' => array(
// 'Authorization' => 'Basic ' . base64_encode( 'user:password' ),
// ),
// );
// wp_remote_request( $url, $args );
global $wpdb;
$item = $request->get_json_params();
$fields = array();
$values = array();
foreach($item as $key => $val) {
array_push($fields, $key);
array_push($values, $val);
}
$fields = implode(", ",$fields);
$values = implode("','",$values);
$query = "INSERT INTO `professor_schedule` (".$fields.") VALUES ('".$values."')";
//$query = "INSERT INTO `professor_schedule` ('Nom') VALUES ('test')";
$list = $wpdb->get_results($query);
return $list;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'professor-schedule/v2', '/add', array(
'methods' => WP_REST_Server::CREATABLE,
'callback' => 'addNewSchedule',
'permission_callback' => function () {
return current_user_can( 'edit_others_posts' );
}
) );
} );
JS
$scope.addNewSchedule = function(){
$http({
method : "POST",
url : "http://localhost/structurecours/index.php/wp-json/professor-schedule/v2/add",
params:
{
nom : $scope.scheduleModel.nom
}
}).then(function(){
getAllSchedules();
});
}
Upvotes: 0
Views: 3135
Reputation: 1732
You can try disabling the mod_recurity by adding the following code to the .htaccess file. But sometimes it will not work and you have to contact the hosting provider.
<IfModule mod_security.c>
SecFilterEngine Off
SecFilterScanPOST Off
</IfModule>
Upvotes: 0
Reputation: 504
I had the same issue WordPress endpoints. You can try disabling mod_security
on your server or making an exception for mod_security
for the REST endpoints. Also you can try WordPress on your local server and confirm issue.
Upvotes: 0