Accessing Objects Attributes Within Ajax - django

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>

Related

Django and ajax - data returning value but not populating field

I am new to Django and Ajax. I have a dropdown that is populated from a database. I want another field to populate based on the selection made in the dropdown. I am getting the return value, but it is not populating the form field. Console.log shows the value being returned. It just never shows on the form field and I am sure the field name is correct. In the browser I get 600. How do I get the 600 into the #id_Deductable field? Any help would be greatly appreciated.
`
<form method="POST" id="BaseQuoteForm" data-agent-url="{% url 'ajax-load-agent' %}">
{% csrf_token %}
{{ form|crispy }}
<input class="btn btn-success btn-block" type="submit" value="Add">
</form>
<script
src="https://code.jquery.com/jquery-3.6.1.js"
integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI="
crossorigin="anonymous"></script>
<script>
$("#id_Agency").change(function () {
var url = $("#BaseQuoteForm").attr("data-agent-url"); // get the url of the `load_cities` view
var Agency = $(this).val(); // get the selected country ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
data: {
'Agency_id': Agency // add the country id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_cities` view function
console.log(data);
$("#id_Agent").html(data); // replace the contents of the city input with the data that came from the server
}
});
});
</script>
<script>
$("#id_Primary_Plan").change(function () {
var url = $("#BaseQuoteForm").attr("data-agent-url"); // get the url of the `load_cities` view
var PlanData = $(this).val(); // get the selected country ID from the HTML input
$.ajax({ // initialize an AJAX request
url: url, // set the url of the request (= localhost:8000/hr/ajax/load-cities/)
data: {
'PlanData_id': PlanData // add the country id to the GET parameters
},
success: function (data) { // `data` is the return of the `load_cities` view function
console.log(data);
$("#id_Deductable").html(data); // replace the contents of the city input with the data that came from the server
}
});
});
</script>
`

Django & Ajax : data get lost between the view and the template

Using Ajax and Django, my data get lost when sent back to my template and I can't retrieve them.
Here is my code and the logic :
Following the dependent dropdown lists tutorial offered by ["Simple is Better Than Complex"][1]
I have implemented an Ajax request.
Here is the html code:
<p class="multiple-choice" id="mandate-city" data-url="{% url 'officials:ajax_load_mandate_city' %}">Local Mandate: {{ form.mandate_city }}</p>
The ajax request is fired from this script:
<script>
$("#id_departments").change(function (){
var url = $("#mandate-city").attr("data-url");
var departmentId = $(this).val();
$.ajax({
url: url,
data: {
'department': departmentId
},
success: function (data){
$("#id_mandate_city").html(data);
console.log(data);
}
});
});
</script>
After check with console.log, the data are collected by the script. Then, they reach the view.
Here is my view:
def load_mandate_city(request):
department_id = request.GET.get('department')
mandate_city = MandateCity.objects.filter(department_id=department_id).order_by("department")
return render(request, "officials/mandate_city_list.html", {mandate_city: mandate_city})
With a print, I have checked, and the data are treated as planned.
Then the data are sent back through the url:
path('ajax/load_mandate_city/', views.load_mandate_city, name="ajax_load_mandate_city")
They seem not to reach the template:
{% for mandate in mandate_city %}
<option value="{{ mandate.pk}}">{{ mandate.get_mandate_display }}</option>
{% endfor %}
And I could not track them in my script. :-/
Can somebody let me know where the bug is ?
Thanks.
[1]: https://simpleisbetterthancomplex.com/tutorial/2018/01/29/how-to-implement-dependent-or-chained-dropdown-list-with-django.html
did you try to return the information in a json object and then render it with client side js? in general when you use ajax (or fetch) you wanna use the information returned so it's better to return it as a data type,
if you do want to return the html response you should probably not use ajax but rather a form

How to get response back from Django API to Calling HTML Page i am posting an image to Api?

How I can call a Django API from another Django Project (or from any other project) and get the response back after some processing on the same calling page (the page from which I called the API)
I am calling the API from form action ....but API shows the response in a new blank page
Here is API CODE: (//skipping some code to avoid confusion)
def IdealWeight(request):
#defining a list of data to send back to html
list_of_data=[]
list_of_data.append(name)
list_of_data.append(fatherName)
list_of_data.append(registration)
print(list_of_data)
# outPut_Data = ast.literal_eval(list_of_data)
# return render(request,'LibraryForm.html',{'data1':outPut_Data})
return JsonResponse(list_of_data,safe=False)
I want list_of_data on the calling page in some variable.
Here is my HTML Code from which i am calling the API:
<form action="http://127.0.0.1:8000/idealweight/?image/" method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" class="form-control-file" name="image" onchange="readURL(this);" required>
<input type="submit" class=" btn btn-primary" title="Process" value="Process" id="processButton">
</div>
{{ data1 }}
</form>
From HTML page, I am sending a picture to API (API build in Django)
and from that, I want to send an array or list of data extracted from the image and want to show that on same HTML page....................from which I called the API how I can do that?
hope I am clear what I want?
Using an Ajax call would be better choice. you would be doing something along the line.
$(document).ready(function (e) {
$('#upload').on('click', function () {
var file_data = $('#file').prop('file');
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'http://127.0.0.1:8000/idealweight/?image/',
contentType: false,
data: form_data,
type: 'post',
success: function (response) {
// use response to update html
},
error: function (response) {
// use response to update html
}
});
});
});
and your template would be something like
<input type="file" id="file" name="file"/>
<button id="upload" type="button">Process</button>
note: you might get cross origin request block error. so you have to allow that explicitly.

Django: how to add csrf token when prepending a from using ajax

I am adding a comment functionality in my project. And I am using ajax to make it dynamic so that when the user clicks on the comment submit button it will be added in the comment section dynamically without refreshing the page. But the problem is when prepending a form using ajax I cant add csrf token like this
{% csrf_token %}
in the form because ajax wouldn't understand it and take it as text.
function getids(postid){
console.log(postid)
$(postformid).one('submit', function(event){
event.preventDefault();
console.log(event)
console.log("form submitted!") // sanity check
create_comment(posted);
});
}
// AJAX for posting
function create_comment(postid) {
console.log("create comment is working!") // sanity check
console.log(postid)
console.log(talkid)
$.ajax({
url : "create_comment/"+postid, // the endpoint
type : "POST", // http method
data : { the_comment : $(cmtext).val() }, // data sent with the post request
// handle a successful response
success : function(json) {
$(cmtext).val(''); // remove the value from the input
console.log(json); // log the returned json to the console
$(talkid).prepend(
"<div class='col-1 p-0'><form' id=upvote' method='POST'>{%"csrf_token"%}<button
class='btn btn-md btn-outline-danger btn-
block p-auto' id='btnid' onclick='---' type='submit'></button></form></div>");
console.log("success"); // sanity check
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
}
});
};
pretending my form here
<div class="row m-0" id="talk{{post.id}}"></div>
is there any other way around?
Use
{% csrf_token %}
just before the form tag inside your template.

How can I get the href value from a list?

I am trying to get the href value after I click on it, so I can use then the <?php include 'list'; ?> to load the content of the php page I'd clicked before. I was trying something like this:
$(document).ready(function() {
$('list').click(function)
var page=$(href);
<ul id="list">
<li>Mypage </li>
<li>Mypage2 </li>
So I can load a paragraph in my page using the content of the link I clicked before?
You can get the href value, then load the content of the linked page using the proper selectors and any appropriate jQuery ajax function, like ajax() or load().
$(document).ready(function() {
$('#list > li a').click(function(event) {
var page = this.attr("href");
// Here should go your ajax code or what-have-you to load the content.
// If you use an ajax function, the url will be equal to the var page.
event.preventDefault();
$.ajax({
type: "POST", // or "GET" may be better for your needs
url: page,
data: "",
success: function(content) {
console.log("ajax success");
$("#divID").html(content);
},
error: function() {
alert("ajax error");
},
complete: function() {
console.log("ajax complete");
}
});
});
});
<ul id="list">
<li>Mypage </li>
<li>Mypage2 </li>
</ul>
The code was missing the hash telling jQuery to find the id 'list'. The '#list > li a' tells jQuery to apply the code block to all 'li a' children of #list.
//thanks a lot for your response, i real apreciate it
//i finally used this and works fine
$(function() {
$("#team-tabs a").click(function() {
var page= this.hash.substr(1);
$.get(page+".php",function(gotHtml) {
$("#cv-content").html(gotHtml);
});
return false;
});
});
//for this:
<ul id="team-tabs">
<li>name 1</li>
<li>name 2</li>