I'd like to generate a JavaScript file for JSONP data exchange.
All fine, but I need / want to set the header as :
header("Content-Type: text/javascript");
or
header("Content-Type: application/javascript");
Is this possible in a response from a controller in Laravel 4, or do I need to create a view and set the header with PHP?
I'd like to output something like:
var obj = JSON.parse('{"item1":"value1","item2":"value2"}');
// then do whatever with the object
$('#somediv').html(obj.item1);
Thanks for your help in advance
Okay, looks like I have to answer my question myself :-). Thanks to #terrylow for trying though.
Here is the way to change the header of my response using my function in my controller
public function javascriptResponse(){
$statusCode = 200;
$content = "var obj = JSON.parse('{\"item1\":\"value1\",\"item2\":\"value2\",\"some\":\"whoaevaNew\"}');";
$response = Response::make($content, $statusCode);
$response->header('Content-Type', 'application/javascript');
return $response;
}
variable content can also be filled with a view:
$content = View::make('tools/jsonp_resonse'); // also possible with view
Hope that will help someone...
you can use this method provided by laravel
return Response::jsonp($callback, $data,$status, $header);
Related
I have a function developed by PHP that at the moment all I want it to do is to return the value of the variable $_POST['token']
I tried:
public function actionGetuserbytoken() {
$data = json_decode(file_get_contents("php://input"), TRUE);
$id = $data['token'];
return $id;
}
Or I also just tried:
public function actionGetuserbytoken() {
return $_POST['token'];
}
I tried doing the POST with Insomnia to check what is going on:
I feel this is a very absurd question but I can't understand why I can't get the value of the POST in either of the two ways.
The php://input stream can only be read once per request. Yii is likely reading the payload before you can, which means that the body is empty when you read the data.
Instead of using php://input, try the following:
$data = json_decode(Yii::app()->request->getRawBody(), true);
I am trying to get my webhooks header (Woocommerce webhook),
I am retrieving the body with file_get_contents('php://input'), although this only gives the body according to http://php.net/manual/en/wrappers.php.php
I also found this thread: link, but I can't figure it out.
Is there any other function that gives me back the header?
My function looks like this:
public function webhook(Request $request) {
$json = file_get_contents('php://input');
Storage::disk('local')->put('file.txt', $json);
}
Edit: Other things I tried:
public function webhook(Request $request) {
$json = file_get_contents('php://input');
$headers = getallheaders();
Storage::disk('local')->put('file.txt', $headers['Content-Name']);
}
This sets the webhook to "Disabled", I suppose this throws an error for some reason.
apache_request_headers is not changing the status to "Disabled" but is returning an empty file.txt
Use getallheaders():
This function exists for the sole purpose of retrieving request headers:
$headers = getallheaders();
var_dump($headers['Content-Name']);
Is there any other function that gives me back the header?
Assuming you use Apache, then: http://php.net/apache-request-headers
For the ones who might be facing the same problem in the future, I found the following solution:
public function webhook(Request $request) {
$json = file_get_contents('php://input');
Storage::disk('local')->put('file.txt', $json);
Storage::disk('local')->put('request.txt', Request::header('x-wc-webhook-source'));
}
Main url solution: Link
I am writing a restful webservice for my android app, and i am using flight php framework to route url. i have written a simple code shown below to return a json payload posted to the server instead it returns an html content type instead of a json. Please guys how to i change the response content-type to json, thanks in advance.
My code here:
include ('lib/flight/autoload.php');
include ('TestClass.php');
use flight\Engine;
$app = new Engine();
$app->_route('/', 'hello');
$app->_route('/user', array('TestClass', 'hello'));
$app->_start();
function hello(){
$request = Flight::request()->getBody();
echo json_encode($request);
}
#julianm is almost correct.
Flight::json($response);
But echo function is not needed.
source: http://flightphp.com/learn#json
header( "Content-type: application/json" );
echo json_encode( $request );
To send a JSON response with FlightPHP, you can use something like:
$response = array('id'=>1, 'website'=>'http://slidehunter.com');
echo Flight::json($response);
I have problem with setting headers in ZF2. My code looks like this:
public function xmlAction()
{
$headers = new \Zend\Http\Headers();
$headers->clearHeaders();
$headers->addHeaderLine('Content-type', 'application/xml');
echo $file; // xml file content
exit;
}
But headers are still text/html. I can set the proper header with:
header("Content-type: application/xml");
but I would like to do it with Zend Framework. Why code above doesn't work?
What you are doing is setting headers in a ZF2 Response object, but this response is later on never used. You are echoing a file and then exiting, so there is no chance for ZF2 to send the response (with its headers).
You have to use the response to send the file, which you can do like this:
public function xmlAction()
{
$response = $this->getResponse();
$response->getHeaders()->addHeaderLine('Content-Type', 'application/xml');
$response->setContent($file);
return $response;
}
The idea of returning the response from a controller method is called "short circuiting" and is explained in the manual
Try -
public function xmlAction()
{
$this->getResponse()->getHeaders()->addHeaders(array('Content-type' => 'application/xml'));
echo $file; // xml file content
exit;
}
I'm using Zend Framework 1.x for my project. I want to create a Web service return only JSON string for the caller function. I tried to use Zend_Controller_Action and applied those ways:
1.
$this->getResponse()
->setHeader('Content-type', 'text/plain')
->setBody(json_encode($arrResult));
2.
$this->_helper->getHelper('contextSwitch')
->addActionContext('nctpaymenthandler', 'json')
->initContext();
3.
header('Content-type: application/json');
4.
$this->_response->setHeader('Content-type', 'application/json');
5.
echo Zend_Json::encode($arrResult);
exit;
6.
return json_encode($arrResult);
7.
$this->view->_response = $arrResult;
But when I used cURL to get result, it returned with JSON string surrounded by some HTML tags. Then I tried to user Zend_Rest_Controller with the options above. It still did not success.
P.S.: Most of those ways above are from the question which had been asked on Stack Overflow.
I Like this way!
//encode your data into JSON and send the response
$this->_helper->json($myArrayofData);
//nothing else will get executed after the line above
You need to disable the layout and view rendering.
Explicit disable layout and view renderer:
public function getJsonResponseAction()
{
$this->getHelper('Layout')
->disableLayout();
$this->getHelper('ViewRenderer')
->setNoRender();
$this->getResponse()
->setHeader('Content-Type', 'application/json');
// should the content type should be UTF-8?
// $this->getResponse()
// ->setHeader('Content-Type', 'application/json; charset=UTF-8');
// ECHO JSON HERE
return;
}
If your using the json controller action helper you need to add a json context to the action. In this case the json helper will disable the layout and view renderer for you.
public function init()
{
$this->_helper->contextSwitch()
->addActionContext('getJsonResponse', array('json'))
->initContext();
}
public function getJsonResponseAction()
{
$jsonData = ''; // your json response
return $this->_helper->json->sendJson($jsonData);
}
Your code would need to disable the layout as well in order to stop the content being wrapped with the standard page template. But a much easier approach would just be:
$this->getHelper('json')->sendJson($arrResult);
the JSON helper will encode your variable as JSON, set the appropriate headers and disable the layout and view script for you.
It is much easier.
public function init()
{
parent::init();
$this->_helper->contextSwitch()
->addActionContext('foo', 'json')
->initContext('json');
}
public function fooAction()
{
$this->view->foo = 'bar';
}