WordPress endpoint plugin shows SyntaxError: JSON.parse - wordpress

i have read many pages to find out howto create a simple endpoint into my simple WP-Plugin.
links of good articles i have read for that:
https://developers.shopware.com/developers-guide/rest-api/plugin-api-extension/ , https://wptips.dev/custom-rest-api/ , https://torquemag.io/2016/07/adding-custom-endpoints-extra-touches/ , https://www.cloudways.com/blog/wordpress-rest-api-to-fetch-posts/#get-wp-v2-posts , https://www.cloudways.com/blog/wordpress-rest-api-to-fetch-posts/#wordpress-rest-api-using-json , https://developer.wordpress.org/rest-api/
this gives me most hope to get success with it and i used the source from here:
https://stackoverflow.com/a/64331655/2891692
My URL i using in Web-Browser:
http://localhost/wordpress/wp-json/a0plugin/v1/testing
excerpt of my complete source from gist
htdocs/wp-content/plugins/a0plugin/a0plugin.php
<?php
/**
* Plugin Name: a0plugin
*/
function at_rest_testing_endpoint(){
return new WP_REST_Response('Howdy!!');
}
function at_rest_init(){
$namespace = 'a0plugin/v1';
$route = 'testing';
register_rest_route($namespace, $route, array(
'methods' => WP_REST_Server::READABLE,
'callback' => 'at_rest_testing_endpoint'
));
}
add_action('rest_api_init', 'at_rest_init');
?>
complete source:
https://gist.github.com/sl5net/10d21e8bd358b9149968885a93862424
SyntaxError: JSON.parse
Error: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

if the comments are left out, the error disappears. these are not listed in the so-called relevant source text excerpt. the cause is unknown to me.

Related

lumen - Why does PHPUnit register test returns 405?

I want to make phpunit tests for lumen app, like :
public function testRegisterUser()
{
$newUserData = [
'name' => 'test_user',
'email' => 'test_user#mail.com',
'password' => Hash::make('111111'),
'status' => 'A',
'has_debts' => false
];
$response = $this->get('/api/v1/register', $newUserData); // http://localhost:8000/api/v1/register
$this->assertResponseOk();
}
But running tests I got 405 error :
1) PagesTest::testRegisterUser
Expected response status code [200] but received 405.
Failed asserting that 200 is identical to 405.
/ProjectPath/vendor/illuminate/testing/TestResponse.php:177
/ProjectPath/vendor/illuminate/testing/TestResponse.php:99
/ProjectPath/vendor/laravel/lumen-framework/src/Testing/Concerns/MakesHttpRequests.php:415
/ProjectPath/tests/PagesTest.php:27
Why I got 405 Method Not Allowed ? I postman I check my method : https://prnt.sc/207bu03
Method /api/v1/register in postman has no any token protection.
How to make my test working ?
UPDATED BLOCK :
I got error :
Error: Call to undefined method PagesTest::getJson()
If I modify :
$response = $this->getJson('/api/v1/register', $newUserData);
method getJson is mentioned here : https://laravel.com/docs/8.x/http-tests
But on this page I see in test file header:
namespace Tests\Feature;
But not in my generated lumen test file.
In my routes/web.php I have :
$router->group(['prefix'=>'api/v1'], function() use($router){
$router->post('/register','AuthController#register');
$router->post('/login', 'AuthController#login');
$router->group(['middleware' => 'auth'], function () use ($router) {
$router->get('/profile', 'UserProfileController#index');
What is wrong ?
Thanks!
Because you maybe have to use $this->getJson instead of $this->get.
It is not http://localhost:8000 as you are testing, you are not literally accessing the URL. It is simulating that.
Also share your api.php or routes file and the controller please (also the middlewares working on that URL).
Looking at the Lumen's documentation I can see that there is no getJson, my bad. You have to use $this->json('GET' instead.

Ninja Forms server-side validation not working

I have spent two days trying to figure this out. I have wordpress page with a four field Ninja Form. One of the fields is an Email. I created an API (in our .NET Core project) that checks and then throws a 400 error if a already with that email address exists in our DB. I am using the Ninja Forms Webhook feature to submit the form to my API. I just want to display my 400 error message to the user.
I am using the documentation below from Ninja Forms but it is not working:
https://developer.ninjaforms.com/codex/custom-server-side-validation/
More specifically, I am getting a 500 with the the following error in the console:
Uncaught Error: Call to undefined function my_nf_validation() in \/home\/site\/wwwroot\/wp-content\/themes\/hello-elementor\/functions.php:245\nStack trace:\n#0 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): {closure}(Array)\n#1 \/home\/site\/wwwroot\/wp-includes\/plugin.php(206): WP_Hook->apply_filters(Array, Array)\n#2 \/home\/site\/wwwroot\/wp-content\/plugins\/ninja-forms\/includes\/AJAX\/Controllers\/Submission.php(132): apply_filters('ninja_forms_sub...', Array)\n#3 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): NF_AJAX_Controllers_Submission->submit('')\n#4 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(311): WP_Hook->apply_filters('', Array)\n#5 \/home\/site\/wwwroot\/wp-includes\/plugin.php(478): WP_Hook->do_action(Array)\n#6 \/home\/site\/wwwroot\/wp-admin\/admin-ajax.php(175): do_action('wp_ajax_nf_ajax...')\n#7 {main}\n thrown<\/pre>"},"last":{"type":1,"message":"Uncaught Error: Call to undefined function my_nf_validation() in \/home\/site\/wwwroot\/wp-content\/themes\/hello-elementor\/functions.php:245\nStack trace:\n#0 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): {closure}(Array)\n#1 \/home\/site\/wwwroot\/wp-includes\/plugin.php(206): WP_Hook->apply_filters(Array, Array)\n#2 \/home\/site\/wwwroot\/wp-content\/plugins\/ninja-forms\/includes\/AJAX\/Controllers\/Submission.php(132): apply_filters('ninja_forms_sub...', Array)\n#3 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(287): NF_AJAX_Controllers_Submission->submit('')\n#4 \/home\/site\/wwwroot\/wp-includes\/class-wp-hook.php(311): WP_Hook->apply_filters('', Array)\n#5 \/home\/site\/wwwroot\/wp-includes\/plugin.php(478): WP_Hook->do_action(Array)\n#6 \/home\/site\/wwwroot\/wp-admin\/admin-ajax.php(175): do_action('wp_ajax_nf_ajax...')\n#7 {main}\n thrown","file":"\/home\/site\/wwwroot\/wp-content\/themes\/hello-elementor\/functions.php","line":245}},"debug":[]}
I placed the code in the function.php file in Themes Editor. This is my first time working with wordpress so I hope I am doing this right. This is my code and is taken directly from the above documentation:
add_filter( 'ninja_forms_submit_data', function( $form_data ){
if( ! my_nf_validation( $form_data ) ) { // Add check here.
$errors = [
__( 'An unexpected error occurred.', 'my-plugin' )
];
$response = [
'errors' => $errors,
];
echo wp_json_encode( $response );
wp_die(); // this is required to terminate immediately and return a proper response
}
// If no errors, be sure to return the $form_data.
return $form_data;
});
I would really appreciate anyone's help with this.
Try the following Code, It will work.
function validateCode($field){
if( checkCondition ){
// let it go
return true;
}
else{
return false;
}
}
add_filter( 'ninja_forms_submit_data', 'my_ninja_forms_submit_data' );
function my_ninja_forms_submit_data( $form_data ) {
$form_settings = $form_data[ 'settings' ]; // Form settings.
if($form_data['id'] == '2'){
foreach( $form_data[ 'fields' ] as $field ) { // Field settigns, including the field key and value.
if( 'unique_code' == $field[ 'key' ] ){
if(!validateCode($field)){
$form_data['errors']['fields'][$field['id']] = "INVALID CODE";
}
}
}
}
return $form_data;
}
The documentation references a custom WordPress filter, as defined by the Ninja Forms plugin. Filters are a feature of WordPress Hooks, which allow a theme or plugin to modify the functionality of another theme or plugin. See https://developer.wordpress.org/plugins/hooks/filters/
To your question, the Webhooks add-on plugin (an official extension of Ninja Forms) is not required to use the filter that you reference from the documentation.
Instead, you'll need to replace "my_nf_validation()" with your own defined function, as the documentation shows an example.
Your function needs to handle the API request and response handling. In the documentation example, the custom function returns a Boolean value.

Wordpress REST API cannot post comments

I am trying to post comments to my posts using the Wordpress JSON API but I keep getting an error.
Heres what I have done:
I have added the 'rest_allow_anonymous_comments' function
add_filter( 'rest_allow_anonymous_comments', '__return_true' );
Then went to the URL
https://example.com/wp-json/wp/v2/comments?post=192&author_email=mytestemail#gmail.com&author_name=TestName&content=ThisIsTestContent
But it just returns the error:
{"code":"rest_forbidden_param","message":"Query parameter not permitted: author_email","data":{"status":401}}
Does anyone know what I am doing wrong?
First of all, You have to create a endpoint for comment.
add_action('rest_api_init', function () {
register_rest_route( 'mycomment/v1', 'comment/(?P<post_id>\d+)',array(
'methods' => 'POST',
'callback' => 'post_comment'
));
});
Then the post_comment in callback will point it to another function to create another function for your logic. In this call back function, you can add your comment using wp_insert_comment().
function post_comment($request) {
// Your code here
}
Enjoy!

Get current user inside register_rest_route method

How to retrive wp_get_current_user() inside a register_rest_route callback (Wordpress site)?
I'm just trying to do a simple hello wp_get_current_user()->user_login on a php test page:
add_action('rest_api_init', 'helloTest');
function helloTest() {
register_rest_route('hello', 'hello/(?P<id>\d+)', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'showHello'
));
}
function showHello($someVariable) {
echo "Hello " . wp_get_current_user()->user_login . $someVariable;
}
But wp_get_current_user() is null and wp_get_current_user->ID is 0;
I dont want to authenticate the user again. I just want to retrieve his username. If he is not logged in, just show empty an empty string.
If I have to authenticate again, how to add a "nonce" to it? On internet I just have examples using javascript, but not directly on PHP methods.
Issues in your code
First off, you should understand properly how to add custom WP REST API endpoints:
An endpoint's namespace (the first parameter passed to register_rest_route()) should be in this format: your-plugin/v<version>. E.g. hello/v1 or hello-world/v1 and not just hello or hello-world.
$someVariable (the first parameter passed to your endpoint callback function) is not just any variable — it's an instance of the WP_REST_Request class — and shouldn't be echo-ed like what you did here:
function showHello($someVariable) {
echo "Hello " . wp_get_current_user()->user_login . $someVariable;
}
And normally, the $someVariable is better be changed to $request (i.e. rename it to "request").
And you should return a valid WP REST API response. For example, to return just the username:
return new WP_REST_Response( wp_get_current_user()->user_login, 200 );
And know your own API endpoint URL..
(based on your original namespace)
/wp-json/hello/hello/1 <- correct
/wp-json/hello/?John <- incorrect
because in your code, the parameter is a number and not string: (?P<id>\d+)
I hope those help you, and once again, do read the handbook for a more detailed guide.
The Corrected Code
add_action( 'rest_api_init', 'helloTest' );
function helloTest() {
register_rest_route( 'hello/v1', 'hello/(?P<id>\d+)', array(
'methods' => WP_REST_SERVER::READABLE,
'callback' => 'showHello'
) );
}
function showHello( $request ) {
return new WP_REST_Response( wp_get_current_user()->user_login, 200 );
}
Now about getting the user (from the API endpoint — showHello())
If I have to authenticate again, how to add a "nonce" to it?
Just because the user is logged-in/authenticated to the (WordPress) site, it doesn't mean the user is automatically logged-in to the WP REST API. So yes, you'd need to either provide a nonce along with your API request, or use one of the authentication plugins mentioned right here.
Now in most cases, GET (i.e. read-only) requests to the API do not need any authentication, but if you'd like to retrieve the data of the currently logged-in user on your site, then one way is via the _wpnonce data parameter (either POST data or in the query for GET requests).
Example for a GET request:
http://example.com/wp-json/wp/v2/posts?_wpnonce=<nonce>
So based on your comment and the corrected code (above):
Theres no "code" that make the request. Its is just an anchor that
calls my route: Hello
You can add the nonce as part of the URL query string like so: (the namespace is hello/v1 and the <id> is 1)
// Make request to /wp-json/hello/v1/hello/<id>
$nonce = wp_create_nonce( 'wp_rest' );
echo 'Hello';
So try that out along with the corrected code and let me know how it goes. :)
And once again, be sure to read the REST API authentication handbook.

Wordpress Rest API returns error

I'am developing a plugin for wordpress and have trouble with the Rest API.
On my test server it works without a problem. (v4.6.6)
On a different server (v4.4.10) the API returns this error message:
{"code":"rest_invalid_handler","message":"
Der Handler f\u00fcr die Route ist ung\u00fcltig","data":{"status":500}}%
The message is in german and means "The handler for the route is invalid." Don't understand why they translate the error messages for an API. Makes no sense for me. :)
The routes on the http://domain/wp-json are equal.
Maybe an problem with the different WP versions?
Definition of the route:
function __construct() {
add_action( 'rest_api_init', function(){
register_rest_route( 'test_namespace', 'ping', array(
'methods' => 'POST',
'callback' => array($this, 'ping_test'),
'permission_callback' => array($this, 'myhacks_permission_callback'),
) );
} );
}
Thanks for help.
I had the same issue. It seems that method ping_test cannot be private. If you change it to public, the error disappears.
Take a look at the WordPress core and you can see that the method passed as the callback aka ping_test must be callable.
So this error triggers only when that method doesn't exist (for example I just encountered it because of a typo) or if is not accessible(like a protected or private method)

Resources