I'm new in REST API. I'm building up a test environment and trying to make a handshake between Rest API and Client side PHP.
My JSON data is at
http://localhost:50417/api/device
the data is like:
[
{"Truck_ID":1,"Company":"Food Mall","Distance":2000},
{"Truck_ID":2,"Company":"Food Mall","Distance":4000},
{"Truck_ID":3,"Company":"Food Mall","Distance":3050}
]
I'm trying to act like a client, use PHP to get the data, and put the data in an array. What I tried on client side which is http://localhost:8080 is
<?php
$url = "http://localhost:50417/api/device";
$response = file_get_contents($url);
echo $response;
?>
I also tried js like
<script type="text/javascript">
$(document).ready(function(){
$.getJSON("http://localhost:50417/api/device",
function(data){
alert (data) // this will show your actual json array
});
});
</script>
But no matter what I tried, I always get a "No 'Access-Control-Allow-Origin' header is present on the requested resource." What could be the problem? How clients generally get the data from server using REST API? Thank you.
allow cross origin requests
Enable it in the .htaccess by putting the below line
Header set Access-Control-Allow-Origin "*"
or try from php
<?php
header('Access-Control-Allow-Origin: *');
$url = "http://localhost:50417/api/device";
$response = file_get_contents($url);
echo $response;
?>
Related
I am trying to send data from my react native app to my remote app server written in PHP, here is the code snippet it:
fetch('http://172.20.10.2/fyp/products.php', {
method: 'POST',
body: JSON.stringify({
//passing input data to server
cid: this.state.category_id
})
Here is the PHP code where I am trying to receive data from my react native app:
// Getting the received JSON into $json variable.
$json = file_get_contents('php://input');
// decoding the received JSON and store into $obj variable.
$obj = json_decode($json,true);
$obj_id = $obj['cid'];
For debugging, I am printing $obj_id to a .txt file but it is printing nothing which indicates I am not receiving the data in my server. How do I resolve this?
At the very top of your php file add
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
And try again!
I am working on Angular4 Project.
For testing, first I had done the get request to any json api and its worked well.
Now I am working to connect the php file and testing it. In test.php I had
echo "string";
Now in console I am getting this error:
XMLHttpRequest cannot load http://localhost/php-file/test/test.php.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:4200' is therefore not allowed
access.
I also attached screenshot of it. I had googled it but unable to get any solution for this.
then I had edited the test.php like below. Is it right way to do so?
<?php
header("Access-Control-Allow-Origin: *");
$data = ['news','dfdf','ddd'];
echo json_encode($data);
?>
This is how you need to do. You need to include headers in angular as well.
import { Http, Headers, Response, RequestOptions } from '#angular/http';
headers = new Headers();
requestOptions = new RequestOptions();
this.headers.append('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
this.headers.append('Cotent-Type', 'application/json');
this.requestOptions.headers = this.headers;
return this.http.post("http://localhost/php-file/test/test.php", this.requestOptions).map(res => res.json());
This is how you should make post request. Make sure to subscribe this call and then you can get data from return.
I hope it helps.
We are trying to call from index.html on local, a simple PHP file hosted on webhost000 to receive a response. PHP file is:
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
echo ($name);
}
?>
We would like to simply input a character on a textbox in html.index and receive the same character as response from the php. We are using an ajax call to do this in html file:
<script>
$(document).ready(function() {
$('#name').keyup(function() {
var name = $('#name').val();
var request = $.ajax({
url: "https://nedo93.000webhostapp.com/phpdemo.php",
method: "POST",
data: { name : name },
dataType: "html"
});
request.done(function( msg ) {
alert( "Request done: " + msg );
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
</script>
(The remaining html should not be important, it works perfectly, tested and retested)
If we try to debug this we can see that the file is found, the request is sent, but we can't receive a response: screenshot
If we use this browser function instead, we can send data and receive a response without a problem, don't know if this can help.
Thank you in advance if you can answer this question.
This is because your PHP script is hosted on a different server and your AJAX call code is on local.
For AJAX to run, there is same-origin policy. Under this policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin (means both are on same domain). Read more about same origin policy here.
The same-origin policy prevents some Ajax techniques from being used across domains, although the W3C has a draft of the XMLHttpRequest object that would enable this functionality. Methods exist to sidestep this security feature by using a special Cross Domain Communications channel embedded as an iframe within a page, or by the use of JSONP, websockets, cross-domain messaging or cross-domain resource sharing.
So in short you will not be able to access the PHP request residing on a 000webhost server to be accessed using AJAX code on local.
Either you host the AJAX code on the same 000webhost domain as well or enable cross-domain resource sharing on 000webhost domain where your PHP code is running.
As far I know, 000webhost is a free server and doesn't supports these changes. So you will have to either get a better server or test this all in a local.
Also as you mentioned in your query, all HTTP requests like GET, POST, PUT works cross domain. But for AJAX, no its not so straight forward.
Hope this helps!
use json_encode
your code should be....
<?php
if (isset($_POST['name'])) {
$name = $_POST['name'];
header('Content-Type: application/json'); //just used as info for your application
echo json_encode($name); //encode to JSON object
}
?>
after that do JQuery validation for checking Json reply (specially for error).
im developing an API with FlightPHP microframework and I can't set an HTTP response code for my routes.
I can set this and works perfectly:
header('HTTP/1.0 500 Error');
But I want use the native function http_response_code() from PHP. This one don't do anything.
I want to use this because that I don't have to manually type the error message.
To return a HTTP response code using Flight, you can do it like this :
Flight::route('GET /', function(){
Flight::json($data, $code = 500);
});
Where $data is the variable that leads to the array you want to send in json.
If $code is not set, then the default returned HTTP response code is "200".
https://github.com/mikecao/flight/blob/e25f023d4377a2b99b4be8bf7977f3fc0f8089c8/flight/Engine.php#L500
from flight php
Flight::json($data, [$code], [$encode], [$charset], [$option]) // Sends a JSON response.
Flight::jsonp($data, [$param], [$code], [$encode], [$charset], [$option]) // Sends a JSONP response.
I had a similar problem, to send my own headers, I do so:
$code = 404;
Flight->before('stop', function(&$params) use ($code) {
$params[0] = $code;
});
I've been debugging this for hours. Tried to set the header etc but no luck!
My controller
$http({
url: 'http://myphp.php/api.php',
method: "POST",
data: {'wtf':'test'}
})
.then(function(response) {
console.log(response);
},
function(response) { // optional
// failed
}
);
and my php
<?php
echo "test";
echo $_POST["wtf"];
?>
In my network tab this is how it look like
Not sure what's wrong man, really exhausted, I'm stuck for hours! Why my $_POST['wtf] didn't echo?
$http is serializing the data to JSON in the request body but PHP's $_POST is looking for key/values parsed from posted form data. These are two different mechanisms for posting data so you need to choose one and use that mechanism on both sides.
You have two options to solve this:
In your PHP code, parse the request body as JSON data and then use that object to retrieve your data. See this StackOverflow question for more information.
Modify your $http request to post the data as form data. See this StackOverflow question for more information.
$http.post (by default) does not send the data as key/value pairs. It sends it as post request.
Therefore, in your php script you should consume it like this:
$input = file_get_contents('php://input');
And then parse it like this:
$data = json_decode($input, true);