Post Data not working correctly Laravel - php

I have a Route as below that will display a profile depending on the data in the url:
Route::get('/{region}/{summonername}', function () {
return 'Summoner Profile';
});
I have a Form on the Home page which consists of a Input Box and Region Selector. I am posting this data to:
Route::post('/summoner/data');
The problem is that i don't know how i can convert the form data eg. Summoner Name and Region into the url format where the user will be displayed with the profile page and the url would be /{region}/{summonername}. Am i supposed to use a Redirect::to inside my controller? I feel like that is a crappy way of doing it. Any Suggestions?
Right now when i post the data the url displays as '/summoner/data'.
I hope this makes sense, let me know if you need more clarification.

Routes :
Route::post('/summoner/data','ControllerName#FunctionName');
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});
Controller:
public function FunctionName()
{
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{$Region}/{$SummonerName}');
}
Hope this will work. Try it!
Using Routes:
Route::post('/summoner/data',function () {
$SummonerName = Input::get('SummonerName');
$Region = Input::get('Region');
return Redirect::to('/{'.$Region.'}/{'.$SummonerName.'}');
});
Route::get('/{region}/{summonername}', function () {
return view('SummonerProfile');
});

Yes, you will need to redirect:
Route::post('/summoner/data', function (Request $request) {
return redirect()->url($request->region .'/'. $request->summonername);
});

If you want to take the data from URL, just do the following
use Illuminate\Http\Request;
Route::post('/summoner/data', function (Request $request) {
echo $request->segment(1); // gives summoner
echo $request->segment(2); // gives data
});

Related

Laravel send data to multiple page

In laravel 7, I am getting data from db from a single route:
Route::get('/connection_view_details/{Cid}','ConnectionController#view_details');
I want to send the data to multiple page:
public function view_details($Cid)
{
$Cid = base64_decode($Cid);
$network_details = DB::table('connection_network_details')
->where('Connection_id',$Cid)
->first();
return view('connection.view_details',compact('network_details'));
return view('connection.connection_detail_tables.network_details',compact('network_details'));
}
I want to retuen view of view_details page ,not the network_details page.but I want to send the variable network_details in the both pages.
You can use the view composers
use Illuminate\Support\Facades\View;
public function view_details($Cid)
{
$Cid = base64_decode($Cid);
$network_details = DB::table('connection_network_details')
->where('Connection_id',$Cid)
->first();
View::composer('connection.connection_detail_tables.network_details', function ($view) use ($network_details) {
$view->with('network_details', $network_details);
});
return view('connection.view_details',compact('network_details'));
}
But you only can use that variable in that view only.

How to get ID from different controllers Yii2?

In the ActiveForm I have model button with Pjax render field after form from the modal button will created. Added a picture for an example. How can I get newly created id (not select added to the database, need to get the id that comes from this form).
I think I need to set get to button, than with ajax catch this and transfer to my Pjax rendered cell
I tried variations, but unsuccessfully, I cann't fully understand how to implement it. Can anyone help with the solution ?
//TwoController
public function actionCreate()
{
$model = new Formtwo();
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
echo 1;
//maybe here I must to do query ?
} else {
echo 0;
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
Index GridView
I hope I understood correct; you wish that when a user creates an instance of Form2, it is transferred then to create an instance of Form1, and the id of newly created record for Form2, is put in the Form1 _form.
If I did not understand correctly, please explain better :)
In TwoController create action, after creation, you would call the create action of OneContrller:
if ($model->save()) {
return \Yii::$app->runAction('/controller/action-name', ['form2_id'=>$model->id]);
}
On OneController actionCreate add parameter with default value:
public function actionCreate($form2_id=null) {
and make sure it is passed to the view (don't forget to make sure you pass it on create.php as well to the _form.
//TwoController
public function actionCreate()
{
$model = new Formtwo();
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
echo $model->id;
//maybe here I must to do query ?
} else {
echo 0;
}
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
You don't need query. Just use $model->id. It has value after save().
Update
It doesn't matter in which controller you are. You get the id of the model saved after save(). Then you can use id attribute. So, you can open modal form with ajax load. On form2 you register script to ajax post form. Something like this:
$("#form :submit").click(function (e) {
e.preventDefault();
$.ajax({
method: "POST",
url: $("#form").attr("action"),
data: $("#form").serialize(),
success: function (response) {
$("#modalid").modal("hide")
$.pjax.reload({
container: "#grid"
});
$('#Form2_id').val(response); //here you get the id
},
})
return false;
});

Silverstripe - populate fields depending on selected DataObject

I want to display a members details on screen when I select their name from a Dropdown
More information: I have a form that submits a few fields. Amongst them I have a "Select User" Dropdown to link this person to the data being submitted
Problem is- client wants the user's details to show when they select a user(make sure its the right person etc)
How can i accomplish this? There are like 3 seperate input fields that will need to contain data. I know how to do it using raw PHP/javascript, but do not know how to implement this in a Silverstripe way
You don't have to use Ajax for this, when you setup the form on your controller you can use loadDataFrom (http://api.silverstripe.org/3.3/class-Form.html#_loadDataFrom) to load the member directly into the form.
An example implementation could be (I haven't tested this, but it should work):
class Page_Controller extends ContentController
{
public function index()
{
$member = Member::currentUser();
$this->customise(array(
"Form" => $this->Form()->loadDataFrom($member)
));
}
public function Form() {
return Form::create(
$this,
"Form",
$fields, // Add your own fields here
$actions // Add your own actions here
);
}
}
Got a solution based off of this: https://www.silverstripe.org/community/forums/form-questions/show/24628
The way I did it was like this:
SS template
$("table.myTable").on('change','select#Some_Form',function(){
$.ajax({
type: "POST",
data: {param:param},
url: window.location.href+"your_action_here",
success: function(result) {
var resArr = JSON.parse(result);
$('input#Some_Field').val(resArr['key']);
}
});
});
Controller
static $allowed_actions = array('your_action_here');
//parameter is a SS_HTTPRequest
public function your_action_here($request){
//assuming my parameter is an ID
$ID = $request['param'];
$dataObject = DataObject::get_by_id('Object',$ID);
$JSONArray = array('key'=>$dataObject->Field);
echo json_encode($JSONArray);
}
When the select changes, gets the DataObject and populates correctly :)

Issue in the declaration of functions on SlimPhp

It's just since I started to discover slim and I ran into a problem, I do not know how to look for a solution because it is very strange.
Basically if I declare a function that is called from the route after another function is also called by a route, the first is not performed.
API group
// API group
$app->group('/api/:key', function () use ($app) {
//print all route
$app->get('/all',function () use($app){
echoRoutes();
});
// Library group
$app->group('/themer', function () use ($app) {
//get number of subscribed themer
$app->get('/count','allowed',function (){
echo "ciao";
});
//get information about the themer selected
$app->get('/:id','getThemer'); //AFTER THIS ROUTES /ciao AND /themes NOT WORK
$app->get('/ciao',function () use($app){
echoRoutes();
});
// Get book with ID
$app->get('/themes', function () use ($app) {
$articles = R::findAll('users');
$app->response()->header('Content-Type', 'application/json');
echo json_encode(R::exportAll($articles));
});
//get number of submitted theme by themer
//$app->get('/:id/themes','getSubmitedThemeById');
//get information about selected theme
//$app->get('/:id/themes/:theme','getThemeById');
$app->get('/themes/:id/', function ($id) {
$articles = R::find("users","id = ?",[$id]);
echo json_encode(R::exportAll($articles));
});
});
});
external file with function
//external file with function
function getThemer($key,$id) {
$themer = R::find("themers","id = ?",[$id]);
echo json_encode(R::exportAll($themer));
return true;
}
function countThemer(){
echo "count";
$count = R::exec( 'SELECT COUNT(id) FROM themers' );
echo $count;
}
function allowed($key){
$app = \Slim\Slim::getInstance();
$params = $app->router()->getCurrentRoute()->getParams();
if(!($params["key"]=="giulio"))
$app->redirect ("http://google.com");
}
after the route index.php/api/giulio/themer/1 that call getThemer and work the route index.php/api/giulio/themer/ciao and index.php/api/giulio/themer/themes not work
I thank you in advance for possible help
criticism or comments on the code in 'general appearance are welcome
Change the order of the routes:
// API group
$app->group('/api/:key', function () use ($app) {
//print all route
$app->get('/all',function () use($app){
echoRoutes();
});
// Library group
$app->group('/themer', function () use ($app) {
//get number of subscribed themer
$app->get('/count','allowed',function (){
echo "ciao";
});
$app->get('/ciao',function () use($app){
echoRoutes();
});
// Get book with ID
$app->get('/themes', function () use ($app) {
$articles = R::findAll('users');
$app->response()->header('Content-Type', 'application/json');
echo json_encode(R::exportAll($articles));
});
//get number of submitted theme by themer
//$app->get('/:id/themes','getSubmitedThemeById');
//get information about selected theme
//$app->get('/:id/themes/:theme','getThemeById');
$app->get('/themes/:id/', function ($id) {
$articles = R::find("users","id = ?",[$id]);
echo json_encode(R::exportAll($articles));
});
//get information about the themer selected
$app->get('/:id','getThemer');
});
});

Laravel 5.1 Ajax call to controller's method error

I'm doing an ajax call to controller's method, I made some attempts, but don't know where is the problem.
First try:
public function show(Request $request, $from, $to)
{
//return $request;
$envData = EnviromentalData::whereBetween('data_recorded', array($from, $to))->get();
return TransformService::transform($envData);
}
Output: {"from":["The from field is required."],"to":["The to field is required."]}", responseJSON: Object, status: 422, statusText: "Unprocessable Entity"
And, ofc,those fields 'from' and 'to' have values.
Second try:
public function show(Request $request) {
return $request;
}
Output: undefined
So the question is what is the problem? Also, I added two additional files of routes.php and script.js, I hope it will help.
routes.php
----------
Route::get('dashboard', 'DashboardController#dashboard');
Route::get('dashboard/from/{from}/to/{to}', 'DashboardController#show');
scripts.js
----------
// Ajax call to update the dashboard
function loadChart() {
$.getJSON(window.location.href + '/from/' + fromDate + '/to/' + toDate)
}
You dont have to add Request $request
Try this
routes.php
----------
Route::get('dashboard/from/{from}/to/{to}', 'DashboardController#show');
controller.php
--------------
public function show($from, $to) {
return Response::json($request) ;
}
If you get data from ajax means you have return data as json.
So, I found my problem and it was in two places:
1) return json_encode($request);
2) fixed scripts.js file, added some logic for .done() method and .fail() and all started working!

Categories