$_REQUEST php equivalent in node js - php

Actually I am using a third party api url of Plivo.
There I need to supply a URL with POST method on which they are gonna post call data .
I have provided url in lumen and able to get the data posted by third party url using $_REQUEST successfully.
Now I am trying implement the same in node js express like:
exports.plivoIvrCallback = function (req, res) {
console.log(req);
}
but I am not getting anything in req or req.body !
So what might be node js equivalent to $_REQUEST in php.??

Please install body-parser package and then try.

you can install body-parser (as suggested by # Mr.Gandhi) or any other requests parsers you want, than add the following line at the start of your handler:
let request = Object.assign(req.query, req.body); // you can also add here req.params etc...
and use request from now on.

Related

How to accept the PUT request data in laravel? [duplicate]

I am using Laravel to create a RESTFUL application and I test the application with Postman. Currently, there is an issue for PATCH or PUT if the data sent from Postman with form-data.
// Parameter `{testimonial}` will be sent to backend.
Route::post ('testimonials/{testimonial}', 'TestimonialController#update');
// Parameter `{testimonial}` will not be sent to backend (`$request->all()` will be empty) if sent from Postman with form-data.
Route::patch ('testimonials/{testimonial}', 'TestimonialController#update');
Route::put ('testimonials/{testimonial}', 'TestimonialController#update');
Using form-data, $request->all() will be okay for POST.
Using x-www-form-urlencoded, $request->all() will be okay for PATCH, PUT, and POST.
However, if I am sending PUT and PATCH with form-data from Postman, the $request->all() will be empty (the parameters will not be sent to backend).
Right now the solution is to use POST for updating a model. I want to know why PATCH and PUT is not working when sent with form-data from Postman.
This is a known issue and the workaround suggestion as per the following Github comment is that when sending a PATCH / PUT requests you should do the following:
You should send POST and set _method to PUT (same as sending forms) to make your files visible
So essentially you send a POST request with a parameter which sets the actual method and Laravel seems to understand that.
As per the documentation:
Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The #method Blade directive can create this field for you:
<form action="/foo/bar" method="POST">
#method('PUT')
...
</form>
Alternatively, you can use the method_field helper function to do the above:
The method_field function generates an HTML hidden input field containing the spoofed value of the form's HTTP verb. For example, using Blade syntax:
<form method="POST">
{{ method_field('PUT') }}
</form>
I learnt how to solve it here on this post and I'd like to share what did I do.
The following image is how I setup the Postman to send a HTTP POST request and go into PUT Request and make it receive my files.
I'm not sure whether it is the right way to do a RESTFul API. But it works fine
so as everyone mentioned above and explained everything, but still i dont see the answer for cases when using a REST API so i fallowed #Caique Andrade answer and send a POST request and formed my URL link like this:
url = 'https://yourwebsite.com/api/v1/users/$id?_method=PUT';
$id is the variable id for the user.
?_method=PUT is added to the url POST request to spoof the request and it works
in my case i used Dart in flutter and sent a post request using Http package Laravel catches that POST request as a PUT request
Laravel PATCH and PUT method does not work with form-data, it's known issue of Symfony and even PHP (Google for that - Laravel use many Symfony foundation packages, include Request).
If you do not need to pass file(s) via request, change form-data to raw with json content-type. E.g: {"name":"changed"}. It will be read as php://input and your code should work well ($request->all() is now ["name" => "changed]).
If you need to pass file(s), in my opinion, DO NOT pass it within the REST API methods. You can write another method to do whatever you need with your file(s) (E.g: POST form-data -> upload file -> update db -> return a file path/url/even its base64 content), then you can use its output/result to continue with your patch/put method (raw with json content-type). I always do that when I work with files in API.
Hope this help!
InertiaJS Solution
I had the same problem. When no file was send, everything works perfectly, but when i send a file, none of the fields make it to the backend.
It seems that it's a PHP limitation, receiving no file via put, as said here before.
So, for those using InertiaJS, you need to make a post - instead of a put - call and add _method: "put" to your inertia form, like this:
updateForm: this.$inertia.form({
_method: "put",
"other fields"
}),
Your controller will understand it like a PUT call, but with the file accessible to the backend.
Source:
https://inertiajs.com/manual-visits#method
I hope it is not too late, or if someone is seeking help with the FormData interface of JavaScript. Here is the solution,
In Laravel, you can use #script47 answers above, for normal Ajax request you can append the data like this, (PS: I'm using same form for Add and Update so here is my code)
let _url = '';
let _type = 'POST';
let _formData = new FormData(this);
if(user_id == '' || user_id == null){
_url = "{{ route('users.store') }}";
}else{
_url = "{{ route('users.update', ':id') }}";
_url = _url.replace(':id', user_id);
_formData.append('_method', 'PUT');
// _type = 'PUT';
}
As mentioned, this isn't a symfony (or laravel, or any other framework) issue, it's a limitation of PHP.
After trawling through a good few RFCs for php core, the core development team seem somewhat resistant to implementing anything to do with modernising the handling of HTTP requests. The issue was first reported in 2011, it doesn't look any closer to having a native solution.
That said, I managed to find this PECL extension. I'm not really very familiar with pecl, and couldn't seem to get it working using pear. but I'm using CentOS and Remi PHP which has a yum package.
I ran yum install php-pecl-apfd and it literally fixed the issue straight away (well I had to restart my docker containers but that was a given).
That is, request->all() and files->get() started working again with PATCH and PUT requests using multipart/form-data.
I believe there are other packages in various flavours of linux and I'm sure anybody with more knowledge of pear/pecl/general php extensions could get it running on windows or mac with no issue.
As #DazBaldwin says, this is a php limitation and can be solve installing apfd extension. On windows just download the dll file here according to your system settings and put php_apfd.dll on path-to-php/ext directory finally put extension=apfd in php.ini file.
it worked for me on windows.
The form media types do not have any semantics defined for PATCH, so it's really a bad idea to use them (see https://www.rfc-editor.org/errata/eid3169).
For PUT, the expected behaviour would be to store just the form-encoded payload (in that format). Is this really what you want here?
If You Route Method Is Patch And Use Postman For Api Request
If you want to send a file, for the controller, when using postman, you must set the sending mode to the post method and in the form-data section
key = _Method
Value = PATCH
You do not have to set the file so that you do not encounter any errors when sending the request.
You can also create a custom function in your controller to update the product then create an api route.
public function updateTestimonial($id, Request $request) {
$testimonial = Testimonial::where('id', '=', $id)->first();
//update logic
}
Api route
Route::post('updatetestimonial/{id}', 'Testimonial#updateTestimonial');
Use a post request and pass testimonial id.
submitForm() {
let data = new FormData();
data.append('id', this.testtimonial.id);
data.append('description', this.testtimonial.description);
axios.post("/api/updatetestimonial/" + this.testimonial.id , data, {
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': 'multipart/form-data',
}
}).then(({ data }) => {
console.log("success");
});
},
I know this article is old.
But unfortunately, PHP still does not pay attention to form-data other than the Post method.
But you can use the library I wrote for this purpose:
composer require alireaza/php-form-data
You can also use composer require alireaza/laravel-form-data in Laravel.
You can use post method.
const form = new
just append form.append('_method', 'PATCH');

PATCH and PUT Request Does not Working with form-data

I am using Laravel to create a RESTFUL application and I test the application with Postman. Currently, there is an issue for PATCH or PUT if the data sent from Postman with form-data.
// Parameter `{testimonial}` will be sent to backend.
Route::post ('testimonials/{testimonial}', 'TestimonialController#update');
// Parameter `{testimonial}` will not be sent to backend (`$request->all()` will be empty) if sent from Postman with form-data.
Route::patch ('testimonials/{testimonial}', 'TestimonialController#update');
Route::put ('testimonials/{testimonial}', 'TestimonialController#update');
Using form-data, $request->all() will be okay for POST.
Using x-www-form-urlencoded, $request->all() will be okay for PATCH, PUT, and POST.
However, if I am sending PUT and PATCH with form-data from Postman, the $request->all() will be empty (the parameters will not be sent to backend).
Right now the solution is to use POST for updating a model. I want to know why PATCH and PUT is not working when sent with form-data from Postman.
This is a known issue and the workaround suggestion as per the following Github comment is that when sending a PATCH / PUT requests you should do the following:
You should send POST and set _method to PUT (same as sending forms) to make your files visible
So essentially you send a POST request with a parameter which sets the actual method and Laravel seems to understand that.
As per the documentation:
Since HTML forms can't make PUT, PATCH, or DELETE requests, you will need to add a hidden _method field to spoof these HTTP verbs. The #method Blade directive can create this field for you:
<form action="/foo/bar" method="POST">
#method('PUT')
...
</form>
Alternatively, you can use the method_field helper function to do the above:
The method_field function generates an HTML hidden input field containing the spoofed value of the form's HTTP verb. For example, using Blade syntax:
<form method="POST">
{{ method_field('PUT') }}
</form>
I learnt how to solve it here on this post and I'd like to share what did I do.
The following image is how I setup the Postman to send a HTTP POST request and go into PUT Request and make it receive my files.
I'm not sure whether it is the right way to do a RESTFul API. But it works fine
so as everyone mentioned above and explained everything, but still i dont see the answer for cases when using a REST API so i fallowed #Caique Andrade answer and send a POST request and formed my URL link like this:
url = 'https://yourwebsite.com/api/v1/users/$id?_method=PUT';
$id is the variable id for the user.
?_method=PUT is added to the url POST request to spoof the request and it works
in my case i used Dart in flutter and sent a post request using Http package Laravel catches that POST request as a PUT request
Laravel PATCH and PUT method does not work with form-data, it's known issue of Symfony and even PHP (Google for that - Laravel use many Symfony foundation packages, include Request).
If you do not need to pass file(s) via request, change form-data to raw with json content-type. E.g: {"name":"changed"}. It will be read as php://input and your code should work well ($request->all() is now ["name" => "changed]).
If you need to pass file(s), in my opinion, DO NOT pass it within the REST API methods. You can write another method to do whatever you need with your file(s) (E.g: POST form-data -> upload file -> update db -> return a file path/url/even its base64 content), then you can use its output/result to continue with your patch/put method (raw with json content-type). I always do that when I work with files in API.
Hope this help!
InertiaJS Solution
I had the same problem. When no file was send, everything works perfectly, but when i send a file, none of the fields make it to the backend.
It seems that it's a PHP limitation, receiving no file via put, as said here before.
So, for those using InertiaJS, you need to make a post - instead of a put - call and add _method: "put" to your inertia form, like this:
updateForm: this.$inertia.form({
_method: "put",
"other fields"
}),
Your controller will understand it like a PUT call, but with the file accessible to the backend.
Source:
https://inertiajs.com/manual-visits#method
I hope it is not too late, or if someone is seeking help with the FormData interface of JavaScript. Here is the solution,
In Laravel, you can use #script47 answers above, for normal Ajax request you can append the data like this, (PS: I'm using same form for Add and Update so here is my code)
let _url = '';
let _type = 'POST';
let _formData = new FormData(this);
if(user_id == '' || user_id == null){
_url = "{{ route('users.store') }}";
}else{
_url = "{{ route('users.update', ':id') }}";
_url = _url.replace(':id', user_id);
_formData.append('_method', 'PUT');
// _type = 'PUT';
}
As mentioned, this isn't a symfony (or laravel, or any other framework) issue, it's a limitation of PHP.
After trawling through a good few RFCs for php core, the core development team seem somewhat resistant to implementing anything to do with modernising the handling of HTTP requests. The issue was first reported in 2011, it doesn't look any closer to having a native solution.
That said, I managed to find this PECL extension. I'm not really very familiar with pecl, and couldn't seem to get it working using pear. but I'm using CentOS and Remi PHP which has a yum package.
I ran yum install php-pecl-apfd and it literally fixed the issue straight away (well I had to restart my docker containers but that was a given).
That is, request->all() and files->get() started working again with PATCH and PUT requests using multipart/form-data.
I believe there are other packages in various flavours of linux and I'm sure anybody with more knowledge of pear/pecl/general php extensions could get it running on windows or mac with no issue.
As #DazBaldwin says, this is a php limitation and can be solve installing apfd extension. On windows just download the dll file here according to your system settings and put php_apfd.dll on path-to-php/ext directory finally put extension=apfd in php.ini file.
it worked for me on windows.
The form media types do not have any semantics defined for PATCH, so it's really a bad idea to use them (see https://www.rfc-editor.org/errata/eid3169).
For PUT, the expected behaviour would be to store just the form-encoded payload (in that format). Is this really what you want here?
If You Route Method Is Patch And Use Postman For Api Request
If you want to send a file, for the controller, when using postman, you must set the sending mode to the post method and in the form-data section
key = _Method
Value = PATCH
You do not have to set the file so that you do not encounter any errors when sending the request.
You can also create a custom function in your controller to update the product then create an api route.
public function updateTestimonial($id, Request $request) {
$testimonial = Testimonial::where('id', '=', $id)->first();
//update logic
}
Api route
Route::post('updatetestimonial/{id}', 'Testimonial#updateTestimonial');
Use a post request and pass testimonial id.
submitForm() {
let data = new FormData();
data.append('id', this.testtimonial.id);
data.append('description', this.testtimonial.description);
axios.post("/api/updatetestimonial/" + this.testimonial.id , data, {
headers: {
'accept': 'application/json',
'Accept-Language': 'en-US,en;q=0.8',
'Content-Type': 'multipart/form-data',
}
}).then(({ data }) => {
console.log("success");
});
},
I know this article is old.
But unfortunately, PHP still does not pay attention to form-data other than the Post method.
But you can use the library I wrote for this purpose:
composer require alireaza/php-form-data
You can also use composer require alireaza/laravel-form-data in Laravel.
You can use post method.
const form = new
just append form.append('_method', 'PATCH');

Saving Angular expression output in PHP variable

How I can save the expression output in a php variable?
I am looking for something like this
$document_id = {{Document.id}};
Thanks
use $http service injecting it to controller.
Use its ajax function ( here i am doing post method, but you can use get - look at documentation of
$http
directive.
.controller('MyCtrl',['$http',function($http){
//your additional code
$http.post('/myurl.php', {param:'Document.id'}).
success(function(data, status, headers, config) {
// execute after succesfully sent
})
}]);
Then create a php file named myurl.php
and in it:
$document_id = $_POST['param'];
The post url 'myurl.php' should reflect current php url, so it depends on application structure. You can also set direct url like: 'localhost:8080/myurl.php'. If you use on same domain it is ok, otherwise you can get origin policy problem.
What is done here is sending through AJAX to server where php interpreter handle it.

Getting POST data using AltoRouter PHP

I've implemented Alto Router in my MVC framework and it's routing Get requests using the URI perfectly.
It's got to the point where i need to start dealing with forms and POST data, so ive set up a route to deal with a POST request, the request works and i get taken to the post requests route e.g domain.com/contact/send/
Unfortunately i don't get the POST data in the params array on the match.
I'm not sure if im getting myself confused as to whether the router should do this or not.
If the router is not supposed to handle getting the POST data, could you point me in the right direction of how i could ideally handle the POST data?
If the router is supposed to handle POST data, home comes i can't see it in the params array of the match?
Here's a snippet of the POST request:
$router->map('POST','/contact/send/,'contact#send', 'contact_form_send');
$match = $router->match()
Any help will be much appreciated, thanks
Here is how I do it.
$router->map('POST', '/companies/create', function() {
if isset($_POST['company'])) {
createCompany($_POST['company']);
}
});
hope it helps
If you take a look at the AltoRouter source, params is extracted from the request URL, so it will not contain any POST data. This parameter is mainly used by AltoRouter for its reversed routing feature, but you can use it instead of accessing $_GET directly.
If you need to access POST data you will have to get it from the request directly by using either the $_POST or $_REQUEST superglobal.
Note that AltoRouter will overwrite $_REQUEST when you call match so it may behave differently than expected since it will not contain cookies.
I get POST data through php://input
// update a document
$router->map('POST', '/docs', function () {
$rc = new DocumentController();
$data = json_decode(file_get_contents('php://input'));
$data = (array)$data;
$rc->updateDocument($data);
});

jQuery AJAX not sending to my PHP program

I'm no expert in AJAX (or jQuery) but I thought what I was doing was pretty easy yet when I send an ajax request with:
$.ajax ( requestObj );
it doesn't send and I'm hoping someone can help. In order to give context, I've set the "requestObj" up as follows:
//initialise a request object
var requestObj = {};
requestObj.response = 'ajax-response';
requestObj.type = 'POST';
requestObj.url = my_config['ajax-service-list'][service]['url'];
requestObj.data = $.extend ( requestObj.data , {
action: service,
other: parameters,
_ajax_nonce: my_config['ajax-service-list'][service]['nonce']
});
requestObj.global = false;
requestObj.timeout = 30000;
requestObj.success = function ( r ) {
alert ( "Success: " + r );
}
requestObj.error = function ( r ) {
console.log ("FAILURE WITH AJAX Call ( " + JSON.stringify (r) + ")");
}
There's one thing that probably needs explaining. The two references to "my_config" are references to a Javascript variable that I set using Wordpress's wp_localize_script() function. Basically it just provides context about where to find the URL, the NONCE to use, etc. I have tested that the URL and NONCE information is working correctly so that shouldn't be the problem. For example, I put a breakpoint on the browsers debugger on the line after the two references are defined and got these results:
When I call the ajax function it immediately executes the success function and sends in the value of 0. Looking at my PHP error logs though I can see that the request was never sent. What could be getting in the way of $.ajax(requestOb) from actually sending the request?
UPDATE:
Thanks to Michael's sage advice I realised that I am in fact getting a request to go out but as it's running in a local environment the response is coming back lightening fast. Now I am suspecting this has more to with Wordpress configuration. I have hooked into the wp_ajax_[service_name] but it immediately returns 0. I'll re-ask this question with this new information in the wordpress forum.
You should be using a browser inspector to detect if an ajax request is made. Open up the network tab of any inspector, and you can watch requests as they happen. How is the $.ajax() method being instantiated? You may have an issue with that, as opposed to $.ajax().
Once you've used the inspector, look at the $_POST or $_GET data you're sending in the headers section, and then look at the response. Is the HTTP response code 200? If it's 500, then you probably have an error in your PHP controller that receives the request.
If you have PHP CLI, run this to see if you have a syntax error:
php -l path/to/php/controller.php
If you have a non-fatal error in your file, you'll see the error output in the request response.
Try var_dump( $_REQUEST ) at the top of your php file, too, to make sure that the file is receiving the data, and you can inspect it inside the browser-inspector response.
If you have a problem with the program inside of your controller... you've got yourself a new question to post. :)
At first look, it looks like your URL has spaces around get_action_template. That might be an issue.
Also, passing dataType might help.
If not try getting a JSON response without any parameters and post the output
Ok, i've answered this damn question finally. Arrgh. BIG, BIG THANKS to Mathew to who's troubleshooting skills I could not have done without. Anyway, the problem was in the AJAX request and as a result the Wordpress Ajax manager was never respecting the "hooks" I had put into place on the PHP side.
How was my AJAX request off? I had a POST request but the URL had GET variables hanging off of it. The key variable for Wordpress based Ajax requests is the "action" variable. This is the variable which WP's ajax manager uses to distinguish the various services and is the name that you'll be hooking into.
So in the end, my URL was:
http://mysite.com/wp-admin/admin-ajax.php
and my POST variables included:
action: get-action-template
My wordpress hook is:
add_action ( 'wp_ajax_get-action-template' , 'AjaxServiceManager::ajax_handler' );
My sleepless nights may continue but they won't be related to this damn problem anymore. :^)

Categories