I'm currently working on a project in Django and currently I'm working on a form that includes several elements. Each element is dynamic and needs to have it's options updated when the element above it changes value. I know I can use AJAX to update the elements contents whenever another one is changed in value, but I was wondering if there was a more Django way, or anyway to do this server side? My main goal is to do it without reloading the entire page each time, any feedback is appreciated. Thanks!
Update: My question is very similar to Django ajax form, choicefields dependancy But I don't fully understand what's going on in the answer. If someone could explain it in a little more detail, that would solve all of my problems for now. I'm trying what that answer says, but I'm getting 500 and 403 errors when I try to load it.
Follow Up: Apparently all of my issues were coming from an outdated jQuery library, once I updated it, everything worked again!
AFAIK there isn't a canonical Django way of doing Ajax… But it's fairy straight forward to do yourself:
First you've got to create a view which returns whatever JSON data will be needed to update the view. For example, the list of cities in a province:
from django.utils import simplejson as json
def list_cities(request):
cities = city_names_in_province(request.GET["province"])
return json.dumps(cities)
Second you've got to call that view from the HTML (assuming jQuery):
<select id="provinces">
…
</select>
<select id="cities" disabled="true">
<option>---</option>
</select>
<script>
$("#provinces").change(function() {
var province = $(this).val();
$.getJSON("{% url list_cities %}", { province: province }, function(cities) {
var cities_select = $("#cities");
… put the `cities` list into the `cities_select` …
});
});
</script>
And, apart from the “prettying up” and error checking (eg, what happens if the call to list_cities fails?), that's basically all there is to it.
Related
I am newbie to MVC and Web App.
Recently I have went through the article
http://www.c-sharpcorner.com/UploadFile/pmfawas/Asp-Net-mvc-how-to-post-a-collection/
It uses the Ajax Form, to do the partial update towards a particular region alone..
But I have a doubt in that example...
I have seen the partial Page inside the Div with Id "AllTweets"....
<div id="AllTweets">
#Html.Partial("_AllTweets", Model) ***** (XXX)
</div>
And also in the controller action,
try
{
viewModel.Tweets.Add(viewModel.Tweet);
return PartialView("_AllTweets", viewModel); **** (YYYYY)
}
Now my question is,
They are returning the partial view along with the data from the action in the controller.
Whatever the data returned from the controller, the engine will place that data, inside the target div with id "AllTweets"...
But still, why I have to have the statement, #Html.Partial("_AllTweets", Model) inside the Div, since already I am returning the data from the controller...
And also in some of the examples, i have seen the same kind of the code..
But, even if I have removed the code "#Html.Partial("_AllTweets", Model)" inside the div, the code still works fine, and without any problem and i can able to post the data to the action in the controller.
I got totally stuck at this point.
May I kindly know, what is the reason behind it and why so.... So I can understand it more better.
Thanks in advance...
But, even if I have removed the code #Html.Partial("_AllTweets",
Model) inside the div, the code still works fine, and without any
problem and i can able to post the data to the action in the
controller.
Yes it will work fine. The Html.Partial("_AllTweets",Model) renders the partial with the specified model on every page load. After page is loaded, then ajax is used to fill the div with id AllTweets.
Html.Partial("_AllTweets",Model) is usefull when you want to display, for example, already saved tweets from your database to user when the page first loads. And then ajax takes care of later updates.
I am a beginner in MVC. In my application, I list categories (as a button) on the left hand-side (inside a div). Just right to this div, there is another div which displays the items associated with the clicked category.
When a category button is clicked, I am planning to call the action of the controller that will retrieve the Items from the database and add these Items to the ViewModel (e.g., model.Items = db.Items...), and then call the View with the updated Model and display the Items.
However, I am curios if it is better to make an Ajax call here and use a partial view for displaying the Items of the clicked category.
If feel like between these two approaches in my scenario only difference will be the page-refresh, they should work the same in terms of speed since both of them require the same database call.
Can anyone share good practices in MVC for such scenarios?
Yes AJAX is faster and good way to update detail in same page without refresh.
For that you have to create JsonResult method in controller. It will give you result in Json.
Try JQuery Template plugin for repeated code.
<script id="trTemplate" type="text/x-jquery-tmpl">
<tr>
{{each $data}}
<td>${Col}</td>
{{/each}}
</tr>
</script>
<table id="containerTable">
</table>
AJAX Call
$.ajax({
url: 'Your JsonResult Method URL',
type: "GET",
data: data,
beforeSend: function () {
},
success: function (data) {
// It will pass data to template and template will bind parsing json
$('#trTemplate').tmpl(data).appendTo('#containerTable');
//Business logic
},
complete: function () {
// Your Code
}
});
Your JsonResult Method
[HttpPost]
public JsonResult GetData(ViewModel model)
{
// Your Code here
}
using ajax or not when displaying new records in asp.net mvc
Using jquery would be the best approach for this scenario. As you don't have to load the layout page which will have to render the scripts and stuff all over again. Stick on to Ajax calls in MVC as much as possible, The technologies are being improved and a lot of single page applications are out there, And if we still use a page load for every new request then there is no point.
Coming to comparison between passing back Partial View And Json Data. Which is better to use in the application design?
Both partial Views and Json data hold the same weight depending on the scenario.
When to use partial view: Lets say you have a Model and you have to build the view HTML by lot of if checks and loops and possibly some c# code ( in rare scenarios), etc, in such scenario using Partial view would be the better choice, Because if we try to build the same thing in Jquery using json data the complexity of the code required would be high compared to what can be done in Partial views, But still achieving it is possible but wont be that easy and we might make errors during development.
When to use Json Data: If the requirement is like updating a grid, generating dynamic drop down or dealing with some Jquery plugins in the page I think Json data would be better, as many plugins play with json data as the core requirement.
A Small Example Of Deciding Between Partial View And Json Data - interested folks and read through
Lets take a scenario where we have to display a grid of data. This is our initial requirement. So we can happily build our viewModel with data and pass it to our partial view and render the table using for loops. All set, Now the requirement changes and we are asked to build sorting, filtering and paging stuff in our table. So at present we look for a plugin that can be easily integrated with current code and yes the easy one to use at this scenario is Datatables. Ok, we wrote a small Jquery to apply the plugin to the table and all set we have the fancy stuff ready.
Now here is the tricky part, we are asked to add functionalities like add, edit, delete record from the table. Yes its possible but is little tricky to get it done in the best possible way with the current code which we have. What we tend to do is, when ever there is a change in the table we plan to recall the partial view. Which works fine but still asking to ourselves just to delete one record from the table is it good to reload the partial view again?? Definitely NOT,
What can we do? When ever there is any add, edit, delete operation we hit the controller to update the database and we can make the controller return a JSON data and just pass this Json data to the plugin API and refresh the table, This will be more neat and faster. So here you see JSON data would be the better choice. Also some might even want to make it more cleaner by just playing with that one record of data and writing up some jquery code to manipulate the table, which is absolutely fine, But it requires us to pass the Json data itself back from controller.
So having this done, we can go back and refactor our code to make partial view to use json data for the grid initially too or leave it as it is saying the initial load will be a partial view, but following operations would be a json result, which is fine but I feel let all the data related stuff come from one point.
So that explains how a simple module can change from being a partial view to then use Json data. There are scenarios where the story is the other way around, You have to pick the right one for the right work.
I need help with the form submission and saving to db in my ruby camping web app.
The app itself is a quality assurance app. Users fill in forms for any errors detected during the quality check. The problem is that the check can take for a couple of hours or in extreme cases even more. During that time, in order to save the data, users have to submit the form several times. Currently I've set it up so that the users submit the form and are immediately redirected back to the form.
How would I go about to enable some sort of autosaving, let's say every 10 minutes or upon each change to the form so users don't have to do it manually.
This is quite difficult for me because I'm not a programmer per say, butI learn as go alogn to optimize my processes.
I've been reading about ajax and jquery but I'd really appreciate if someone could point me in the right direction since I don't know where to start and camping examples are rather scarce.
EDIT
Some additional infos:
I've successfully implemented jQuery to my camping app and I can manipulate html elements, but AJAX doesn't work. Firebug console doesn't return any errors.
Here are my assumptions:
If the form can be successfully submitted manually I don't have to change anything in my controller or view in order for AJAX to work, right?
The url passed to AJAX doesn't have to include the object id for which I want to submitt the form, right? I'm passing the '/edit' url and the full url to the relevant object is for example '/edit/5'.
Here is the code from the html head:
script :type => 'text/javascript' do "
$(document).ready(function() {
$('#np').change(function() {
$('#add_form').submit(function() {
$.ajax({
type: 'POST',
url: '/edit',
data: $('#add_form').serialize(),
});
});
});
$('#search_indiv_form').click(function(){
$('#search_indiv_form_toggle').toggle(700);
});
});"
end
Are there any errors in my ajax code to prevent the form being submitted?
thank you.
regards,
seba
Ok, this idea might seem quite a bit crazy and it kindo' is (at least for me at my level).
I have a fairly standarad rails app (some content pages, a blog, a news block, some authentication). And I want to make it into a single page app.
What I want to accomplish is:
All the pages are fetched through AJAX like when using turbolinks, except that the AJAX returns only the view part (the yield part in the layout) withought the layout itself, which stays the same (less data in the responces, quicker render and load time).
The pages are mostly just static html with AngularJS markup so not much to process.
All the actual data is loaded separately through JSON and populated in the view.
Also the url and the page title get changed accordingly.
I've been thinking about this concept for quite a while and I just can't seem to come up with a solution. At this point I've got to some ideas on how this actualy might be done along with some problems I can't pass. Any ideas or solutions are greatly appreciated. Or might be I've just gone crazy and 3 small requests to load a page are worse then I big that needs all the rendering done on server side.
So, here's my idea and known problems.
When user first visits the app, the view template with angular markup is rendered regularly and the second request comes from the Angular Resource.
Then on ngClick on any link that adress is sent to ngInclude of the content wrapper.
How do I bind that onClick on any link and how can I exclude certain links from that bind (e.g. links to external authentication services)?
How do I tell the server not to render the layout if the request is comming from Angular? I though about adding a parameter to the request, but there might be a better idea.
When ngInclude gets the requested template, it fires the ngInit functions of the controllers (usually a single one) in that template and gets the data from the server as JSON (along with the proper page title).
Angular populates the template with the received data, sets the browser url to the url of the link and sets the page title to what it just got.
How do I change the page title and the page url? The title can be changed using jQuery, but is there a way through Angular itself?
Again, I keep thinking about some kind of animation to make this change more fancy.
Profit!
So. What do you guys think?
OK, in case enyone ever finds this idea worth thinking about.
The key can be solved as follows.
Server-side decision of whether to render the view or not.
Use a param in the ngInclude and set the layout: false in the controller if that param is present.
Have not found an easier way.
Client-side binding all links except those that have a particular class no-ajax
Here's a directive that does it.
App.directive('allClicks', function($parse) {
return {
restrict: 'A',
transclude: true,
replace: true,
link: function(scope, element, attrs) {
var $a = element.find('a').not($('a.no-ajax')),
fn = $parse(attrs['allLinks']);
$a.on('click', function(event) {
event.preventDefault();
scope.$apply(function() {
var $this = angular.element(event.target);
fn(scope, {
$event: event,
$href: $this.attr('href'),
$link: $this
});
});
});
}
};
})
And then use it on some wrapper div or body tag like <body ng-controller="WrapperCtrl" all-links="ajaxLink($href)"> and then in your content div do <div id="content" ng-include="current_page_template">
In your angular controller set the current_page template to the document.URL and implement that ajaxLink function.
$scope.ajaxLink = function(path) {
$scope.current_page_template = path+"?nolayout=true";
}
And then when you get your JSON with your data from the server don't forget to use history.pushState to set the url line and document.title = to setr the title.
I want to show my users data from my mysql database without reloading the page.
I am using Codeigniter. I have a dropdown menu like the following, - when the page loads I want it to show all data by default. But when any user selects any name it will query to database and show results immediately without having the page reloaded.
I already have a controller, model and view to display all data from database but I don't know how to get the dropdown menu work after a person has selected a value, to fetch data from database and show immediately without reloading the page.
I have some basic knowledge of PHP but I have no idea about AJAX. Would you please kindly give me an example or idea on how to do this?
I am not expecting you to write the code for me, I am just asking for an example or a guideline. :)
Thanks in Advance.
<form>
<select name="info">
<option value="">Select a person:</option>
<option value="11080101">John</option>
<option value="11080102">Bon Jovi</option>
</select>
</form>
It sounds like with what you are aiming to achieve this isn't really a codeigniter related question but more a HTML, JQUERY question.
Using jQuery To Manipulate and Filter Data over at Net-tuts shows a jquery solution to sorting and filtering data. Their solution is based on a table but the principals are there so a modification can get it to do what you want it to do.
well i can give you the flow of how can you try it
trigger a jquery event on selecting an dropdown menu item. if you don't have any idea how to do it try reading the documentation of jquery for using selectors .
once you have the selected element , extract its value and send an ajax call to your path
like this (for jquery ajax visit jqapi it has all the documentation for jquery ajax functions and its derivatives)
$.post('/user/data/' + id , function(response) {
console.log(response)
})
or
$.post('/user/data/', 'id=' + id , function(response) {
console.log(response)
})
and now you have your data in reponse so you can do whatever you wish to do with it