How to pass variables from view to controller without using forms in Laravel? - laravel

I'm using RESTful controller and passing variables (using forms) works just fine here.
Now for some reason I need to use simple link, created with action() and dedicated route for #create action.
My view creates few similar links with different parameters:
<a href="{!! action('\App\Http\Controllers\Admin\Franch\Category\SubCategoryController#create', array('mainCategoryName' => $mainCategoryName)) !!}">
It works, because I can see this in URL:
/create?mainCategoryName=some_sample_name
But the route doesn't pass variables to the #create action OR controller doesn't recieve it for somereason:
Route::get('admin/franch/sub_categories/create', ['uses' => 'Admin\Franch\Category\SubCategoryController#create');
I wonder how can I pass variables from views to specific controllers, using GET and POST methods?
And this is my #create controller:
public function create($mainCategoryName = false)
{
dd($mainCategoryName);
....
Which is always gives false.

Well You can create a function on the link and in that function user Ajax
$.ajax({
type: "POST",//Or Get
url: url,
data: {"var_name":variable},
success: success,
dataType: dataType
});
Now you can send you variables in the data. and then you can get value of the variable in your controller by:
Input::get('var_name');

It would be much better if you make all your "calculations" in the controller and pass a resulting value to the view like so
class SomeController() extends Controller
{
public function getView():View
{
$mainCategoryName = "fix";
$formUrl = action('\App\Http\Controllers\Admin\Franch\Category\SubCategoryController#create', array('mainCategoryName' => $mainCategoryName));
return view('view.show', compact('formUrl'));
}
...
Your mistake is in keeping meaningful data in the view, when the view should only have processed values:
<a href="{!! $formUrl !!}">
And if you really want to go "nuts", you can create a class that would generate HTML using a blade-view and the controller data and then you can execute this class in the controller to have your "partial" ready to be incorporated in a view as HTML. But not the other way round. Keep the calculations out of your views.

Related

How to pass variables from Controller to View without refreshing the Web Page in Laravel?

Whenever there is a call to Controller inside View, I want the Controller to return some variables to the View and do not refresh the View.
Already know:
return view("webpage" , compact('variable1', 'variable2') );
What I expect to achieve:
return compact('variable1', 'variable2');
This will not return the Webpage but only some of the variables.
Edit:
Thinking it from a complete different perspective, The question maybe rephrased as such
Is there a way to manipulate REQUEST variables of a web page from the controller? This way, i would be able to get new variables from the Controller without the web page being Refreshed.
With out much to work with, here is an example:
Ajax call:
$.ajax({
url: '/your/route/',
type: 'GET',
data: {getVariable: formInputValue},
})
.done(function (data) {
console.log(data);
})
.fail(function () {
console.log('Failed');
});
Controller Function:
public function getVariable(Request $request){
$resault = $request->getVariable;
return response()->json($results);
}
Update: as per comments on this answer try this and see if it works for you.
In your controller where you fetch records instead of using a ->get();
change it to paginate(5); this will return 5 records per page. and on your view at the bottom of your </table> add {{ $variable->links() }}

Serialize Laravel Query Builder

I would like to be able to construct a query using laravel, and serialize it into a url string.
This would allow me to create routes which would unserialize a query builder, run the query, and make a view which displays the database results.
For example, to implement a button which refreshes a list of posts made by kryo:
http://example.com/ajax/posts.php?name=kryo&order_by=created_at&order_type=desc
Posts.php would simply be a route which unserializes, validates, and runs the query in the url params, and provides the results to a view.
Perhaps this is not useful in general, but I would personally find it handy specifically for ajax requests. If anyone knows how to implement this as a laravel plugin of some nature, that would be fantastic.
I'll try to give you a basic idea:
In Laravel you have to create a route to make a request to a function/method, so at first you need to create a route which will be listening for the ajax request, for example:
Route::get('/ajax/posts', array('uses' => 'PostController#index', 'as' => 'showPosts'));
Now, create a link in the view which points to this route, to create a link you may try this:
$url = to_route('showPosts');
If you use something like this:
<a class='ajaxPost' href="{{ $url }}?name=kryo&order_by=created_at&order_type=desc">Get Posts</a>
It'll create a ink to that route. So, make sure you are able to pass that $url to your JavaScript or manually you can write the url using /ajax/posts?name=.... Once you done creating the link then you need to create your JavaScript handler for this link (maybe using click event) then handle the click event from your handler, make ajax request, if it's jQuery then it could be something like this:
$('.ajaxPost').on('clcik', function(e){
e.preventDefault();
var url = $(this).attar('href');
$.getJSON(url, function(response){
$.each(response, function(key, value){
// loop... you may use $(this) or value
});
});
});
In your PostController controller class, create the index method:
class PostController extends BaseController {
public function index()
{
$name = Input::get('name');
$order_by = Input::get('order_by');
$created_at = Input::get('created_at');
$order_type = Input::get('order_type');
$posts = Post::whereName($name)->orderBy($order_by, $order_type)->get();
if(Request::ajax()) {
return Response::json($posts);
}
else {
// return a view for non ajax
}
}
}
If you want to send a rendered view from the server side to your JavaScript handler as HTML then change the getJson to get and instead of return Response::json($posts); use
return View::make('viewname')->with('posts', $posts);
In this case make sure that, your view doesn't extends the master layout. This may not be what you need but it gives you the idea how you can implement it.

In coffeescript how do I make a variable available in my controller and return the results via ajax to fill a datatable?

So I have a view with a datatable (javascript library to create pretty tables) that is generated like in this RailsCast
Briefly, the datatable is created in the server side and a new class creates a json response that is rendered in the view
So in my generated view I have a link that I want to trigger an ajax event when clicked and has a data attribute,
link_to( "#{sir.sir_id}" , '#', :data => {'sir-id' => sir.id}, remote: true )
I fetch the value of that data attribute in coffeescript this way:
$("a[data-sir-id]").click ->
data_sir_id = $(this).data("sir-id")
which works fine
I want to make that value (sir-id) available in my controller so I can get the associated model objects and show them in the same view via ajax, it would fill the content of another datatable (this one would not need server-side processing)
How do I create and feed this new datatable with ajax source?
I think I could return some other json object to the view if I manage to use sir_id in my controller but the view has already rendered json when first created.
You can send the data to the controller using a post method.
$("a[data-sir-id]").click ->
data_sir_id = $(this).data("sir-id")
$.ajax
type: 'POST'
url: '/some-path'
data: {sir_id: data_sir_id}
success: console.log('success posting sir-id')
dataType: 'json'
#config/routes.rb
Rails.application.routes.draw do
post "/some-path", to: "some_controller#some_view"
end
#app/controllers/some_controller.rb
class SomeController < ApplicationController
def some_view
SomeModel.find_by_sir_id(params[:sir_id])
end
end
I would like to say that if you can form a link_to with "#{sir.sir_id}" in your view file it seems to me that the sir_id should already be available to you in your controller and you wouldn't need to use ajax. Nevertheless, I hope this ajax solution is what you were looking for :)

Cakephp : add another view page link on the view page

sorry for asking this question ..i am working on a Cakephp 2.x ... i have a view page in my controller name folder e.g Controller/index.ctp ... and i have ajaxfiles are stored in app/webroot/ajax/ajaxfile.html
now on my index.php file i am acessing the ajax page like this
<a href="ajax-demo/ajaxfile.html" class="file-link">
<span class="icon file-png"></span>
Simple gallery</a>
Controller
public function index(){
}
now the problem is i want to send the variables to both of my pages ... index.ctp and ajaxfile ... how can i do this ??what is the best approach to tackle these things ....
do i have to move the ajaxfiles from webroot and paste under the controller name folder?
if is it so then how can i send variables to ajax files which has no model and controller
please if any one know the solution then please advice me. and give an example too
There are different way to achieve this, here I'm writing the simplest one
First you need to move your "index.ctp" file to your "View/YOUR CONTROLLER NAME/" folder.
1) To access the variable in view you need to set it from your controller's method like this
public index(){
$this->set('yourVariable', 'Your Value');
}
2) To access the value in your view file (index.ctp), you need to call this variable like this
$yourVariable;//If you want to print this then you can write like this
echo $yourVariable;
3) To call a ajax file from your index.ctp the simplest method is to call a onclick event on this anchor, the onclick event will call a JAVASCRIPT method which will further make a ajax call and will place the output in an element in your index.ctp, The ajax call will further call your controller method (implement your html related logic here)
For example,
<span class="icon file-png"></span>Simple gallery
<div id="yourAjaxFileOutputReplaceMentDiv"></div>
4) create a javascript method in your JS file, this JS file must be loaded in your layout file.
function yourAjaxCallMethod(BaseURL,yourVarible)
{
//Initialize Ajax Method
var req = getXMLHTTP();//Let's this method Initialize your Ajax
if (req)
{
req.onreadystatechange = function() {
if (req.readyState == 4)
{
if (req.status == 200)
{
document.getElementById('yourAjaxFileOutputReplaceMentDiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
var URL = BaseURL+yourVarible+'/'+Math.random();
req.open("GET", URL, true);
req.send(null);
}
}
5) Your AJAX file related method in your controller "yourController". Set autoRender to False
public function ajaxMethod(){
$this->autoRender = false;
//Check $this->request['pass'] for arguments send from ajax call
$retreivedVariable = $this->request['pass'][0];
echo 'I retrieved variable'.$retreivedVariable;
}
However instead of writing core javascript and ajax method you can call the inbuild Ajax Helper for same.

Poplate View with new updated Model in success function of $.ajax

I am making an ajax call to controller to post data from view to controller.And in the receiving controller I am updating my model with new values.Now I want to bind this new model to view again in success call of $.ajax post.Please Suggest.
one way to do this is to return a partial view from the controller. You can replace the contents of your previous view with the new html content. Lets expand on this...
so, here is your controller action
[HttpPost]
public ActionResult SomeMethod(params...){
....
var model = some model;
...
return PartialView("ViewName",model);
}
and in the ajax, use
$.ajax({
url : #Url.Create("Action","Controller"),
type : 'POST',
data: { ... your data params ..},
success : function(result){
$("#ContainerId").html(result);
}
})
in the html you would need a div with the id = "ContainerId". The content would get swapped out by the html passed back in the success function.
The Model is only used in RAZOR when rendering the page. Once you get to the point where you are using AJAX, the model is no longer available to you.
What, exactly, are you trying to accomplish? Maybe there is another way to do it?

Resources