Wordpress REST API custom endpoint for method POST - php

I am currently working on a project which requires a WordPress website and a simple REST api. I discovered that WordPress has its own REST api and decided to extend its functionality to meet my needs. All I need to do is to have endpoints for GET and POST requests that retrieve/insert data from/to a table which is not directly related to WordPress (but in the same database). I successfully implemented all GET requests, however, I am struggling to get the POST ones working.
I have this route register defined:
register_rest_route('api/v1', 'create-player/', array(
'methods' => 'POST',
'callback' => 'create_player',
));
The client sends a request through ajax call which is expected to hit the endpoint from the route above. This is the ajax:
$.ajax({
method: "POST",
url: '/wp-json/api/v1/create-player/',
data : JSON.stringify(data),
contentType: 'applcation/json',
beforeSend: function (xhr){
xhr.setRequestHeader("X-WP-None", locData.nonce);
console.log('beforeSend');
},
success: function(response){
console.log("success" + response);
},
fail: function (response){
console.log("fail" + response);
}
});
I am not sure how to build the POST route register from the REST api, the other GET requests have an attribute args that map directly to the parameters passed in the endpoint. Do I need something like that to handle the request data when using POST? How do I get the data type passed from the ajax and then use it in my function create_player(); The WP REST API documentation seems to be incomplete and all of the information I found uses endpoints for built-in WordPress features such as posts/authors/blogs etc. but I don't need that, I just want to use the provided functionality and create my own interface. Thank you.

in your callback function you can use something like this:
$param = $request->get_param( 'some_param' );
// You can get the combined, merged set of parameters:
$parameters = $request->get_params();
https://www.coditty.com/code/wordpress-api-custom-route-access-post-parameters

Finally found it! In order to access the body of the POST request use $request->get_body(); in your register_rest_route callback method.

Add POST in methods while registering route and in your callback function access your POST variables via $request array. That's it.

Related

How to pass a AJAX call on OctoberCMS

Im using OctoberCMS, the user plugin and I want to send data via AJAX to a controller and save the data in the database (in the column of the logged in user).
So I created a new Route in my routes.php
<?php
Route::get('saveHighscore', 'test\Profile\Controllers\HighScore#saveHighscore')
->middleware('web');
And a controller
<?php
namespace Test\Profile\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use October\Rain\Auth\Models\User;
use RainLab\User\Facades\Auth;
class HighScore extends \Illuminate\Routing\Controller
{
function saveHighscore(Request $request) {
DB::table('users')->where(['id' => Auth::getUser()->id])->update(['highscore' => $request]);
}
}
And my jQuery calls
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/saveHighscore",
type: "POST",
data: highscore
});
But nothing works. If I call /saveHighscore in my browser with dummy data in the controller, it works fine
It should work without any issue.
But I think you are making 2 different requests
In ajax config you specified -> type: "POST" and you are listening for get request
May be you just need to change Route::get -> Route::post
Now it should work expected.
If any doubts please comment.
The AJAX framework only works on the CMS controller or Backend controllers (controllers extending backend/classes/controller). If you're wanting to send data via AJAX without using the built in AJAX framework, then we would have to see more information from your console / network tab of your browser dev tools to see why exactly it's failing.

Can't access post route from API callback

I use a webhook to receive callback post from an API server. I've tested to post data from postman, it's works fine but from API server i can't receive anything.
But when i changed webhook by using webhook.site, it's work, but with my domain webhook its not, didn't even access my post route.
My route:
Route::group(['namespace' => 'Web'], function () {
//Callback card
Route::post('/callback', 'CustomersController#callbackCard');
My Controller:(If accessed post route will store a file)
public function callbackCard(Request $request){
Storage::put('Accessed.txt', '1');
}
Sorry for my bad English
Can anyboy help me.
the callback API just send Post with application/x-www-form-urlencoded;charset=utf-8
my url: domain/callback
default namespace Web

How to get form data into laravel 5.6 controller that posted with OPTIONS method

I am creating APIs into laravel 5.6 for angular.
Form data is sending to API with OPTIONS method.
How can I get this data into the controller?
I have tested like this.
jquery ajax
$.ajax({
url:'domain.com/laravel_app/api/register_user',
type:"options",
dataType:'json',
data:{name:'Joe'},
success:function(r)
{
console.log(r);
}
})
Laravel route
Route::match(['post', 'options'], '/register_user/', 'UserController#register_user');
Laravel controller
public function register_user(Request $request)
{
print_r($request->all());
$arr1['status']='SUCCESS';
return json_encode($arr1);
}
All is working fine with "post" method but not with "options"
This seems to be an issue with jQuery ignoring the spec on the OPTIONS verb and sending your data as the request body.
You should be able to bypass this by doing:
$.ajax({
url:'domain.com/laravel_app/api/register_user?'+$.param({name: 'Joe'}),
type:"options",
dataType:'json',
success:function(r)
{
console.log(r);
}
})
However keep in mind that according to the spec:
The HTTP OPTIONS method is used to describe the communication options for the target resource.
What you are using this request here does not seem to be used to describe communication options for the target resource so you should not be using the OPTIONS method for this.

laravel 5.2 valid ajax request

How can we check in Laravel 5.2 if a request is a valid ajax request. In codeigniter ,we could check it like $this->input->is_ajax_request(). Does, Laravel 5.2 has something similar?
Also, I would like to know that how can we validate a request for csrf token. Is it fine if I let my webpage render through the 'web' middleware generating a csrf token and then pass this token as ajax request parameter? Would Laravel take care of validating the token or is there an alternate way around this?
I have checked the laravel 5.2 documentation, and since this is the first time I am dealing with laravel framework, it seems like the documentation assumes that the reader already has a familiarity with earlier versions of the framework. To a new comer like me this is little overwhelming.
Thanks in advance. Please let me know if you need more inputs from me.
Prakhar
I think this may help you to undestand a very basic way of using AJAX with Laravel.
It's a really old piece of code, but it works jajajaja
Controller side:
/**
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function getRamos(Request $request)
{
$check = Ramo::find($request->input('ramo'));
$subramos = Subramo::where('ramo_id', $check->id)->get(['nombre_subramo']);
if($request->ajax()){
return response()->json([
'subramos' => $subramos
]);
}
}
In the front:
<script>
$(document).ready(function(){
$('#ramo').change(function(){
var ramo, token, url, data;
token = $('input[name=_token]').val();
ramo = $('#ramo').val();
url = '{{route('getRamos')}}';
data = {ramo: ramo};
$('#subramos').empty();
$.ajax({
url: url,
headers: {'X-CSRF-TOKEN': token},
data: data,
type: 'POST',
datatype: 'JSON',
success: function (resp) {
$.each(resp.subramos, function (key, value) {
$('#subramos').append('<option>'+ value.nombre_subramo +'</option>');
});
}
});
});
});
</script>
Considering "#ramo" as a select input and in use of the style / html package where the token is passed as a hidden input.
In Laravel 5.2 (I hope any body get help from this code for Ajax)
Get ajax request in function , two examples of function is under:
First Example
public function getLev() {
if (!Request::ajax())
return false;
$result = Input::all();
$lev_id = (int) $result['lev_id'];
$invoiceid = (int) $result['invoiceid'];
return SuppliersController::getLev($invoiceid,$lev_id);//you can do any thing with your variables
//function is working in my case, you case take idea from this function
}
Second Example
public function deleteInvoice() {
if (Request::ajax()) {
$data = Input::all();
return delete_invoice($data['invoice_id'], $data['reason_text']);//you can do any thing with your variables
}
return false;
//function is working in my case, you case take idea from this function
}
Include these files on top of the page/controller where you write above ajax related functions:
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Request;
How can we check in Laravel 5.2 if a request is a valid ajax request. In codeigniter ,we could check it like $this->input->is_ajax_request(). Does, Laravel 5.2 has something similar?
The Request class has an ajax() function, so $request->ajax() or Request::ajax() (depending on how you're getting the request in your controller) will do the trick.
Also, I would like to know that how can we validate a request for csrf token. Is it fine if I let my webpage render through the 'web' middleware generating a csrf token and then pass this token as ajax request parameter? Would Laravel take care of validating the token or is there an alternate way around this?
Yes, pass the token with the AJAX call and make sure your routes have the CSRF middleware (try a request without a token - it should throw an error). Examples are in the docs for this: https://laravel.com/docs/5.2/routing#csrf-x-csrf-token
Anytime you define a HTML form in your application, you should include a hidden CSRF token field in the form so that the CSRF protection middleware will be able to validate the request.
To generate a hidden input field _token containing the CSRF token, you may use the csrf_field helper function:
So to use AJAX request with POST method, you need to pass hidden CSRF token field along with ajax data:
<script>
var token="<?php echo csrf_token(); ?>";
$.ajax({
url:url,
method:'POST',
data:{
'_token':token,
'id':1
}
})
</script>

How to 'forward' all requests from a group of routes to another, with parameters altering in Symfony2?

I have a RESTful API that is made with Symfony, and secured by OAuth. Here is an example of call:
method: POST
url: https://www.mywebsite.com/api/forumposts?access_token=xxxxxxx
params: { title: 'my new post', content: 'this is a great informative new post.' }
I would like to implement a sort of proxy (as described here) to prevent a client JS app to directly access the API and most importantly to prevent the client OAuth id and secret to be available in the JS code. Here is an example of equivalent call to this proxy:
method: POST
url: https://www.mywebsite.com/proxy/forumposts?proxy_key=yyyyyyy
params: { title: 'my new post', content: 'this is a great informative new post.' }
What I need is to be able to:
alter the Request object (for instance replacing proxy_key=yyyyyyy by access_token=xxxxxxx)
'forward' the proxy request to the corresponding route in my base API.
I do not know if 'forward' is the right word here: what I want is
the original request to the proxy to be dealt with by Symfony,
after having modified parameters, as if a direct request to the API.
I guess this will mean creating a Symfony service listening to the kernel.request event. But my question is: how should this redirecting service be coded?
NB.
The Symfony Controller redirect() function is not to be used here since the redirection must be transparent for the user.
On the other hand, I'd say the Symfony Controller forward() function can not be used here either because this function directly calls a Controller and bypass the OAuth checks that would be normally done before and after controller execution when requesting directly the API.

Categories