Send REST response on data using CakePhp - php

Hello Im having trouble with a service Im building. Right now I can see the body of the response in json and everything. But a friend who is getting the response on angular using $http.get('url'); seems to be having a hard time getting the data. Im not familiar with angular, so Im not sure how that call works and Im not sure why he cant get the data Im sending him. Here is the code:
$jsonResponse = array(
'success' => 'Llamada exitosa.',
'producto' => $responseproducts
);
$this->response->type('json');
$this->set('data', $jsonResponse);
$this->set('_serialize', 'data');
$json = json_encode($jsonResponse);
$this->response->body($json);
The $responseproducts is the array with the response I want him to get. The URL does return the array on the body when I try it on postman. And I can use the data on a ajax I build on a simple html to see if I could use the url. But for some reason my friend cant get the array on the data of the response. Any ideas what I might be doing wrong?

Hehe I found the answer. Digging a little bit more, it seems he had a problem with CORS availability. I just use the next code I found to let CORS on my service:
//Enabling CORS for CakePHP
public function beforeFilter() {
parent::beforeFilter();
$this->response->header('Access-Control-Allow-Origin','*');
$this->response->header('Access-Control-Allow-Methods','*');
$this->response->header('Access-Control-Allow-Headers','X-Requested-With');
$this->response->header('Access-Control-Allow-Headers','Content-Type, x-xsrf-token');
$this->response->header('Access-Control-Max-Age','172800');
}
As I read on the page where I found this code, not all 5 are necessary. Most of the time it works only with the first one, but test for the rest if necessary. Hope this helps soemone :P

Related

How can I send raw JSON Data in PUT method In Guzzle POST Body?

This should be soo simple but I have spent hours searching for the answer and am truly stuck. I am building a basic Laravel application and am using Guzzle to replace the CURL request I am making at the moment.
actually I want to send data as JSON in request Body , in PUT method ,using Guzzel PHP client. please anyone help me how can i send.
please share complete code , i am new to using it.
According to the doc of guzzle
$response = $client->request('PUT', '/put', ['json' => ['foo' => 'bar']]);
What version of guzzle do you have and what did you try ?

problems with php POST - POST body is empty in login request

I am currently working on an APP that sends a post request to a server to login. The backend developer of my team is a bit slow so I thought why wouldn't I just set up some mock urls for testing the app.
I got a php file for the login which should return me a session when I enter correct data. Unfortunately I am stuck trying to get the JSON i post into some variables.
In fact, i don't see any data i receive. I've tried to use vardump on $_POST, $HTTP_RAW_POST_DATA as wel as file_get_contents("php://input"). I tried to decode the latter two with json_decode.
Some give me String(0) "" others give me NULL. In some cases i just got nothing.
Using retrofit i send a request to /login with a body of
{
"password":"password",
"username":"Marcel"
}
However when what i get as return is nothing. The my php code is only getting the and returning a json object with a session token
if(!empty($_POST["username"]) && !empty($_POST["password"])){
$id= array('SESSION_ID' => 'random_session_token_0015');
echo json_encode($id);
}
This code example does not give me any return. Using print_r($_POST); i will get an empty array like array().
$json = file_get_contents('php://input');
$object = json_decode($json);
var_dump($object);
This code example does give me any return, but it is NULL. $HTTP_RAW_POST_DATA had the same result as the latter example.
I'm quite stuck in this problem, anyone there to help?
ps. aks if you need more info
I resolved the same problem by making sure I send the "Content-Type: application/json" header to my Node.js server.
Try
file_get_contents(
'php://input',
false,
stream_context_get_default(),
0,
$_SERVER['CONTENT_LENGTH']
);

Getting raw data using php://input not working

I am having a strange problem and could not figure out how to solve it.I am using webservice from my mobile application to authenticate login details and for that application sends a $_POST data to my api and api returns the data.
Now same code seems to work fine through my mobile but if i test it in postman it doesnt work and my file_get_contents ( "php://input" ) do not return any data.
here is the chunk of code which is not working on my localhost and on server,but the same code works fine on my application. If i request through application than it authenticates the data and let the user log in.
public function getPostdata() {
$post = file_get_contents ( "php://input" );
$data = CJSON::decode ( $post, true );
return $data;
}
Okay, I know it's 2 years later, but I ran into this today while testing with Postman and it was making me crazy. The problem? I didn't have the end slash on the endpoint URL and so a 301 redirect occurred and cleared out php://input.
-.-

CakePHP REST Put/Post not accepting data

I am attempting to write a RESTful service using CakePHP 2.3.5. So far I've successfully created the GET functions for the resource I'm working with. I can send a GET request to example.com/areas.json or to example.com/areas/1.json and it returns the data in my database.
However, I started trying to get the edit function working. I wrote a simple edit method that simply saved the incoming data from $this->request->data. I'm using Postman to test the functionality and sending raw JSON over PUT or POST to example.com/areas/1.json returns a message telling me that the data couldn't be saved. I made the method send me more information when it failed and it tells me that there is no incoming data in either $this->request->data or $this->data.
I've been searching the Internet for solutions to this or similar problems, but everything I have tried has failed so far. I've attempted disabling CSRF checks, disabling the SecurityComponent altogether, and multiple other fixes all involving the security. Changing any of those resulted in black holing the request.
Does anyone have any thoughts on what else I could try to get CakePHP to accept the JSON data into a request? I'll include my edit function below in case that helps.
public function edit($id)
{
$this->Area->id = $id;
$message['request-data'] = $this->request->data;
if ($this->Area->save($this->request->data)) {
$message['response'] = $this->Area->findById($id);
} else {
$message['response'] = "Error";
}
$this->set(array(
'message' => $message,
'_serialize' => array('message')
));
}
First, make sure the Content-Type of the request is application/json.
Second, CakePHP doesn't automatically decode the JSON payload; you have to do it manually. From the manual:
// Get JSON encoded data submitted to a PUT/POST action
$data = $this->request->input('json_decode');

Laravel 3 JSON and jQuery getJSON

I'm trying to get a JSON result from a laravel-project.
I have a jquery app on my webhotel, trying to access my laravel api on another server.
Everytime i use getJSON in my js, I get the following error in firebug:
Object {
readyState=0, status=0, statusText="error"
}
I my laravel controller I'm using this to produce the json:
$article = News::with('Category', 'Author')->find($id);
return Response::json($article, 200, array('Content-Type' => 'application/javascript'));
It would be really great, if someone could point me in the right direction. Maybe it's something about having the jquery app and laravel api on two different servers?
the content type for json should be
array('Content-Type' => 'application/json')
Only the first param should be required. It will set the headers and response code automatically. The other issue is that the model is actually quite a bit more complex then what you probably want to return. Try the following.
return Response::json( $article->to_array() );

Categories