Django Ajax Dropdown Select2 not return data - django

There is a dropdown form that I created with ajax. The form works without using the Select2 tag and returns data. But when I enter the select2 tag, it does not show the detail that should be displayed according to the selection.
I use select2 for all select fields in the system. That's why I defined the select2 tag on my layout template like this.
<script>
$('.select').select2({
allowClear: true
});
</script>
Here is my ajax code :
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$("#id_worksite_id").change(function () {
const url = $("#subunitForm").attr("data-subunit-url");
const worksiteId = $(this).val();
$.ajax({
url: url,
data: {
'worksite_id': worksiteId
},
success: function (data) {
$("#id_upper_subunit_id").html(data);
}
});
});
Thank you for your help, best regards

Related

Accessing Objects Attributes Within Ajax

I am adding ajax to my website. I originally had this button:
{% for item in notifications %}
<a class='delete' href="{% url 'delete' item.slug %}">
But changed it to Ajax.
{% for item in notifications %}
<a class='delete'>
$(document).on('click', '.delete', function (e) {
$.ajax({
url: '/users/ajax/delete/',
data: {
// here I was to call the 'delete' function in the 'django.notifications' package
// something like 'notifications.delete(slug)'
},
dataType: 'json',
success: function (data) {
alert("Working");
}
});
});
This Ajax fires correctly, but I don't know how to get item.slug in Ajax. I guess I could do this <a class='delete' slug="{{ item.slug }}"> and access the slug, but it seems really sloppy.
Is there a way to pass an object's attributes to Ajax without setting it as a value within the html code itself?
Thank you.
You can store the value of the notification in a variable while rendering the HTML as shown below in the HTML section. Once you have notifications value in your script code. You can check the index of the clicked anchor and retrieve the item associated with that index.
$(document).on('click', '.delete', function(e) {
let elem = $(this);
$.ajax({
url: '/users/ajax/delete/',
data: {
// here I was to call the 'delete' function in the 'django.notifications' package
// something like 'notifications.delete(slug)'
},
dataType: 'json',
success: function(data) {
alert("Working");
//new code below
let index = $("a.delete").index(elem);
let item = notifications[index];
//You can access slug and other attributes of item now.
}
});
});
<script>
const notifications = {% notifications %}
</script>

Django: how to get a javascript value from template to view?

I am currently using Django framework.
I would like to get the value of a javascript value wrote in an html file.
I would like to be able to display it in my view file
Here is my html file from the folder templates:
<script>
var toto = "javascript";
document.write(toto)
</script>
This is my view file:
def javascript(request):
# print the javascript value here
return render(request, "rh/javascript.html")
Thank you for your help !
You have to consider that your script runs on the client-site whereas the view function runs on the server-side. This is one main challenge when it comes to shifting variables from one end to the other.
To make a long story short:
You will have to make a http request from the client-site (for example using jQuery AJAX) to call the view. Then you can pass the variable via AJAX to the view function and use it for further logic.
Example:
your.html
<script type="text/javascript">
// A CSRF token is required when making post requests in Django
// To be used for making AJAX requests in script.js
window.CSRF_TOKEN = "{{ csrf_token }}";
</script>
<div id="variable">Variable</div>
javascript
(function($) {
// trigger the logic on click of the container
$('#variable').on('click', function() {
// assign variable
var variable_for_view = $(this).html();
// make http request using AJAX
$.ajax({
type: 'post',
url: '/your_url/', // this is the mapping between the url and view
data: {
'variable': variable, // ! here is the magic, your variable gets transmitted to the server
'csrfmiddlewaretoken': window.CSRF_TOKEN
},
success: function(data) {
print(sliced_variable)
},
});
});
}(jQuery));
views.py
def your_view(request):
# Assign variable from AJAX request
variable = request.POST.get('variable')
print(variable)
variable.slice(3)
context = {
'sliced_variable': variable
}
return render(request, 'your.html', context)

React JSX and Django reverse URL

I'm trying to build some menu using React and need some Django reverse urls in this menu. Is it possible to get django url tag inside JSX? How can this be used?
render: function() {
return <div>
<ul className={"myClassName"}>
<li>Menu item</li>
</ul>
</div>;
}
You could create a script tag in your page to inject the values from Django into an array.
<script>
var menuItems = [
{title: 'Menu Item', url: '{% url "my_reverse_url" %}'},
{title: 'Another Item', url: '{% url "another_reverse_url" %}'},
];
</script>
You could then pass the array into the menu through a property.
<MyMenu items={menuItems}></MyMenu>
Then loop over it to create the list items in your render method.
render: function(){
var createItem = function(itemText) {
return <li>{itemText}</li>;
};
return <ul>{this.props.items.map(createItem)}</ul>;
}
This will keep your component decoupled and reusable because the logic for creating the data and the logic for displaying the list items is kept separate.

Opencart Ajax load on Product Filters

Currently I have following JavaScript in my filter.tpl file. This has hidden the refined search button and filters product on checkbox click. But It loads the whole page on a check box click. I want to implement AJAX loader so that only the page loads partially.
<script type="text/javascript"><!--
$(document).ready(function() {
$('#button-filter').hide();
$('input[name^=\'filter\']').on('change', function() {
filter = [];
$('input[name^=\'filter\']:checked').each(function(element) {
filter.push(this.value);
});
location = '<?php echo $action; ?>&filter=' + filter.join(',');
});
});
//--></script>

How to dynamically assign form id to jquery function in rails with erb

I'm implementing Ace text editor into a form partial that I'm using for all my settings. The form id is something like "edit_setting_#{#setting.id}". I've got the text editor substituting for the field and it works perfectly when I hard-code the form id. How do I set it dynamically?
<script>
$(document).ready(function(){
var editor = ace.edit('editor');
editor.setTheme('ace/theme/twilight');
$('#setting_value').hide();
$("#edit_setting_16").submit(function(){
$('#setting_value').val(editor.getSession().getValue());
});
});
</script>
I was over-complicating it.
<script>
$(document).ready(function(){
var editor = ace.edit('editor');
editor.setTheme('ace/theme/twilight');
$('#setting_value').hide();
$("#edit_setting_<%= #setting.id %>").submit(function(){
$('#setting_value').val(editor.getSession().getValue());
});
});
</script>