Get elements of a query-set with a jquery get function. Django - javascript

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.

Related

How to display ajax list response on html using jquery?

So I currently have a search box that the user can search for managers. When the manager is searched and selected, they can choose to show direct report employees via a button that triggers a Javascript function that sends an Ajax post to the backend to query the database. Upon receiving a success response, I would like to display a table with general info of the employee (such as First, Last name, Position, etc.) We have previously used Jquery to pull the data upon load, but I was wondering if there was a way to pull and display this data from the Ajax response and display it on page without refreshing? Another roadblock seems to be that the response is in a List fashion, in such that it returns none to many employees; a variable response. If it is more effective, we are also using a Thymeleaf template, but I doesn't appear if I can make the Thymeleaf selectors open to a live update such as this
In order to set the Ajax Response in your HTML page, Do something like this :-
1.) Use your HTML element's id and then append the response fro your ajax Success function.
Suppose there's a text box in which you want to set the response.
<input type="text" id="inputText" >
2.) Now, in your ajax success Response , get the id of this element and then append the response like this :- -
$.ajax({
url: //your url,
success(data){
$('#inputText').val(""); //clear the text box on each call so that it won't append the data on every request
$('#inputText').val(data); //get the text-box id and append the response
},
error(data){
console.log(JSON.stringify(data));
}
});
See my comment first. The post response if possible should be a JSON list of objects I'm assuming employees. Then after success use jquery to manipulate(add or remove) the table rows and if that sounds complex. House the whole table in a div with id, when ajax returns recreate the table by replacing all said divs HTML with the new table. No need to refresh. However, since a request can take long or fail you need some animation (perhaps blockUI) to show activity and even handle failures

How to update or refresh table using Rails Actioncable?

My action cable is working fine, it shows me an alert with the data content(although it shows in all the pages).
This is my case: an user with role ADMIN has access to an url (http://localhost:3000/ventas/) with a table (html id=tablaventas)that show a list of sales. This table must be automatically refreshed every time a user (role SELLER) inserts a new sale in the database.
This user with role seller has an url (http://localhost:3000/ventas/new) with a form where insert new sales to the database. The Actioncable implementation is working okay, but I have two problems:
1- how to refresh the table from the ventas.coffee:
//here i am stuck
received: (data) ->
alert data.name //this works ok
//...AND HERE I WANT TO UPDATE or refresh THE ADMIN TABLE
2- Also, how can I show for example the alert message only to the admin specific view? in this case only in the view ventas/index.html.erb.
Can you just add another row to the table?
$('#tablaventas').append("<tr><td>#{data.name}</td>...other tds...</tr>")
If you need to refresh the whole table - you'll need to call .html(data.table_html) on table container element. Also this means that you'll have to render table_html in your controller, via render_to_string('table') or something.
I think your issue is that you subscribe to action cable updates globally while you only need to subscribe on the index page. This blog post should help you solve this.
Hope the above helps.

create onClick content after the click in the html

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.

How to make search field for user with autofill for html list

I need a search field on my site allowing users to search for their location (for a local weather forecast).
I have a html list of locations - each location is clickable (with href to the relevant weather forecast page).
The user should start typing a location in the search field - and as the location name is typed, a match function should start and autofill the search field.
The user should not see the list - only the search field.
Once the match function has autofilled the search field, user should press go or return - and the link to the relevant weather forecast be activated.
I know some html and javascript, but this one is above my level.
I found this code on stackoverflow Filter search for <ul>. It's something like that - but user must not see the list.
You would have shared a bit info with us:
You know some HTML, but don't wanna show it? We would have helped you better if you just sent us some code! :)
What you'll need
Ok, here is the thing.
First create an input field such as:
<input type="text" name="text" id="text" value="" onkeyup="search()"/>
Then use a function as:
function search () {
var value_field = $('#text').val();
$.ajax({
// create an ajax request here..and get the value
success: function (data) {
$('#div').html(data);
}
});
}
<div id="div"></div>
This will be the div where all the data from ajax would come and display.
Where all the thing is happening
Now the main thing is from the other page. You need to control it to show the data or hide it or whatever you want it to do. That's going to happen on the other page the page where request is going.
You can try to show the data only when there is a perfect match else write this:
$('#div').html('Keep writing, you can match');
And make the user write some more words, who know what he mind match!
User will never see the list
Untill or unless you let him go to the page, untill then he will just see the results you are viewing him! So you should use a Database to show the data when the request is Ajax only, otherwise don't create a connection to the database. This way user would never ever see the list, unless its you! :D
Summary:
And the thing is same, the main process is:
You create a function in the input field to search when there is any word added. Forget the backspace right now.
You will send the value to the next page for processing, get the data, set it to the type you want the user to see.
Display it using `$('selecter').html(data);
Good luck.

populate textfield on selecting dropdown struts2

I have a text <s:select> in my jsp page .
Now what i have to do is when someone selects a value from this dropdown ,
i need to call my action class to get some value based on dropdown selection.
Now this value (which i got from my actionclass) should be shown in the <s:textfield> below this dropdown .
Please help !!
Well all you have to use the power of Ajax.You have multiple options to do this.
User simple Javascript.
User any javascript frameowrk like jquery,DOJO etc
Bind you code with on-click/change even of the Select tag and send a simple request to the S2 action.you can either use Stream result to send data back from the S2 action or better (in my opinion) send back JSON data from your action class and user Jquery build in functionality to parse the JSON data at JSP
user S2 JSON plugin to send and receive JSON data from Action and JSP to make life more easy.
Please follow this tutorial to know how to use JQuery with JSON and struts2
using-struts-2-json-and-jquery
Update
You need to do something like this in your JSP code for Ajax and JQuery
var selectedState = document.getElementById("selectboxid");
var statedata = selectedState.options[selectedState.selectedIndex].value;
var formInput='state='+statedata;
$.getJSON('search/dropDownRenderer',formInput,function(data) {
}

Categories

Resources