I have set up a checkbox that should appear with each row in the list. I would like to pass row.id and boolean based on checkbox state. But the problem is that it only works for the first checkbox: id and boolean state is passed.
{% for row in list %}
....
<label>
Off
<input name="active{{ row.id }}" id="active{{ row.id }}" type="checkbox" list_id="{{ row.id }}">
<span class="lever"></span>
On
</label>
....
{% endfor %}
I have added javascript to listen to checkbox state and after checking, send a POST request to Flask app. It works but it only fires when the first checkbox is checked, all other checkboxes generated by Jinja2 are ignored.
document.addEventListener('DOMContentLoaded', function () {
var checkbox = document.querySelector('.input[type="checkbox"]');
checkbox.addEventListener('change', function () {
var list_id = $(this).attr('list_id');
if (checkbox.checked) {
req = $.ajax({
url : '/dashboard',
type : 'POST',
data : { id: list_id, active : 'true' }
});
console.log(list_id);
} else {
req = $.ajax({
url : '/dashboard',
type : 'POST',
data : { id : list_id, active: 'false' }
});
console.log(list_id);
}
});
});
You only get the first when you use querySelector
you have a dot in front of the input that should not be there
You have jQuery, so use it - it will take all checkboxes in one go without the need for querySelectorAll
$(function() {
$('input[type="checkbox"]').on('change', function() {
var list_id = $(this).attr('list_id');
console.log(list_id);
req = $.ajax({
url: '/dashboard',
type: 'POST',
data: {
id: list_id,
active: this.checked ? 'true' : 'false'
}
});
});
});
Related
Based on my understanding, ajax could be used to prevent the page from reloading/refreshing/redirecting after submitting a request to the server. However, my code will redirect to display the JSON response. I used e.preventDefault() and it didn't work. Is there anything that I am doing wrong?
My Django code looks like this:
views.py:
def projects(request):
if request.method == 'POST':
task_id = request.POST.get('task_id')
myUser = User.objects.get(pk=request.user.id)
myTask = Task.objects.get(pk = task_id)
myTask.claimed.add(myUser) #add the user to the task
return JsonResponse({'status': 'ok'})
projects = Project.objects.all()
tasks = Task.objects.all()
open_tasks = tasks.filter(status='Created')
proj_dict = {}
context = {
'projects' : projects,
'tasks' : tasks,
'open_tasks' : open_tasks,
}
return render(request, 'projects/projects.html', context)
My HTML:
<form action="{% url 'projects:' %}" method="POST" class='join-form' id='{{task.id}}'>
{% csrf_token %}
<input type="hidden" name="task_id" value={{task.id}}>
<button type="submit" class=" claim-font claim-button">
Join
</button>
</form>
Tha ajax call:
<script>
$(document).ready(function () {
$('#join-form').on('submit', function (e) {
e.preventDefault();
e.stopPropagation();
const url = $(this).attr('action');
console.log("here we are");
const task_id = $(this).attr('id');
$.ajax({
type: 'POST',
dataType: "json",
headers: { 'X-CSRFToken': csrftoken },
url: url,
data: {
csrfmiddlewaretoken: '{{ csrf_token }}',
task_id: task_id,
},
success: function (response) {
alert(data);
console.log("here we are");
},
error: function (response) {
console.log('error', response);
alert("shit")
}
})
return false;
});
});
</script>
Seems like ajax will make sure that my browser doesn't redirect/reload/refresh after the submit button is clicked, and only the server-side changes. However, my browser turns out to be displaying: {"status": "ok"}
Any insights are greatly appreciated!
I noticed that you have class attribute for your form. Change your JQuery selector from $('#join-form') to $('.join-form') for class attributes
<script>
$(document).ready(function () {
$('.join-form').submit(function(e) {
e.preventDefault();
// write your code here
});
});
</script>
You need to change button type from "submit" to "button"
i have select2 dropdown like:
<select class="form-control validateblank txtSelectChallan" id="txtSelectChallan" />
and i am setting dropdown data by ajax call like:
$.ajax({
type: "POST",
url: "/Account/MaterialSheet.aspx/GetMaterialSheetByLedgerId",
data: '{LedgerId: "' + AccId + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d.Result == "OK") {
var challanresults = [];
$.each(data.d.Records, function (index, challn) {
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
});
eachtr.find('.txtSelectChallan').select2({
placeholder: "Select Challan",
data: challanresults,
multiple: true
});
swal.close();
challanresults = null;
}
},
error: function (err) {
swal(
'Oops...',
'Error occured while retrieving data',
'error'
);
}
});
and i get dropdown like :
<select class="form-control validateblank txtSelectChallan select2 hidden-accessible" id="txtSelectChallan" tabindex="-1" aria-hidden="true" multiple="">
<option value="1006">123123</option>
<option value="1007">32123</option>
i have tried to set option attribute using:
challanresults.push({
id: challn.MaterialSheet_ID,
text: challn.Challan_No,
Amount: challn.Total_Amount
});
but i cant get amout as option attribute any idea how to set custom attribute for all option in select2?
Try like this inside foreach loop, and set the trigger after that.
var data = {
id: challn.MaterialSheet_ID,
text: challn.Challan_No
};
var newOption = new Option(data.text, data.id, false, false);
$('#txtSelectChallan').append(newOption).trigger('change');
Check this link for further solution on custom attributes
Or Simply you can do like this in a loop for the result set
var option = "<option value="+challn.MaterialSheet_ID+" amount="+challn.Total_Amount+">"+challn.Challan_No+"</option>
This is what Select2 Official Site has to say about custom-data-fields
$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});
// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
Click here for the above reference link
I am working on a flask web app and I am trying to implement the like comment feature with jQuery so that the page does not have to reload when the like button is clicked. Below are my codes. Any help will be much appreciated.
route:
#main.route('/like-comment/<int:id>', methods=["GEt", "POST"])
def like_comment(id):
comment = Comment.query.filter_by(id=id).first()
if comment is None:
flash('This comment is invalid or has been deleted by the user')
return redirect(url_for('.home'))
current_user.like_comment(comment)
return jsonify({'result' : 'success', 'like_comment' : current_user.like_comment(comment)})
JavaScript:
$(document).ready(function() {
$('.like').on('click', function () {
var comment_id = $(this).attr('comment_id');
req = $.ajax({
url : '/like-comment',
type : 'POST',
data : {
like_comment : current_user.like_comment(comment),
id : comment_id
}
});
req.done(function (data) {
$('#like'+comment.id).text(data.like_comment);
});
});
});
HTML:
{% if not current_user.is_liking_comment(comment) %}
<button class="like btn btn-pill btn-warning btn-xs" comment_id="{{ comment.id }}">
<span class="icon icon-thumbs-up" id="like{{ comment.id }}"></span> Like
</button>
{% else %}
I don't use flask, but I see you're using an attribute "comment_id", is that a Flask thing? Otherwise, you should use "data-"...
In your HTML...
<button class="like btn btn-pill btn-warning btn-xs" data-comment_id="{{ comment.id }}">
And then in jQuery...
var comment_id = $(this).data('comment_id');
But I think the problem is that your returning JSON and you haven't indicated that to your $.ajax call...
$(document).ready(function() {
$('.like').on('click', function(event) {
event.preventDefault();
var comment_id = $(this).attr('comment_id');
$.ajax({
url : '/like-comment',
type : 'POST',
data : {
like_comment : current_user.like_comment(comment),
id : comment_id
},
dataType='json'
})
.done(function (data) {
$('#like'+comment.id).text(data.like_comment);
});
});
});
Or if you don't want to use Promises...
$(document).ready(function() {
$('.like').on('click', function(event) {
event.preventDefault();
var comment_id = $(this).attr('comment_id');
$.ajax({
url : '/like-comment',
type : 'POST',
data : {
like_comment : current_user.like_comment(comment),
id : comment_id
},
dataType='json',
success: function(data) {
$('#like'+comment.id).text(data.like_comment);
}
});
});
});
Let me know if it helps...
Try adding an action to your data object to call the function on the server. See below:
data: {
action: like_comment, //or the name of your function on the server
like_comment: current_user.like_comment(comment),
id: comment_id,
},
I have a list of brands and categories. One brand can have multiple categories.
{% for brand in brands %}
<li><input type="radio" value="{{brand.title}}" name="brand">{{brand.title}}</li>
{% endfor %}
{% for category in categories %}
<li><input type="checkbox" value="{{category.title}}" name="category" > {{category.title}}</li>
{% endfor %}
<input type="submit" value="submit" id="brand_category">
<script>
var parameter = [];
var brand = [];
var category = [];
$('#brand_category').click(function(event) {
$("input:checkbox[name=category]:checked").each(function(){
if ($(this).prop("checked", true)) {
category.push($(this).val())
}
});
parameter.push({
brand : $("input[type='radio']:checked").val(),
category: category
})
var json = JSON.stringify(parameter);
$.ajax({
type: "post",
url: "{% url 'seller_details' %}",
data: {
'parameter[]' : json ,
csrfmiddlewaretoken: '{{csrf_token}}'
},
contentType: 'application/json; charset=utf-8',
dataType:"json",
success: function(data) {
$('#loading-image').hide();
},
error: function(response, error) { }
});
});
</script>
I tried to send brand and category from the above script but it retains old data in the arrays brand, category and parameter. Is this the correct way to send data for the above scenario?
It sounds like you're defining the category array outside of the click handler and you're not clearing it's values between clicks. Also note that the if statement in the each block is redundant as the selector is only retrieving elements which are checked.
To solve the issue you can either change the code so that the array is defined inside the handler:
$('#brand_category').click(function(event) {
var category = [];
$("input:checkbox[name=category]:checked").each(function(){
category.push($(this).val());
});
// rest of your code...
});
Alternatively you can generate the array from scratch on each click:
var category = [];
$('#brand_category').click(function(event) {
category = $("input:checkbox[name=category]:checked").map(function() {
return this.value;
}).get();
// rest of your code...
});
I am using JQuery ajax to load some data when user selects something from the list. How do i pass value of selected option in action parameters?
I tried by creating variable selectedValue but it says name "selectedValue" does not exists.
<script>
$(document).ready(function () {
$("#students").change(function () {
var selectedValue = $("#students").val();
$.ajax({
url: '#Url.Action("GetData", "Sample", new { table = "Students", id = selected })',
type: "GET",
success: function (result) {
$("#information").html(result);
}
});
});
})
</script>
Are you using the correct variable ? It looks like you are reading the value to selectedValue but not using that. Try this
var selectedValue = $("#students").val();
$.ajax({
url: '#Url.Action("GetData","Sample")?table=Students&id ='+selectedValue,
type: "GET",
success: function (result) {
$("#information").html(result);
}
});
This should work assuming your GetData action method has 2 parameters named table and id
public ActionResult GetData(string table,string id)
{
//to do : return something useful
}
the code that will work for you depends on how you route is setup, but regardless of how you have it setup you will have to append that selected value on the client side.
Assuming this style of route:
/Sample/GetData?table=Students&id=3
This should work for you:
<script>
$(document).ready(function () {
$("#students").change(function () {
var selectedValue = $("#students").val();
$.ajax({
url: '#Url.Action("GetData", "Sample", new { table = "Students" })' + '&id=' + selectedValue,
type: "GET",
success: function (result) {
$("#information").html(result);
}
});
});
})