Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ajax post data don't arrive to Django

I am developing a Django application. I am trying using jquery and ajax for a POST request but I am not able to find the error.
I am basically struggling to send the data from the frontend with ajax to the server.

views.py

def add_new_question_feedback(request, pk):
    if request.headers.get('x-requested-with') == 'XMLHttpRequest':
        question = Question.objects.get(id=pk)
        feedback = QuestionFeedback(
        question=question, user=request.user, text=request.POST.get('feedback'), feedback_choice=request.POST.get('feedback_choice'))
        feedback.save()
        feedback = serializers.serialize('json', [feedback])
        return HttpResponse(feedback, content_type='application/json')

models.py

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class QuestionFeedback(models.Model):
    question = models.ForeignKey(Question, on_delete=models.CASCADE)
    user = models.ForeignKey('users.CustomUser', on_delete=models.CASCADE)
    text = models.TextField()
    feedback_choice = models.CharField(
    max_length=200)
    is_closed = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

template

<div class="modal-header">
                <h5 class="modal-title">${gettext(
                  "Question Feedback"
                )} n° ${res[0].pk}</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                    <div class="form-group mt-3">
                        <label class="form-label">${gettext(
                          "Feedback Type"
                        )}</label>
                        <select name="feedback_choice" id="feedback_choice" class="form-control" required="">
                            <option value="" selected="" disabled>${gettext(
                              "Select Topic"
                            )}</option>
                            <option value="Wrong Question">${gettext(
                              "Wrong Question"
                            )}</option>
                            <option value="Wrong Answer">${gettext(
                              "Wrong Answer"
                            )}</option>
                            <option value="Other">${gettext(
                              "Other"
                            )}</option>
                        </select>
                    </div>
                    <div class="form-group mt-3">
                        <label class="form-label">${gettext(
                          "Feedback"
                        )}</label>
                        <textarea name="feedback" id="feedback"  rows="10" class="form-control"></textarea>
                    </div>
                    <button type="button" class="btn btn-success mt-3" id="addFeedback"> ${gettext(
                      "Add New Feedback"
                    )} </button>
                    <button type="button" class="btn btn-danger mt-3 ms-3" data-bs-dismiss="modal">${gettext(
                      "Close"
                    )}</button>
            </div>
      `;

ajax function

$("#addFeedback").on("click", function () {
        $.ajax({
          type: "POST",
          url: "/quiz/add_new_question_feedback/" + questionBtnId,
          data: {
            feedback_choice: $("#feedback_choice").find(":selected").text(), //I can't post feedback_choice to the server
            feedback: $("textarea#feedback").val(), //I can't post feedback to the server
            csrfmiddlewaretoken: csrftoken,
          },
          success: function (response) {
            $("#feedbackModal").modal("hide");
            handleAlerts(
              "success",
              gettext("New Question Feedback sent successfully!")
            );
          },
          error: function (error) {
            $("#feedbackModal").modal("hide");
            handleAlerts("danger", gettext("Oops, something went wrong!"));
          },
        });
      });

My proble is that basically feedback and feedback_choice are not sent to the serve. I know that something is wrong inside my ajax data variable, but I don’t know how to solve it.

>Solution :

The header for XMLHttpRequest is case sensitive. X-Requested-With

def add_new_question_feedback(request, pk):
    if request.headers.get('X-Requested-With') == 'XMLHttpRequest':
        question = Question.objects.get(id=pk)
        feedback = QuestionFeedback(
        question=question, user=request.user, text=request.POST.get('feedback'), feedback_choice=request.POST.get('feedback_choice'))
        feedback.save()
        feedback = serializers.serialize('json', [feedback])
        return HttpResponse(feedback, content_type='application/json')
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading