I am using:
Python 3.4
Flask 10.1
SQLAlchemy 0.9.6
JQuery 2.1.1
I'm working on a forum application that will show a table of forum threads based on tags selected by the user. The tags are a list of on/off buttons generated as per the below Jinja2 template. (Should be around 8, max 16 tags).
<UL class="ForumTagList">
{% for Tag in Forum.ForumTags.filter_by(Visible=True): %}
<li Class="ForumTag VisibleTrue" id ="liTag{{Tag.TagID}}" >
<input id="{{Tag.TagID}}" type="hidden" value="1" name="Name{{Tag.TagID}}"></input>
<DIV class="Tag{{Tag.TagID}}" onclick="toggle_tag('{{Tag.TagID}}');"> {{Tag.Name}}</DIV>
</li>
{% endfor %}
</UL>
There is a JS script that manages the changing of the values to 0 or 1.
The table will be loaded by an AJAX call as per below. It will initially load an unsorted table but the user will be able to refresh to see if new threads appear.
<script type="text/javascript">
$(document).ready(function(){
ThreadTableRefresh();
});
function ThreadTableRefresh(){
$('#ThreadsHolder').load('{{Forum.ForumID}}/ForumThreads');
}
</script>
<div id="ThreadsHolder">
</div>
I understand from reading the documentation on JQuerys Load Method that I can submit a second argument to the .load() method as an object. I hope to submit the on/off values from the users selection, which will then be used to generate the table only showing the tags the user wants.
I am very new to HTML and JQuery, would anyone be able to point me in the right direction as to how to take the various values from those HTML controls and post them as a list or dictionary to a Flask template?
If you need any addition information, please let me know.
You can send a dictionary or json to your flask template. For each TagID, there is a 1 or 0 value, e.g. {1:0, 2:0, 3:1, 4:0}.
Check out the .ajax jquery function to send a json object to your flask route. This should get you started.
Step by step:
click the refresh button
for each tag, add the id and toggle (1/0) value to a dictionary
convert the dictionary to a json object
use ajax function to send the object to your flask route
flask route takes the values, sends back the new html data
the ajax function will substitute the new html upon success
Javascript
$('#refresh-button').click(function() { //selector for refresh button
data = {}
$('input').each(function(){ //might need more specific selector
id = $(this).attr('id')
toggle = $(this).val()
data[id] = toggle
});
data = JSON.stringify(data);
$.ajax({
url: '/YourFlaskRoute'
type: 'POST',
data: data,
contentType: 'application/json;charset=UTF-8',
cache:false,
success: function (response) {
$(".ForumTagList").html(response); //your flask route needs to send back the html for just your list items
},
error: function(response){
alert('Error refreshing forum items')
}
});
});
Flask
#myblueprint.route('/YourFlaskRoute', methods = ['POST'])
def refresh_tags():
if request.method == 'POST':
data = request.json
#access your data
for key, value in data.items():
key = id
value = id
# run your query
tags = ...
#send back your list items template
return render_template('list_items.html', tags = tags)
Related
Hi I am new to ajax and I have a json response from django with a list of names to be displayed as a list of buttons. I want to disable the button once it is clicked.
Below is the html code I currently write, the button display successfully but it does not do the disable button action.
I would also like to ask what is the scope of this onclick function? Does the function dies at the end of the curly bracket }? Or does this function check even it is out of scope?
<h3>User List:</h3>
<ul id="userLists"> </ul>
$(document).ready(function(){
$.ajax({
type:"GET",
// getUserList is a django views where it query the database and returns JsonResponse of the user's name
url: "{% url 'getUserList' %}",
success: function(response){
$("#userLists").empty();
// Create a list according to number of users in json
for (var key in response.users){
var temp="<button type=\"button\", name=\""+ response.users[key].user +"\", class=\"btn btn-outline-danger\">" + response.users[key].user + "</button>";
$("#userLists").append(temp);
// Here I want to do when clicked, it disables the button and leave others as is.
// Current implementation does not work...
document.getElementsByName(response.users[key].user).onclick =
function(){document.getElementsByName(response.users[key].user).prop('disabled', true)};
};
}
});
})
I have also tried the following implementation, it does not work...
if(document.getElementsByName(response.user[key].user).clicked == true){
document.getElementsByName(response.user[key].user).prop("disabled", true);
};
Thanks all.
getElementsByName returns a node list ... So a collection of matching elements.
That is why .onclick and .prop("disabled", true) have no effect.
if response.users[key].user is to be unique, you can safely use document.getElementsByName(response.user[key].user)[0].
So add [0] to target the first match.
About quotes messing-with, you may be interested in reading about template literals.
Hello everyone I'm currently working on a ASP.NET MVC environment using C#, so right now I'm getting a table from a URL using AJAX and using C# to render it inside my cshtml.
Anyways right now I have a problem where I don't find a way to post data from a button since I'm using javascript mostly to do this I'm kind of lost.
<script>
$(document).ready(function(){
// code to read selected table row cell data (values).
$("#mydataTable").on('click','.btnSelect',function(){
// get the current row
var currentRow=$(this).closest("tr");
// get current row 1st table cell TD value
var col1=currentRow.find("td:eq(9)").html();
var data=col1;
alert(data);
});
});
</script>
Right now this is the script I'm using to get data from the row I want to get data from.
How can I submit this variable at the same time using AJAX to my Controller
I currently use this other script to send data to my controller but it takes the values out of <input> name="", the value I need to get is from a table I render using c# in my cshtml
<script>
function load() {
$.ajax({
url: '#myproject.Models.Base.RootDir()Controller/View',
type: 'post',
dataType: 'text',
contentType: 'application/x-www-form-urlencoded',
data: $("#myForms").serialize(),
success: function (response) {
$('#divToDisplayData').html(response);
},
error: function (error) {
console.log(error);
}
});
}
</script>
If anyone has a question please ask, I'll be around all day
And this is the button I use to submit data
<button class="btnSelect">Seleccionar</button>
You can Pass data inside your form, you just need to take one hidden field inside your form, so when you button clicked, set the value of that hidden field.
<form id="myForms">
//your controlls
//one extra hidden field
<input type="hidden" id="cellValue" />
</form>
Now on button click, set the value of above hidden field.
<script>
$(document).ready(function(){
// code to read selected table row cell data (values).
$("#mydataTable").on('click','.btnSelect',function(){
// get the current row
var currentRow=$(this).closest("tr");
// get current row 1st table cell TD value
var col1=currentRow.find("td:eq(9)").html();
var data=col1;
$('#cellValue').val(data);
});
});
</script>
so finally, when your load() method call, in the $("#myForms").serialize() you will get your cell value in the hidden field control.
Here, you need to take care that whenever you pass html from view to controller, controller will deny your request because it is not safe content. so you need to use [ValidateInput(false)] on your action as below.
public class YourController: Controller{
[ValidateInput(false)]
public ActionResult View()
{
return View();
}
}
When clicking on an button icon:
<a onclick="updateFav({{v.video_id}}, {{v.favorite}});" ><span class="myicons {% if v.favorite == 1 %} heart_active{% else %} heart {% endif %} "></span></a>
I'm using this to change data in my sql database
function updateFav(video_id, favorite) {
$.ajax({
type: "POST",
url: '{{baseurl}}/fav.php',
data:{id:video_id, fav:favorite},
});
}
Depending on database data (0 or 1) heart icon will be gray or red. Clicking on icon works and after refreshing page the changes are visible.
How can I refresh a certain html element? A div for example.
Basically: Have the same effect as the 'star' favorite button on this page (stackoverflow).
To reload a part of a page without refreshing the whole page simply use an ajax request to fetch new data and add it to the div or any element you want see the code below for an example:
$.ajax({
type: "GET",
url: 'getnewData.php',
success:function(response){
$('#myElement').html(response);
},
});
What we did here is we issued an ajax request in which we requested data from getnewData.php and placed the data (which came to us in the response variable) and then we placed the data in the div with an id = myElement
You can go all the way and use a reactive framework or just create a function to update the current element after updateing the database.
When selecting with jQuery $('') or with plain js document.querySelector(), you get a living reference to the DOM element. So you can add/toggle/remove an "active class" to it to styled it as filled with css.
Tricky part here is that you have to keep consistency between the view and the model with your own code. Reactive frameworks or two-way data binding do it for you.
OK. I know this has been tackled many times but I can't find an answer with a useful example of javascript to use.
Say I have this form:
class MyForm(Form):
category = SelectField("Category")
issue = SelectField("Issue")
What I need is for whatever is selected in 'category' at runtime to determine what the user sees in the issue dropdown without a POST of any kind ocurring. I know how to dynamically create the choices in the view from my database query. I even have gone so far as to create a dictionary of "issue choices" based off of category choices.
I just can't for the life of me figure out the javascript I need so that on select of something from the category drop down determines whats in the issue dropdown.
I found the info I needed by looking at the example at Flask jQuery AJAX Example -
- it is a minimal working example, almost a
GIST or a book chapter.
I came up with an example very close to jsbueno's implementation. You can find the Gist here. The .py file is a standalone example.
In your html template use jquery to register an ajax request when you click the select field. If the request is a success the html for the select field gets updated with the new select options (send as a response from the server). Look at the actual HTML generated by the template to see how the select field looks like.
<form action="" method="post" id="selectDevice" name="device">
Nummber of Devices: {{ form.selectAmount(size=1) }}
Select device: {{form.deviceAddress() }}
</form>
<script type="text/javascript" charset="utf-8">
$("#deviceAddress").click(function(){
$.ajax({
url: '/selectform',
type: 'POST',
data: $('#selectDevice').serialize(),
success: function(selectOptions){
$("#deviceAddress").empty();
for (var i = 0; i < selectOptions.length; i++){
$("#deviceAddress").append(
$("<option></option>")
.attr("value", selectOptions[i][0])
.text(selectOptions[i][1])
);
}
}
});
});
</script>
On the server side, use a route for the ajax post request.`As example this route changes the options depending on another form field (the information got send over with the data tag in the ajax request). In WTForms the select field options is a list of tuples containing an ID and name, I kept this the same on the python side.
#app.route('/selectform', methods=['POST'])
def updateselect():
deviceAmount = int(request.form.get('selectAmount'))
choices = [('device{}'.format(i), i) for i in range(deviceAmount)]
response = make_response(json.dumps(choices))
response.content_type = 'application/jsons'
return response`
Only one remark: the ajax request is performed on dropping down and on collapsing. The last part is not necessary of course, there is probably a way to structure the jquery so it only requests on dropdown.
Hi I have been playing around with jqtouch today and I'm just wondering how to manage data.
I tried looking around but couldn't see much documentation.
If I had a list of links for say products? And I click on one i can navigate to the product 'view'. How to I pass variables like you would a $_GET variable to select THAT product?
Or even if I set the id of the link to the id of the record and use JS to grab the ID and somehow pass it to the next view?
Any help with this would be most appreciated!
NOTE: I also want to use it with the offline extension so I'm not sure get ajax would work
Regards,
Billy
You can use the referrer property for the data object. The link would look like:
Product #1
where the HTML ID would correspond to the product ID. Then in the "pageAnimationEnd" event you can retrieve the product details like this:
$('#view').bind('pageAnimationEnd', function (e, info) {
// get the id of the calling href
var id = $(this).data('referrer')[0].id;
$.getJSON('/products/' + id, function (data) {
// do something with the data
});
});
You could look at the demo to see how it does form submission, i.e. AJAX > POST Form Example. Essentially, you create a form and a jQT-style submit button:
<form id="ajax_demo" action="ajax_demo.php" method="POST" class="form">
...
<a class="submit whiteButton" href="#">Submit</a>
</form>
Then in your receiving page (i.e. ajax_demo.php), you can access the form fields, e.g. PHP's $_GET or JavaScript's location.search.
Another way is to store the data in the DOM with jQuery:
// in global level
$('body').data('ajax_demo', "some data for the page");
// in page/view level
$('#ajax_demo').data('key', 'value');