I want to capture every information passed to view using the afterFilter. So I need to know:
all variables
session flash
the action executed (last action)
the view called
This is because I need to check if the request is json or not for change the response.
Currently I use afterFilter like this:
public function __construct()
{
// Here's something that happens after the request
$this->afterFilter(function() {
});
}
What I want is: use the afterFilter method in BaseController to capture all events/actions and then decide if the request is json or not.
If you need more information, comment please.
And sorry for my english
Do you need to know if JSON or if AJAX? If AJAX then just use:
if (Request::ajax())
{
//
}
You may use Request::wantsJson() to determine if the request is asking for json in return using:
// In app/filters.php
App::after(function($request, $response)
{
if($request->wantsJson()) {
//...
}
});
In this case, Laravel (through Base/Symfony class) checks if the Accept header is set and if that is application/json.
Related
I can not get values sent from post method, using http request.
I am getting values using get method, but I need to get it using post method.
I am not using any view, I want to call http url, and send some data in my controller using post method.
This is how my controller looks like,
namespace Spaarg\eMenuApi\Controller\Index;
class Products extends \Magento\Framework\App\Action\Action
{
public function __construct(\Magento\Framework\App\Action\Context $context)
{
return parent::__construct($context);
}
public function execute()
{
//$token = $this->getRequest()->getPostValue();
$token = $this->getRequest()->getPost();
}
}
I am new to magento 2, and I don't understand what is the problem.
It will be great if someone can help.
It probably has to do with the Content-type of the http request, where Magento only understands Json and Xml (this is explained here). If you're using a different Content-type in the request or your data doesn't match the type declared in the header, then getPost() will not work.
As a fallback, you can always get all the POST data by using the following way:
public function execute()
{
$postData = file_get_contents("php://input");
}
Keep in mind that this will get the raw string, so you will likely need to process it accordingly before using it (for example with json_decode() or something like that).
For more information about this, check this SO question.
I'm new to Slim and PHP, but I'm trying to do a simple rest API with Slim. It's working, but I don't know if I'm doing it the right way and I cannot find another way to do it.
For example, I've a route like that:
$app->get('/contacts', '\Namespace\Class:method');
The method:
public function searchContacts($request, $response) {
return Contact::searchContacts($resquest, $response);
}
So, the unique way I found to access request and response from other classes is by passing the objects as params. Is it correct or is there a better (right) way to do it?
I think your way is not good.
Controller should process request and return response.
Your model(Contact) should'nt process requests. It should take needed params and return data.
Simple example:
public function searchContacts($request, $response)
{
// to example, you pass only name of contact
$results = Contact::searchContacts($request->get('contactName'));
$response->getBody()->write(json_encode($results));
return $response;
}
You don't need access to Request and Response objects from another classes. If it required, possible your architecture is wrong.
Good example from official site: http://www.slimframework.com/docs/tutorial/first-app.html#create-routes
the simplest way is to get the values from params and recieved the response in method.
$app->get('/contacts', function (Request $request, Response $response) {
$Contactname = $request->getAttribute('contact');
//You can put your search code here.
$response->getBody()->write("Contact name is, $name");
return $response;
});
I want to make an Ajax search request agains an API and get the data returned to my PHP file, right now I'm using Javascript and jQuery to do the job. But I want to let PHP do all the job, simply because I don't want my API key to be public and I may want to cash the data in a database further on. It seems that it should be simple, but I just can't figure out how to do it clean, call javascript and return or how to "integrate" it with PHP.
I am doing my PHP in the MVC pattern, like so:
Controller called from "mastercontroller/index":
class SearchController {
public function DoControl($view, $model) {
$ret = "";
$ret .= $view->GetSearchForm();
if($view->TriedToSearch()) {
if($view->GetSearchString()) {
$ret .= $model->CheckSearchString($view->GetSearchString());
} else {
// Didn't search for anything
}
} else {
// Didn't press the search button
}
return $ret;
}
}
My view is returning an HTML form, checking if submit is pressed and also returning the searchstring, that I am sending in to my Model above.
Model:
class SearchModel {
public function CheckSearchString($searchString) {
// 1. Call Googlebooks api with the searchstring
// 2. Get JSON response to return to the controller
// 3. The controller sends the data to the View for rendering
}
}
I just can't figure out how I should do it.
I'm not entirely sure, but you seem to be asking how to perform an AJAX request without JavaScript. You can't do that -- it's not possible to use the XmlHttpRequest object without JavaScript. That's, according to legend, the origin of the "J" in the AJAX name.
It sounds like you need to use REST to call specific API's. RESTful state allows you to use web services to return specific data according to a predefined API. Data can be returned in XML or JSON.
You can do this very easily with PHP's cURL implementation using whatever keys Google gives you.
See Google's Google Books API Family page for links to PHP API and sample code.
Would the below practice be useful to you? If you just want to implement ajax functionality in your code.
Simple AJAX - PHP and Javascript
I am sorry for mistaking the content. How about the two below:
simple http request example in php
PHP HTTP-Request * from another stackoverflow question
But I think ajax is main in client program meaning. At the server-side, just call it http request.
How can I echo something at the end of the cakePHP json/xml response?
I need this in order to add JSONP support (Because i need to add the callback at the beginning and the ');' at the end
The controller uses this :
public function json() {
//...code to populate $jsonObjects
$this->set('objetos',$jsonObjects);
$this->set('_serialize', 'objetos');
}
Firstly, I'm assuming you have Routes set up to correctly handle JSON/XML responses
In your routes file:
Router::parseExtensions('json');
Secondly, you would need to make sure the call to your example uses the .json extension or the Accept header is application/json
You then check for the callback in your controller
public function json() {
//...code to populate $jsonObjects
// check for callback and set it
// note: you should do Sanitize::clean() or something like that to
// prevent code injection
if ($this->request->params['callback']) {
$this->set('callback', $this->request->params['callback']);
}
$this->set('objetos',$jsonObjects);
$this->set('_serialize', 'objetos');
}
in your view file (ex: View/Users/json/index.ctp) you should have something like this:
if (isset($callback)) {
echo $callback . '('.json_encode($objetos).')';
} else {
echo json_encode($objetos);
}
I use something similar but didn't test the exact example above so you may need to clean it up. Also make sure you clean up the callback var so you aren't leaving a security hole by outputting exactly what is in the query string parameter.
I have a PHP class called FormController whose constructor currently validates some $_POST variables and throws an exception if they're not all set. The FormController should eventually return the address of the next page.
So my PHP page would something like:
session_start();
try {
// controller needs certain variables set in the $_POST
// superglobal to work properly.
$controller = new FormController();
echo $controller->nextPage();
} catch(Exception e) {
// Handle exception here
}
my javascript code (jQuery):
$.post('next_page.php', {
form_variant: form_variant,
person: person,
last_page: last_page,
direction: "forward"
},
function(data) {
var response = JSON.parse(data);
window.location = response.new_page;
});
Initialing the POST request from javascript this is fine, but I am also working with some legacy code and would need to get the new page address from the form controller but I can't figure out how to call the FormController because that needs to use the $_POST variable.
One compromise is that I could have the form controller accept normal arguments and validate any post requests before I construct the FormController. This way I can contruct it from a PHP page.
Sorry for the length of this question, but can anyone tell me how I could make a POST request from within a PHP page? Or even if there is a better way I could be designing this?
Many thanks
In your formController allow $_POST vars being sent to be overwritten with a passed array:
public function __constructor($data = array())
{
if(!sizeof($data))
{
$data = $_POST;
}
}
Then send it directly when required:
$controller = new FormController($data);
You are using ajax just to get the post url and then do a redirection?
Why not just post to the nextpage, and let the nextpage decide what your want to forward to.