Backend can't get POST from javascript fetch API [duplicate] - javascript

I'm using PHP, ExtJS and ajax store.
It sends data (on create, update, destroy) not in POST or GET. In the Chrome Console I see my outgoing params as JSON in the "Request Payload" field. $_POST and $_GET are empty.
How to retrieve it in PHP?

If I understand the situation correctly, you are just passing json data through the http body, instead of application/x-www-form-urlencoded data.
You can fetch this data with this snippet:
$request_body = file_get_contents('php://input');
If you are passing json, then you can do:
$data = json_decode($request_body);
$data then contains the json data is php array.
php://input is a so called wrapper.
php://input is a read-only stream that allows you to read raw data
from the request body. In the case of POST requests, it is preferable
to use php://input instead of $HTTP_RAW_POST_DATA as it does not
depend on special php.ini directives. Moreover, for those cases where
$HTTP_RAW_POST_DATA is not populated by default, it is a potentially
less memory intensive alternative to activating
always_populate_raw_post_data. php://input is not available with
enctype="multipart/form-data".

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).
... the values will be sent as part of the request parameters as
opposed to a raw post (via docs for encode config of Ext.data.writer.Json)
UPDATE
Also docs say that:
The encode option should only be set to true when a root is defined
So, probably, writer's root config is required.

Related

fetch formdata response from php server

I understand that fetch() response lets you receive formData from a server. I searched for an example that implements this functionality but I didn't find a single one. All examples talk about uploading (posting) formData from a client to a server, but not vice versa. This doesn't explain the .formData() method of the response.
So, could you please direct me to any link that has an example that receives a form data from a PHP server using the .formData() method of a fetch() response.
Thank you
https://developer.mozilla.org/en-US/docs/Web/API/Body/formData demonstrates the basic idea:
response.formData()
.then(function(formdata) {
// do something with your formdata
});
But it's very unusual for a server to return data in formData format - I've never seen that happen. It's not actually a very convenient format when it's serialised. Normally a server will return plain text, HTML, JSON or XML (or binary file data, of course).
The "note" in yellow at the top of the documentation explains what it's mainly used for. It says:
This is mainly relevant to service workers. If a user submits a form
and a service worker intercepts the request, you could for example
call formData() on it to obtain a key-value map, modify some fields,
then send the form onwards to the server (or use it locally).
(It's important to realise that this can read from the body of an outgoing request as as well as an incoming response. And also that the comparable text(), json() blob() etc methods can all be used in both directions too - these methods are attached to the Body object. Both requests and responses can contain a Body. So actually these methods don't care if it's a request or a response, they simply try to read from the Body of whatever it happens to be.)

Why is my $_POST empty but file_get_contents('php://input') is not?

When I POST data to my server using a regular old form submit I can pull that data from the $_POST variable, but when POSTing JSON data via AJAX I need to access it via file_get_contents('php://input'). Why is that? In both cases I am using the POST method, are there some explicit headers I should be setting on my AJAX call? I have only ever come up against this problem on the current development server and have never had to use file_get_contents('php://input') before. Is there a server setting somewhere? Can I change this behaviour with a .htaccess?
Add this to the top of your .php file:
$_POST = json_decode(file_get_contents("php://input"), true);
so that the contents will be property decoded and available. After that, you can access individual keys as usual.
So as far as I have been able to find out, this has something to do with the way the data is received by the server - PHP can't natively parse JSON. Sending plain old JSON objects from Javascript to PHP will result in PHP not knowing what to do with the datatype, and thus it won't be able to prepopulate the appropriate global variables.
In order to get around it I added a check to my ajax wrapper function that intercepts the JSON, encodes is as a FormData object and shoots that off to the server instead.

When to use POST method when using AJAX explanation

I am learning about AJAX using W3school resources, and there is a phrase in this URL that I do not understand: http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
It is about when POST should be used when using AJAX. It says:
GET or POST?
GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
A cached file is not an option (update a file or database on the server).
Sending a large amount of data to the server (POST has no
size limitations).
Sending user input (which can contain unknown
characters), POST is more robust and secure than GET.
What does, A cached file is not an option (update a file or database on the server). mean?
if a file is cached it is stored locally on the clients machine which means that the data is already present and there is no need to go get it from a server. The reason this isn't an option for the post (it is but not best practice) is because the posts job is to send data to the server with the intention of updating a record or a file (sometimes if it's a really small change to the configuration of the server you would store it in a .json or .config or .txt file. This could be a post to update that file) / or database record.
The post will hide the data being sent (kind of, you won't see it in the URL unlike a GET Request which will show the name=value pairs in the URL). Post request is meant to update a piece of data.
It's impossible to update the server data with the local cached data - because if you update the local file/data it's not updating on the server, which is accessed via RESTful CRUD (GET/GET:ID/POST/PUT/DELETE) (Create, Read, Update, Delete) patterns

Pros and cons of parameterizing angular request

I'm a full-time backend developer just starting to learn angular for some of my own projects.
By default it seems angular $http requests are sent as JSON strings. I am currently overriding the transformRequest method to parameterize it like jquery. Its more convenient for my backend framework (Phalcon PHP) to receive it this way.
Before I commit to this path, are there any cons to structuring it this way? Any problems unit testing or using third-party modules?
Edit
To clarify, angular sends POST as JSON string in the body. jQuery and other frameworks I've used send as form-urlencded like:
Name=Jonathan+Doe&Age=23&Formula=a+%2B+b+%3D%3D+13%25%21
http://en.wikipedia.org/wiki/POST_%28HTTP%29#Use_for_submitting_web_forms
Which, perhaps due to the content header populates the $_POST global in php (I assume) with the form data;
I would recommend you to stick to the JSON format and send data in JSON request body instead of key=value param pairs. You can receive JSON cleanly with Request::getJsonRawBody() in Phalcon.
The main difference is that POST vars format allows you to send key=value pairs of data. When it comes to more complex structures (arrays, associative arrays, nested objects and so on), you will start to have problems which you will have to solve some way. It won't happen if you send JSON objects in POST/PUT request bodies. And, of course, you get serializing and deserializing OOTB in both AngularJS and Phalcon.
You should strongly consider key=value params for GET parameters only and JSON data for everything else. Obviously, you can mix those two (I mean i.e. sending new content for your article as PUT request with JSON body, but specifying article id in URL like /article?id=123).
You may be also istresed in reading REST API: Request body as JSON or plain POST data?.

using backbone to put data into rest server

I have a question.
If i have a model named Input. It contains model Invoice and Collection InvoiceDetailCollection.
I modified the backbone.js specifically create:"POST" into create:"PUT" inorder to allow PUT since my service doesn't use POST.
If i were to use Input.save() What should my server expect as a request? I mean already have set a service method to expect string since if i expect string i can't use the input.save();
What should be the right parameter i should expect on my server side if i were to use the Input.save() method of backbone.js
By default, Backbone sends application/json data and the server should expects JSON data. You'll want to decode it. I use PHP and middleware that automatically json_decode($data) and turns it into an associative array for me to manipulate.
If this isn't possible, (can't take JSON data) I think what you want is to use emulateJSON It will serialize your data and send it as application/x-www-form-urlencoded like an HTML form.
http://documentcloud.github.com/backbone/#Sync-emulateJSON

Categories

Resources