I am writing a django template and I am working woth lot of data. I have all the data in the django object with me in template. I want to create tables on button click so i have used
$(document).ready(function()
{
$(document).on("click", ".open-infoDialog", function ({{users}}) {});
});
I am creating tables inside the above function
But whatever is there in the function is already created before the click of the button. Is there a way i can create the code in the html after the button click.
The problem is happening as there is large amount of data it takes ages to see the page.
The answer is no, not within the template. Your template variables are filled in on the server. By the time the browser gets it, everything is filled in.
If you want to get hold of some data only after the user clicks, you will need to make a special view which returns the extra data you want (either as json or however you like). Then in your click handler you can do an ajax request to that view.
Think of this problem in terms of where the data is located and when it travels.
1) You would like to first load a page into the users browser, which does not contain any of this large data.. it only contains a button for the user to press to get the large data. The way this happens is, the browser connects to the server/url, django looks at urls.py and decides what view to execute. The view then, using the template, generates the html which diplays the button.. which travels back to the browser and is displayed.
That is the end of the request and your first template and first view have done their job and exited.
2) Then, only if the user presses a button, you want to load the data up into the existing page. This is ANOTHER REQUEST. When the button is pressed, the click handler must execute code which makes another connection to the server, a different url, different view, different template.. since you are returning different data. Then in your javascript you take this new html and load it into the part of the existing page that you would like...
It's classic AJAX, it is two different requests but instead of loading a whole new page you're only loading part of it. Since you are not clear on how this works just yet the easiest way to do this is to just write two totally separate Django views each with their own template, own url etc. Then you can test each one separately. One returns the page with the button and the javascript but no data. The other returns just the part of the page that would normally contain the data. Then once you have got that working, write the jQuery/javascript code which loads the data.
For example, in your first template:
<script>
$(document).ready(function()
{
$(document).on("click", "#loadusers", function () {
$( "#user_select" ).load( "/myapp/loadusers/" );
});
});
</script>
<form>
<input type="button" id="loadusers" value="Load User Choices">
<select id="user_select" name="user"></select>
</form>
In your loadusers template:
{% foreach user in users %}
<option value="{{user.pk}}">{{user}}</option>
{% endfor %}
This would result in the first view rendering a page which contains an empty select. If you then click the button it will load the options from the second view.
Try the following code:
$(document).ready(function()
{
var template = {{users}}; // Storing the template in a variable
$(document).on("click", ".open-infoDialog",
function (l_template) {
return function() {
// This function will be called on click.
// Do the stuff here. using l_template
};
}(template)
});
The template will contain your data. Here, We are returning a function instead of value.
That returned function will be called on click callback.
You can use l_template in the returned function.
Related
I am looking for a very simple process to record a click to an element then to update a database with that number.
For example a page is displayed then the variable is incremented when a click is made within that element. It only needs to record 1 click so a 0/1 variable is fine but when the zero changes to a 1 it needs to be recorded on the database.
Any simple way to do this? I am assuming it would be ajax but not too hot with that. I would need to also pass the ID of the row to update on the DB. Any help is appreciated :)
It really needs to happen in the background with the only interaction being the click on the element that holds the page so no page refresh. I have a good idea of what i want but the coding part in Javascript/Ajax eludes me. Basically i need to set up a listener for the click or an onclick to the element which will then fire up ajax to send a single variable (the id in the database) which will update the row in the db.
so for example
<div id="page" onclick="updateclick()">
Page content
</div>
<script>
function updateclick() {
var click = "1";
ajax part to send the variable $db_id to a seperate php file so the DB can
be updated
}
</script>
Something like this.
I have a Django template with an AJAX menu (where clicking on different menu items reloads a part of the page). Each menu click invokes a Django view function through AJAX and returns some data to be shown on the page.
I am loading all the JS required for all the menu items in the main page only (as I learnt that it is not a good idea for AJAX to return JS in a <div> and then use eval() to execute it). Since I am loading all the JS on the menu's main page only, the data obviously isn't there for other menu options at start since it will come later when the corresponding view is invoked (when the menu option is clicked)
Because of that, code like the one below gives a syntax error on the console since JS is parsed the very first time only.
<script> var data = {{se_data|safe}}; </script>
Now I am not able to use the data returned from the view, even after I click the menu options, since the JS parsing failed in the first place. I tried using if to execute the code only when the corresponding menu option is selected but that too does not work since the parser just parses everything.
I have been trying different methods to get around the issue but cant seem to find an efficient way to solve this. An alternative could be to have the view function return all the data at first only, but I fear that the menu options and the data returned may grow over time, hence delaying the initial load of the main menu page.
This is the ajax menu's click function:
$(".ent-menu li a").click(function(e) {
e.preventDefault(); // prevent from going to the page mentioned in href
// get the href
var href = $(this).attr("href");
$("#data_container").load(href, function() {
load_data(); //this function uses the data variable defined earlier
});
});
Error I see in the console when loading the menu's main page:
Uncaught SyntaxError: Unexpected token ; at line 1110
data = ;
since the data is not available yet.
As discussed, you should use JSON to send the data from Python to JS; use JSON.parse() to deserialize the data for use in your JS.
I'm hoping there is a simple solution to this, or else its possible AJAX time!
I WAS using ClickBank. I had a simple button on my page. That sent the form data to a script, I processed the data, and then added a redirect at end of script to jump to the "pay" link. Nice n' easy
But now I'm switching to "Click2Sell" ... and they have a direct href to their site.
Now I COULD use javascript to read the form data, place it into their "cp_" prefix, and create a super long (about 400 chars) query string and send that to their server, then re-read the data at the IPN stage ...
?country=UK&area=essex&desc=This is the data entered by the user 'whatever'
(but that leads to a little fact that certain parts might need to be escaped(?) such as the spaces and the " ' " or whatever other symbol they enter)
So I devised this method:
<javascript>
function send_data(){
document.user.submit();
return true;
}
</javascript>
<div name="noshowdiv"><object name="noshow"></object></div>
<form method="post" target="noshow" name="user">
<input type="text" name="country">
<input type="text" name="area">
<textarea name="desc"></textarea>
</form>
<img src="xxx" onclick="return send_data();">
In a nutshell, when the button is clicked, it jumps to the function, and submits the form data to my script, and then returns to the hyperlink to submit the second form via the hyperlink.
Two problems: Firstly, the data returned by my script is opening in a new tab rather than the <div>, (I suspect 'cos the submit option loses track of the sending window) and also, I need to get a response from my script which I can then append to the href link.
For example, if the form records the user's data on line 5 on my server, the script will return "id=5" I would then make the hyperlink "click2sell.asp?cp_id=5"
As I've said, I suspect this is a job for Ajax and a HttpRequest ... which is a whole new area to me. Any advice?
For the first problem, it opens a new tab because you have target="no-show" on your form.
For the second problem, if you want to use Ajax, I recommend you use jQuery, it will simplify a lot of the code.
But the best option is probably that you completely remove the direct link to click2sell, and just add a submit button to your form. Post the form to your site, which will store whatever info it needs, assigns an ID, and builds the click2sell URL with the ID in one of the parameters, and redirect to it.
Now how you would do that depends on what server-side language you use.
(I think) I have managed to find a work around, which was using the first option to reconstruct the href link. I couldn't iterate through the form as there are values that don't need to be forwarded. First I get the value, load it into a variable, then use an encode function I discovered online, and then reassign to the form ...
var cp_cc=document.getElementById('cc').value;
var cp_cs=document.getElementById('cs').value; // plus 10 other values
var str='&cp_cc='+encodeURIComponent(cc)+'&cp_cs='+encodeURIComponent(cs)+ // etc
var send_str=document.getElementById('c2s_bn_lnk_36288').href;
document.getElementById('c2s_bn_lnk_36288').href=send_str+str;
The "no-show" was a slip up in my typing! Alas, the answer given above wouldn't work as the Click2sell button also includes two calls to external JS files - and they give you no idea what they do, but is something to do with initializing the button, (it passes the "36288" to the script to do ???). And whilst using "Location: ..\n\n" on my server would redirect to their site, it wouldn't action whatever those external files do. (OK, so I didn't give the full facts, but I didn't want to increase the post size with data I felt didn't relate to problem)
** Now got to amend the listening scripts such that rather than set the ID number up front then jump to C2S, it now waits for C2S to send the data back to me and then sets up the database!!
In my django app I would like to display a text when a user clicks on a button, without refreshing the page. When the user clicks again, I would like an other text to be displayed, still without refreshing the page.
The informations (texts) I wan't to display are in a query set, named "information".
So I would like to know how to accomplish that.
Here is the way I try to do it:
I create a view where I store my query set:
def get_information (request):
information= Information.objects.filter(object1__id= X)
Then I create a jquery get function (in the template of the page where the user clicks) in order to get informations on this list:
function get_info(){
$.get('/mysite/get_information', {'information':information}, function(data) {
$('.information').html(data);
});
};
And then I render it in my template with a submit button and a onclick="get_info".
But I don't know how to make the request get a different information at each request, in order that the user does not get the same information twice.
Thank you a lot for your help.
Take a look in to Django Pagination. You could create the Paginator object in your view and then you can display message from the queryset based on the request from the client side. Let me know in case of any issues.
I have an ajax query that returns an array . . I only show the first 20 items in the array right now but i have now added a link for "Show All" after I displayed those first results.
When the user clicks Show All i want to display all of the items in the array.(either inline or in a dialog (but that implementation shouldn't matter)
I want to avoid having to go back to the server to get the full list since I already retrieved the full list from the first ajax call . . where is the best way to locally store this array to be accessed later.
Save the array in a variable, or possibly attached as a data element to something on the DOM. Then, when your "Show All" event fires, read from that array and rebuild your display.
<div id="myArrayDisplay">
</div>
<script>
$(function () {
$.getJSON("backendCode.php", function (jsonData) { // assumes your array arrives as a response from a JSON-based Ajax request to some server code
$("#myArrayDisplay").data("arrayObj", jsonData);
});
});
</script>
Obviously I'm not showing how you would display the contents of the array in the above code, just how I would store it.
I think the easy way you can do is to put the full list data into a hidden input textfield
I don't know about the best way, but the simplest is using a global variable.
Define it here:
$(document).ready(function(){
$.myArray = [];
})
And use it like so:
function myFunction(){
alert($.myArray[0]);
}
More info about $(document).ready.
On the other hand, you could create two separate fields, one with the initial info and one with the rest, making the second one invisible. When the user clicks "Show more" you can show the hidden one.
More information about .show().