I’m making a recipe generator website where each ingredient is an image inside a div. When that div is clicked, it toggles to another colour. When submit is clicked, I want the ids of all the selected divs to be consolidated into one array. I’m able to achieve this using JavaScript, using the following code.
$(document).ready(function () {
var selectedDivs = [];
$(".square").click(function () {
$(this).toggleClass("selected");
var divId = $(this).attr("id");
var index = selectedDivs.indexOf(divId);
if (index === -1) {
selectedDivs.push(divId);
} else {
selectedDivs.splice(index, 1);
}
});
$("#submit").click(function () {
$("#result").text("Selected Divs: " + JSON.stringify(selectedDivs));
});
});
How do I now send this data to the views.py file in my Django project, where it can become a list? Or is there a way to achieve this functionality directly in the python file itself?
I tried using AJAX but I’m not sure how to link the pages properly.
2
Answers
You can definitely use AJAX to send data from your JavaScript to Django.
Here’s an example.
Do you have a urls.py?
You create a URL route there
Create a view function in your Django app’s views.py
Finally, add a CSRF protection for AJAX in your JavaScript file and send the data using AJAX.
So when the submit button is clicked, the JavaScript sends and AJAX post request to the process_selected_divs URL, which calls the process_selected_divs view function in your views.py.
The selected_divs array is sent as part of the POST request, then the view function returns a JSON response that you can use.
U can use ajax for this , but there is some other way too. Here’s an example of using ajax
And handling data in views.
Front part Using ajax :
And the backend part :
In this example, we define a CBV called SubmitFormView that handles the AJAX POST request. The post method of this view extracts the form data from the request, processes it, and returns a JSON response with a success message.
To wire up this view to a URL, you can add the following line to your urls.py file:
Also feel free to use walrus for parsing data
Take a look