skip to Main Content

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


  1. 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

    from django.urls import path
    from . import views
    
    urlpatterns = [
        path('process_selected_divs/', views.process_selected_divs, name='process_selected_divs'),
    ]
    

    Create a view function in your Django app’s views.py

    from django.http import JsonResponse
    
    def process_selected_divs(request):
        if request.method == 'POST':
            selected_divs = request.POST.getlist('selected_divs[]')
            # Process the selected_divs list as required
            return JsonResponse({'message': 'Success'})
    
        return JsonResponse({'message': 'Invalid request method'})
    

    Finally, add a CSRF protection for AJAX in your JavaScript file and send the data using AJAX.

    $(document).ready(function () {
      // Get CSRF token
      const csrf_token = document.querySelector('[name=csrfmiddlewaretoken]').value;
    
      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));
    
        // Send the data to the Django view
        $.ajax({
          url: '/process_selected_divs/',
          method: 'POST',
          data: {
            csrfmiddlewaretoken: csrf_token,
            selected_divs: selectedDivs
          },
          success: function (response) {
            console.log(response);
          },
          error: function (error) {
            console.log(error);
          }
        });
      });
    });
    

    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.

    Login or Signup to reply.
  2. 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 :

    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <!-- HTML form with input fields -->
    <form id="myForm">
      <input type="text" name="name" placeholder="Enter your name">
      <input type="email" name="email" placeholder="Enter your email">
      <button type="submit">Submit</button>
    </form>
    
    <!-- AJAX script -->
    <script>
    $(document).ready(function() {
      $('#myForm').on('submit', function(e) {
        e.preventDefault(); // Prevent the default form submit behavior
    
        $.ajax({
          type: 'POST',
          url: '/submit/',
          data: $(this).serialize(), // Serialize form data as a string
          success: function(response) {
            alert(response.message); // Show the response message from the backend
          },
          error: function(error) {
            console.log(error);
          }
        });
      });
    });
    </script>
    
    

    And the backend part :

    from django.views.generic import View
    from django.http import JsonResponse
    
    class SubmitFormView(View):
        def post(self, request, *args, **kwargs):
            name = request.POST.get('name')
            email = request.POST.get('email')
    
            # Do something with the form data
            # For example, save it to a database
    
            response_data = {'message': 'Form submitted successfully.'}
            return JsonResponse(response_data)
    
    

    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:

    from myapp.views import SubmitFormView
    
    urlpatterns = [
        path('submit/', SubmitFormView.as_view(), name='submit'),
        # other URL patterns...
    ]
    
    

    Also feel free to use walrus for parsing data

    Take a look

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search