Insert a view using JS? - laravel

Is it possible to insert a view using javascript?
I wish to perform an ajax call, get the data, then insert a view in to a page and provide the data from the ajax call to that view?
Is this possible?

Yes you can use the render method on a view. Like so;
$view = View::make('your.view')->render();
And then return the html (which is the output) from your controller method by returning the data stored in $view.
If you need to add any data to the view just add the second parameter to the view make.

alternatively you can do this,
set the route for pages you want to call.
e.g.,
Route::get('callajax','PagesController#showAjax');
and then in PagesController#showAjax you return the view.
e.g.,
public function showAjax()
{
return View::make('ajaxpages');
}
and then in ajax call you code this
$.ajax({
url:'callajax',
});

Related

Asp MVC AjaxExtensions, call from controller

I'm sure this is simple but I'm struggling to find it
Inside a controller you can do something like this:
public ActionResult MyAction()
{
string url = Url.Action(action, controller),
// do something with the url
}
What's the Ajax equivalent? i.e. where you would call Ajax.ActionLink in a View whats the equivalent for the controller?
Elaboration-
I have a master/detail arrangement with a grid and some input elements. You can click on select/delete in the grid to amend or delete the line.
The grid is a Kendo UI grid, the view is rendered via:
a partial view to render the input elements
creating a json object, i.e.
#{
var jsLines = #Html.Raw(Json.Encode(Model.Lines));
}
Binding the Kendo grid to this json
From within the grid I want to hit on select and call an Ajax method to update the partial view with the form details
thanks
You can use Url.Action from the razor view. Something like :
$.ajax({
url: '#Url.Action("Action", "Controller")',
...
I'm not at all convinced that this is the right way to go but it's always good to have options.
Ajax.ActionLink seems to be the same as Url.Action but with a few attributes thrown in. So you can use this:
return string.Format("<a data-ajax='true' data-ajax-mode='replace'
data-ajax-update='{2}' href=\"{0}\">{1}</a>",
Url.Action(action, controller, routeValues),
text,
"formContainerSelectSection");
to update this:
<div id="formContainerSelectSection">
... stuff to be replaced via ajax
</div>
I accept, especially after the discussion with NicoD, that there are other and probably easier ways to do this, in particular this is creating a link in the controller, that's the Views job, but the original question was about how to do this

How do I auto fill field values in a section of a form that is loaded via ajax in Laravel 4?

I have a section of a form that dynamically loads different sets of fields based on the user's selection in a control. I'm using a javascript event handler to detect when the selection changes, and using AJAX (with HTML payload) to pull in the proper set of fields.
I would like to be able to use Laravel's Form::getValueAttribute() method to automatically fill in the form fields' values in both the static and dynamic form parts. However, the partial view that is loaded by my AJAX call does not have the same instance of the Form class as the view with my main Form, so I can't simply call getValueAttribute() in the partial.
My thought is to make the AJAX call a POST, and serialize the necessary data (a subset of Input::old() or the model data depending whether the page is loaded as the result of validation errors, or an UPDATE request) to send along with the POST so that the HTML fragment I get back has the values set properly.
Is this the best way to get what I want? If so, does Laravel have any tools to help with the serialization of form data? If not, what might be a better approach?
I've found an approach I like better. When the view is loaded normally I use AJAX as usual to load the partial. But when the view is loaded for a validation post-back or for editing, I use Laravel's Views' nest method to nest the partial view containing the proper fields directly into the response. The partial then has access to all the Input and error data I need. The user is still able to change the field set as usual but I put up a confirm prompt for them if they have already set some values in a field set they previously selected. If they decide to proceed anyway, the field set is cleared and a new field set is brought in via AJAX as usual.
My code looks something like this:
Controller:
public function newThing() {
if ( Request::session()->has('errors') ) {
// this is a validation post-back
return View::make('thing')
->nest('fields', 'fields_partial');
} else {
// just a normal unfilled form
return View::make('thing');
}
}
public function editThing() {
return View::make('thing')
->nest('fields', 'fields_partial');
}
View: thing.blade.php (just a snip of it)
...
<form>
...
<select id="picker">...</select>
<div class="sub-fields">
{{ isset($fields) ? $fields : '' }}
</div>
...
</form>
...
<script>
$('#picker').change(function() {
// if any .sub-fields inputs have been changed, get confirmation from the user
// if user confirms, do ajax stuff to replace .sub-fields contents with new field set
// otherwise cancel the change
});
</script>

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?

Codeigniter: jquery not passing its 'load' value to the controller

The issue is what I say in the title. The parameter of the index selected in the first dropdown box is not sent to the controller. Therefore the controller cannot pass any value to the model etc. If I harcode saying $pais_id = 1 and send that to the Model it works, so this means, the issue is in the controller not getting it from the jquery.
VIEW
<script type="text/javascript">
//jquery code for source list
$(document).ready(function(){
$('#country').change(function() {
if ($(this).val()!='') {
$("#source").load("/CI-3/controllers/control_form.php",{pais_id: $(this).val()});
}
});
}); // end of country and city function
</script>
The problem must be there because I don't visualize the process:
Jquery detects the changing in the select dropdown list and fetches the selected id. Alright, but what happens next ? it sends it to the controller, yes, and? the controller forwards it to the model, the model does a sql search and returns an array back to the controller and the controller forwards it to the view, but, how does #source in the line above get affected after all that?, so it will not modify itself
$source['source'] = $this->model_form->get_source($pais_id);
should be
$data['source'] = $this->model_form->get_source($pais_id);
in controller. third parameter in view is if it's returned or echo'd. all values are passed in the 2nd parameter as an array.

JSON data for jQuery dataTable in web2py

I am trying to load json data from web2py controller to jQuery dataTable via AJAX.
But only blank dataTable is rendered (with desired formatting, search box, etc.)
Can somebody pl. point out into my code as to where I have a mistake.
Data is not displayed (as returned by "get_data" method).
I have made sure that the database tables have been populated.
Controller
def show_data():
return dict()
def get_data():
custdata = db.executesql(qry, as_dict=True)
return custdata
For testing purpose, I returned response.json(custdata) in a separate method & validated the same on "jsonlint.com".
It is valid json.
View (show_data.html)
{{extend 'layout.html'}}
$(document).ready(function() {
var oTable = $('.smarttable').dataTable( {
"sScrollY": "200px",
"sAjaxSource": "{{=URL('MIS','get_data.json')}}",
"sDom": "frtiS",
"bDeferRender": true
} );
} );
Lastly, html table tags are defined for a table with class="smarttable"
Your get_data function should return a dictionary, like this:
def get_data():
custdata = db.executesql(qry, as_dict=True)
return dict(data=custdata)
In web2py, a view is only called if the controller action returns a dictionary -- otherwise, the controller output is simply returned to the client as is (and as is, custdata has not yet been converted to JSON).
When you call the URL /MIS/get_data.json, the .json extension tells web2py to look for a /views/MIS/get_data.json view file to use for rendering the JSON. If it doesn't find that view file, it will trying using /views/generic.json, though it will only use generic.json for local requests, unless you override that by specifying response.generic_patterns=['json'].
As an alternative to using a view to render the JSON, you could also do:
def get_data():
custdata = db.executesql(qry, as_dict=True)
return response.json(custdata)
EDIT: The jQuery DataTables plugin requires the JSON to include some special parameters, so you'll have to add those before returning the JSON. To make things easier, you might consider using PowerTable (a web2py plugin for DataTables), or the jqGrid widget included with web2py's plugin_wiki (the widget can be used on any web page, not just wiki pages).
you have to have the "key" values in the "dictionary" that you give for return .
iTotalRecords,iTotalDisplayRecords,sEcho and aaData. you can find the explanations in http://datatables.net/usage/server-side

Resources