I have an html with a script that is like so (btw, HAVe to use old fashioned post in my html for reasons)...
#extends('layout')
// ... includes for jquery and ajax
<script>
var theVariableINeedInLaravel = "SomeInterestingStringI'mSure"; // in reality, this is a stringify.
$.post ("foo", function(theVariableINeedInLaravel) {
}
</script>
#stop
Then in routes.php...
<?php
Route::post('foo', 'ThatOneController#getValue');
?>
Then, in the related controller....
ThatOneController.php
class ThatOneController extends \BaseController{
public function getValue(){
error_log(print_r($_POST,true)); // returns nothing.
error_log(print_r(input::all()); // returns nothing.
}
}
Or, an alternate version of the function...
public function getValue(Request $request){
error_log(print_r($request->all()); // returns nothing.
}
None of them seem to work. How can I get my post variable?
try this
use Request;
class ThatOneController extends \BaseController{
public function getValue(){
print_r(Request::all());
}
Turns out that even if $_post isn't always accessible from inside a controller function, it is directly accessible from Routes. It's a bit hacky, and "not the laravel way" but you can use $_post in routes to get and pass into other variables to get back into the normal flow.
Related
I'm migrating an old app developed in Yii1 to Yii2.
I used to have a array in the controller that was storing all the variables that I would need to send to the frontend as a JavaScript:
public $jsVars;
public function toJSObject($params){
$this->jsVars = array_merge($this->jsVars, $params);
}
private function printJSVarsObject(){
//convert my php array into a js json object
}
When I needed a variable to be exposed in Javascript, I would just use $this->toJSObject, in the View or in the Controller.
Then, in the controller I also used to have:
public function beforeRender($view){
$this->printJSVarsObject();
}
In Yii2, I had to configure the View component with a custom View and then attach an event:
namespace app\classes;
use yii\base\Event;
use yii\helpers\Json;
Event::on(\yii\web\View::className(), \yii\web\View::EVENT_END_BODY, function($event) {
$event->sender->registerJSVars();
});
class View extends \yii\web\View {
public $jsVars = [];
public function addJsParam($param){
$this->jsVars = array_merge($this->jsVars, $param);
}
public function registerJSVars() {
$this->registerJs(
"var AppOptions= " . Json::htmlEncode($this->jsVars) . ";",
View::POS_END,
'acn_options'
);
}
}
But, having the event outside the class seems weird to me. Also, while I'm in the controller, I won't be able to use my former approach using this method.
Obviously, I'm missing something, or my approach is just incorrect.
How do you guys do that?
If you're trying to access properties of the controller from a view (see above comments!), you can use;
$this->context
to return an instance of the currently used controller from within the view file. So to access your beforeRender() method you would just use
$this->context->beforeRender()
I can't use the Request class in laravel for a Ajax request and the input request.
I'm trying to call a ajax request to the controller and this works until I wanted to request the data that has been posted to the controller. This has somthing to do with the Request class that I use.
use Request;
This class is used by the Ajax Request
use Illuminate\Http\Request;
This is the class used to request the input.
The problem is that I cannot use them both.
public function postQuestion(Request $request) {
//dd($request->answer);
if(Request::ajax()) {
// $answer = new Answers;
// $answer->answer = $request->answer;
// $answer->description = "Test";
// $answer->Questions_id = 1;
// $answer->save();
return Response::json($request->answer);
}
}
This is my code what i've wrote.
Anyone seeing somthing familiar? Or has a answer for it?
Issue turned out to be not being able to use two classes with same namespace. For such a case, PHP provides the as keyword.
use Illuminate\Http\Request as HttpRequest;
use Some\Other\Namespace\Request;
then in code both these classes can be used. E.g. HttpRequest::method() and Request::method()
you can use?
public function postQuestion(Requests\ModelRequest $request) { //your logic }
replace your Model in Requests\ModelRequest
While working on a Laravel 4.2 app, I have recently noticed that calls to Session::flash (and similarly Input::flash) sometimes behave inconsistently.
One particular example: I want to flash some data from the edit function so that I can access it in the corresponding update function. The edit view contains a fairly simple form, including one field that is loaded via an AJAX call after the user selects an option from a drop-down. Here is my MCVE:
In MyController.php:
<?php
class MyController {
public function edit($id) {
Session::flash('somevar', "myvalue");
return View::make('edit');
}
public function update($id) {
var_dump(Session::all()); die();
if (Session::has('somevar')) {
// do stuff
}
return Redirect::to('/');
}
}
?>
In AjaxController.php:
<?php
class AjaxController {
public function getinfo() {
return "here's that data you wanted";
}
}
?>
In edit.blade.php:
<script type="text/javascript">
$('form select[name=foo]').change(function() {
$.ajax({
url: '/ajax/getinfo'
success: function(data) {
alert(data);
}
});
});
</script>
Update
Sometimes the session dump in update() will show the flash data, but sometimes it is missing.
What is going wrong?
The issue is the extra AJAX call to populate one of the fields. Since this counts as a request, the flash data is active for that request, but not the next one.
To fix this issue, I added Session::reflash() to the first line of the function triggered by the AJAX call, like so:
<?php
class AjaxController {
public function getinfo() {
Session::reflash();
return "here's that data you wanted";
}
}
?>
I've tried many solutions that had the same questions like mine. But didn't found a working solution.
I have a controller:
event.php
And two views:
event.phtml
eventList.phtml
I use eventList to get data via ajax call so I want to populate both views with a variable named "eventlist" for example.
Normally I use this code for sending a variable to the view:
$this->view->eventList = $events;
But this variable is only available in event.phtml.
How can I make this available for eventlist.phtml? (without adding a second controller)
Edit:
I get this error now
Call to undefined method Page_Event::render()
Function:
private $_event;
public function init(){
$dbTable = new Custom_Model_DbTable_Events();
//Get Events
$this->_event = $dbTable->getEntries($this->webuser->businessId);
$this->index();
}
public function indexAction(){
$this->eventList = $this->_event;
$this->render();
$this->render('eventlist');
}
If I use $this->view->render('event.phtml') and eventlist.phtml it won't pass the data
I'm using zend version 1
You can pass variables to other views using render()
public function fooAction()
{
// Renders my/foo.phtml
$this->render();
// Renders my/bar.phtml
$this->render('bar');
}
Copy and paste this in your controller and rename your controller from event.php to EventController.php
class EventController extends Zend_Controller_Action
{
private $_event;
public function init(){
$dbTable = new Custom_Model_DbTable_Events();
//Get Events
$this->_event = $dbTable->getEntries($this->webuser->businessId);
$this->index();
}
public function indexAction(){
// You're calling the index.phtml here.
$this->eventList = $this->_event;
$this->render('event');
$this->render('eventlist');
}
}
To specify that only written #Daan
In your action:
$this->view->eventList= $events;
$this->render('eventList'); // for call eventList.phtml
In you View use : $this->eventList
You could render it within the view itself (eventList.phtml), rather than within the controller, using the same line of code you used above:
$this->render('event[.phtml]');
I want to call a function in another controller. for example if user try to log in with incorrect parameter then the application will redirect to another controller and passing a variable (array).
class User extends Controller {
function User()
{
parent::Controller();
}
function doLogin()
{
$userData = $this->users->getAuthUserData($user,$password);
if(empty($userData)){
// this is where i need to call a function from another controller
}else{
echo 'logged in';
}
}
}
is it possible passing a variable using redirect() function in url helper?
Yes you can use redirect('othercontroller/function/'.url_encode($data), 'location');
That should work.
edit: you could also put the code in a helper.
<?php
$array = array('foo'=>'bar', 'baz'=>'fubar', 'bar' => 'fuzz');
$json = json_encode($array);
$encoded_json= urlencode($json);
/* now pass this variable to your URL redirect)
/* on your receiving page:*/
$decoded_json= urldecode($encoded_json);
/* convert JSON string to an array and output it */
print_r(json_decode($decoded_json, true));
?>
this code:
takes an array, converts it to a JSON encoded string.
we then encode the $json string using url_encode. You can pass this via the url.
Decode this URL, then decode the JSON object as an associative array.
might be worth a try
If you want to call a function of one controller from another controller then you can use redirect Helper.
For example:
class Logout extends CI_Controller {
function index() {
session_destroy();
redirect('index.php/home/', 'refresh');
}
}
it will call another contoller.