PHP back-end to output a JSON response - php

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.

Related

Send REST response on data using CakePhp

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

laravel 4 why send content-type when sending json?

In the book of laravel I read, and also my co-worker who has experience with laravel said that generating JSON I should in laravel way.
Why do I need to do this:
Route::get('markdown/response', function()
{
$data = array('iron', 'man', 'rocks');
return Response::json($data);
});
As I read it sends also content-type header when using this.
When I was using codeigniter I used to do simply this:
echo json_endode($data);
and never ever ever had any problems. Even if it is not set content type. Actually I dont know maybe php sets it automatically, but since I did not have problems, I did not care.
And when using 'new' technology I really want to know why it is better than good old one.
With respect, by not providing a content-type header, you were doing it "wrong" when coding in CodeIgniter.
Most clients (browsers, ajax requests, especially jQuery) can still can guess how to handle the response correctly and so probably "just worked" for you. You were likely always implicitly returning a Content-Type: text/html with your response, which is a default header in CodeIgniter.
You should always return a proper content type with your HTTP responses so the consuming client knows how to treat this content. Note that this is a mechanism of HTTP as defined in specification, not specific to any framework or even a language.
Response::json()
The above code is just a convenience function, where Laravel will automatically set the application/json header for you, as well as convert an array of data into JSON format. The only effective difference from your CodeIgniter code is the setting of the header, as you've pointed out.
It's worth noting that the Response object extends Symfony's response object, which is very "powerful" - in other words, it's a very good implementation of the HTTP protocol.
The response object returned from Response::json (and other Response static methods) are highly modifiable.
$response = Response::json($data);
$response->header('Content-Type', 'application/json');
return $response;
You can check for more available methods in the Laravel and Symfony code API.
http://laravel.com/api/class-Illuminate.Http.Response.html
http://api.symfony.com/2.1/Symfony/Component/HttpFoundation/Response.html
Just because it worked doesn't mean it wasn't wrong. JSON isn't HTML, so text/html is an inaccurate Content-Type for it.
Sending the correct header means libraries like jQuery understand what sort of data they're getting back, and thus are able to handle it on their own without guidance. Browsers may also do things like pretty-printing the JSON data or making it otherwise easier to read.
Depends what you are trying to do with the route. if you only want to return json data you can just return json_encode($data) and that will work, To actually return a json response for use with something like an ajax request you need the headers set properly or the accepting route just thinks its getting a string. Response::json is for setting the response which sets the headers appropriately.

Correct way to POST JSON data from Android to PHP

I have seen many tutorials and questions using the following method to send JSON object to PHP from Android. For example this wordpress blog, this codeproject tutorial and some answers on stackoverflow like these.
All of these tutorials and answers use HTTP header to send data(body) to PHP like this.
....
// Post the data:
httppost.setHeader("json",json.toString());
....
As a programmer we all know that headers are not meant to carry data(body). Headers should only carry metadata.
So, is there a correct way to send JSON data to PHP from Android which does not involve setting data in header?
If you use nativ lib without Volley, here is dummy with HttpClient:
httpClient = createHttpClient();
//You wanna use POST method.
mPost = new HttpPost(_urlStr);
//Head
mPost.addHeader(new BasicHeader("Content-Type", "application/json"));
//Body
((HttpPost) mPost).setEntity(new StringEntity(jsonText));
//Do it.
client.execute(mPost);
Try to use Volley: https://github.com/ogrebgr/android_volley_examples/blob/master/src/com/github/volley_examples/Act_SimpleRequest.java
Here is a simple tutorial to send and receive JSON objects in Android.

slim php (explanation of "request body" documentation)

I am working with Slim PHP for the first time and I am trying to understand one of the concepts. In the slim PHP documentation, it states:
Request Body
Use the request object’s getBody() method to fetch the raw HTTP request body sent by the HTTP client. This is particularly useful for Slim application’s that consume JSON or XML requests.
<?php
$request = $app->request();
$body = $request->getBody();
My question is, what is "the raw HTTP request body"? Is it just a string of all the HTML in the body of the page? What format is it stored as? What would echo $body look like? If I do var_dump($body) I get string(0)"". How do I use it?
I'll just make it an answer rather than comment...
Raw request data is what's submitted from the browser as a body of the POST request.
http://en.wikipedia.org/wiki/POST_%28HTTP%29#Use_for_submitting_web_forms
Technically it can be used to read the data from usual html forms, but this doesn't make much sense as PHP does this good enough and places everything into $_POST.
You may need to read raw data if you have some javascript that sends XML or JSON data, which is not natively accepted by PHP.
The terms you ask for are defined in the RFC2616: Hypertext Transfer Protocol -- HTTP/1.1.
For example, in particular what a Message (Request/Response) Body is: 4.3 Message Body.
If those RFCs are new to you, grab that one an read it from top to bottom and try to understand as much as possible. You'll start to see how those things in the internet work.
Also there is version 2.0 is in the pipe with some changes:
Hypertext Transfer Protocol version 2.0 (Draft 04)
Just in case you're interested.

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