Angular Post to PHP - php

I am trying to post data from Angular to PHP.
Angular Post Request
var body = { "action":"getvouchernumber","vouchertype": vtype, "vmonth": vmonth, "vyear":vyear };
return this.http.post(this.BaseURI+'voucherprocessing.php',body);
Output As Shown In Network Tab of Developer Mode
Headers on PHP Page
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
Getting Data in PHP
$data = file_get_contents("php://input");
Output
But when I try to get any value of the object and set it to a variable, it doesn't work.
$action = $data->action
I also tried doing
json_decode(file_get_contents("php://input"));
but that returns an error too.
In response to #Tiago's post, I added json_decode($data, true) and tried to get value by $data->action which resulted in following
The value is correct in text field but it is being shown as an error.
And if I don't add second parameter to json_decode, it returns still null. The PHP version is 5.6.31

try dumping data variable in php by var_dump($data) and see you are able to receive data in php correctly or not,by viewing the response in console.
Check if you are able to encode formData correctly on angular and use this._http.post("voucherprocessing.php",formDataVariable); to submit form.
Also it may happen relative route for your file may not be working as angular has its own way of setting routes,use absolute route instead like "http://localhost/path/to/your/php/file".

Due to security reasons (everyone has access to the Angular code), Angular doesn't communicate directly with a Database. Instead, it uses HTTP Requests and HTTP Responses to a Server / API (REST, GraphQL) that can be built using PHP (like in your case) but could be using, for instance, NodeJS. Then, this API can interact with the Database (could be doing something different too, like simply uploading files).
When it comes to HTTP Requests to REST API it's important to note that we will need to know the URL (API Endpoint), the HTTP Verb we want to use (in this case POST) and can also possible to send Header ({"Content-Type": "application/json") and a Body (to send some piece of information - note that this won't be possible using the HTTP Verb GET).
In this particular case, you've used the HttpClientModule's post() method to send the data to the server. Will assume you have the right URL given as the first parameter and can also see the body in the second parameter.
So, now the problem can only happen in the PHP side. In order to get the data POSTed from Angular and associate it to a variable, use
$postdata = file_get_contents("php://input");
As this data comes in JSON format and JSON data is not recognized by PHP, you need to then extract it / convert it into an array
$request = json_decode($postdata, TRUE);
So now it should be straightforward PHP Arrays. Of course you can then had conditions / validations throughout the way to ensure these variables ($postdata and $request) always hold data or else give a specific error.
As in your comment to this answer you mention that $request is returning null, there's a question already addressing it from where you can read more about it.

Related

Angular $http executed twice when using headers

I'm developing an ionic project and I'm using header parameters in each POST and GET Request. How ever When I test the project on Android Phone and monitor all requests that come into my server through my android device there are no issues. But when I deploying my ionic project and testing it in my web browser ( Chrome Web Browser ) I see that each request has been executed twice,( one without headers params and without inputs when I use POST method, and the second one is with all params ).
I've solved it in my server if there are no header parameters to ignore the request each time. How can I prevent the duplicated execution for the $http (POST and GET)?
These parameters I've set in the angular.config js file.
$httpProvider.defaults.headers.common['Accept'] = 'application/json; q=0.01';
$httpProvider.defaults.headers.common['Authorization-Token'] = value;
and my PHP service starts with
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type, Authorization-Token");
header('Access-Control-Max-Age: 60');
header('Access-Control-Allow-Methods: ["GET","POST"]');
header("Content-Type: application/json; charset=UTF-8");
Sounds like an OPTION call indeed.
It should be done, and not carry any payload, it is just to check with the server what actions are allowed on the resource before performing the actual call (post/get/whatever).
Check the answer to this similar question : Angular 2 HTTP POST does an OPTIONS call
The first request is the preflight.
This is part of the browser mechanism.
You cannot avoid it.
It all comes down to how browsers manage CORS. When making a cross-domain request in JavaScript that is not "simple" (i.e. a GET request), the browser will automatically make a HTTP OPTIONS request to the specified URL/URI, called a "pre-flight" request or "promise". As long as the remote source returns a HTTP status code of 200 and relevant details about what it will accept in the response headers, then the browser will go ahead with the original JavaScript call
Please look here and here

PHP post server - how does posttestserver.com work?

I am trying to build a post server similar to posttestserver.com and have been runnning into lots of trouble.
The following returns nothing -
do {
$data = file_get_contents('php://input');
} while (empty($data));
header('HTTP/1.0 200 OK');
header('Content-Type: text/html');
var_dump($data);
I have also had a look into the use of sockets but the client should be directed to a URL rather than an ip/port for the clients ease. I suspect that this is what i need to use but am not sure where to start.
For what its worth, the client expects an HTTP 2XX response code from its HTTP POST request, and the client will not attempt submitting the next HTTP POST request while a previous request is still in flight.
Any ideas?
It would seem that you cannot capture and view the POST data in the one browser window.
For what its worth, here is the code that worked in the end -
$data = file_get_contents('php://input');
//do something with the data such as write to file or database
Then you could use the data in another PHP script.

PHP API Content-Type: application/json. Response empty data

Works fine for:
Sending from Android platform to PHP (web service)
Request headers sent with this Content-Type: application/x-www-form-urlencoded
Not working for:
Request headers sent with Content-Type: application/json. no data is received
API is working on same platform but not in cross platform:
Web to web WORKING
Android to web NOT WORKING
In PHP added both header on top:
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
If you compare these two content types application/x-www-form-urlencoded and application/json in a "The first works with PHP, the second doesn't", then you probably expect the data to appear magically inside $_POST in both cases.
This will not happen. PHP only fills $_POST if the first content type is given (alternatively, application/multipart-form-data can be used for everything, especially file uploads).
If you want to use application/json, then you have to implement a parser on the PHP side yourself that reads the HTTP request body and parses it to your liking.
after log search i found my answer..
we need this function to get $_POST response from cross platform (android to web)
file_get_contents('php://input')
OR we can also use this function to get $_POST response
$HTTP_RAW_POST_DATA
here is complete function to get the response.
$data = urldecode(file_get_contents('php://input'));
echo $data;

Receive JSON object from HTTP Get in PHP

I am trying to implement a php client that sends an HTTP GET to the server which sends back a JSON object with the return information. I know how to decode the JSON once my php script has received it, but how would I go about actually getting it?
EDIT: Note - I send the server an HTTP GET, and it generates and sends back a JSON file. It is not a file sitting on the server.
Check out file_get_contents
$json = file_get_contents('http://somesite.com/getjson.php');
Browsers act differently based on what the server responds. It does not matter what type of request you make to the server (be it GET, POST, etc), but to return JSON as a response you have to set the header in the script you make the request to:
header('Content-Type: application/json;charset=utf-8;');
And then echo the JSON string, for example:
//...populating your result data array here...//
// Print out the JSON formatted data
echo json_encode($myData);
User agent will then get the JSON string. If AJAX made the request then you can simply parse that result into a JavaScript object that you can handle, like this:
//...AJAX request here...//
// Parse result to JavaScript object
var myData=JSON.parse(XMLHttp.responseText);
The header itself is not -really- necessary, but is sort-of good practice. JSON.parse() can parse the response regardless.

How to get json data coming from another domain?

I want to use the google images api. In the past when I worked with json I simply used the ajax function to get the json from my own server. But now I will be getting it from an external domain:
https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy monkey&v=1.0
Obviously I can't load this using js since its not from an internal url. So in these cases how does one work with json data. Are you supposed to load it via CURL using a server side script or is there another way?
You can make use of JSONP by adding a callback GET param.
https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=hello
Then you can request it with jQuery's $.getJSON().
$.getJSON('https://ajax.googleapis.com/ajax/services/search/images?q=fuzzy%20monkey&v=1.0&callback=?', function(response) {
console.log(response.responseData);
});
jsFiddle.
You must use Cross Origin Resource Sharing (CORS http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing)
It's not as complicated as it sounds...simply set your request headers appropriately...in Python it would look like:
self.response.headers.add_header('Access-Control-Allow-Origin', '*');
self.response.headers.add_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
self.response.headers.add_header('Access-Control-Allow-Headers', 'X-Requested-With');
self.response.headers.add_header('Access-Control-Max-Age', '86400');

Categories