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() );
Related
I am trying to post some data using a Guzzle Client Http request in Laravel. But for some reason the server respons with the message that it can't find the property Id in the JSON object, while the property Id is clearly in the request. The Guzzle documentation says that assigning the array to a json property in the request will result in a Json object being sent.
$url = "https://blablabla.com/api";
$key = "1234";
$data = [
'Id' => "4"
];
$response = Http::withHeaders([
"Authorization" => $key
])->post($url, [
'json' => $data
]);
Now I have tested the api in Postman and don't experience any problems. I even use the same api in a different php application using curl and it works perfect. So obviously there is something wrong with lines of code above and not with the api. I have tried different things but nothing works.. I have a feeling that the solution is so simple.. but for the last 6 hours I couldn't figure it out.. So please help before I go crazy :)
Laravel documentation on page HTTP Client says: "By default, data will be sent using the application/json content type". So you don't need to use 'json' property in post data. Just sent it directly: ->post($url, $data).
I have been writing an API using Symfony as the backend, a plugin written by a third party is sending certain data to an endpoint, the endpoint is then to return a json encoded response, however following the instructions as set out in the current symfony documaentation(https://symfony.com/doc/current/components/http_foundation.html) the return value is displayed twice and the response is not well formed and outputs like string
The original method that I wrote had calls to a database to validate a token, store a bookmark and display the result of the backend process, however when getting down to brass tacks and removing everything but the response building; it is obvious that this is where the problem lies. The method uses this snippet, though for clarity I have not included the database processing and used the posted values as the return array, the result is the same if it is the post or processed data, the output displays twice.
$token = $request->request->get('token');
$bookmark = $request->request->get('bookmark');
$data = ['token' => $token, 'bookmark' => $bookmark];
$response = new Response();
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->setContent(json_encode($data));
$response->send();
return $response;
What I was expecting was a single json response but what is returned is a double string of the json output
e.g. if I posted these values to the above snippet:
token: ksjdbvqpi8e7rqp7evbprb
bookmark: http://www.google.com
the return result is
{"token":"ksjdbvqpi8e7rqp7evbprb", "bookmark":"http:\/\/www.google.com"}{"token":"ksjdbvqpi8e7rqp7evbprb", "bookmark":"http:\/\/www.google.com"}
when what I was expecting was just
{"token":"ksjdbvqpi8e7rqp7evbprb", "bookmark":"http:\/\/www.google.com"}
I have no idea at the moment why it is displaying twice, any help is as always appreciated.
Thanks
$response->send(); is the line that should be removed.
As you already return object of class Response symfony will take care to output this response to browser, you don't need to do it manually with send().
I use Unirest for PHP to do some HTTP Requests. Everything works fine, until I want to pass a fairly complex JSON to my Node.js router.
First I do a GET request that returns a JSON Object, then I extend this JSON object (needs to be done, I know it sucks) and want to feed it back into my other http POST request... and here is where the trouble starts:
I echoed the JSON that is returned and copied the output into postman -> works fine. If I want use the JSON directly in PHP in next request:
$teamsMemberOf is the variable which is containing the GET response.
$headers = array("Accept" => "application/json");
$newBody = '{"team":'.$teamsMemberOf->raw_body.'}';
$relevantBoxesAmount = Unirest\Request::post("http://localhost:3001/my/route/".$result['_id']."/get-something-from-server", $headers, $newBody);
and it doesn't work.
Error is 500 and 'Cannot read property '0' of undefined' which is certainly related to something in the JSON object.
Does someone have an idea how to fix it?
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
I'm new to back end development and i'm trying to learn back end development. What i want is to create a backend using PHP which should output a json response.
For example if there's a field called First Name in my backend,and when i update that field, I want the updated name in a json response so i can display the outputs in my android app.
Sorry for being a noob.
Just point me some tutorials to learn and any further tips would be appreciated.
Outputting JSON is quite simple, you first set an HTTP Response Header and then print the JSON content. The response header is to tell the receiving application (client) what type of data to expect.
A simple example:
header('Content-Type: application/json');
echo json_encode(array(
'name' => "Your Name"
));
You didn't mention if you were using a framework or not, but frameworks like Laravel or Lumen make this kind of thing easy.
Here's a tutorial that might be of use to you.