Paul Viorel
Paul Viorel

Reputation: 252

Why Ajax is triggering 500 internal error in django?

Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py).

My Hmtl form does have a csrf_token, so I added the header in ajax function, but still got 500 internal erorr. The data is saved into database but the response is not sent to ajax function.

View.py

## Ajax
@login_required
def SubmitModal(request):
    if request.method == 'POST':
        text = request.POST['Text']
        date = request.POST['DatePicker']
        time = request.POST['TimePicker']
        
        T = SText()
        
        T.User = request.user
        T.Text = text
        T.STime = date + ' ' + time
        T.save()

        return HttpResponse(json.dumps({'success': True}), content_type="application/json")
    else:
        return JsonResponse({'success': False})

file that contains ajax

$(document).ready(function () {
    // Show the modal window when a button is clicked
    $('#open-modal').click(function () {
        $('#modal').modal('show');
    });

    // Close the modal window when a button is clicked
    $('.close-modal').click(function () {
        $('#modal').modal('hide');
    });
    
    // Handle the form submission
    $('#modal-form').submit(function (event) {
        event.preventDefault(); // Prevent the form from being submitted
        var formData = $(this).serialize(); // Get the form data
        // Submit the form data to the server using an AJAX request
        $.ajax({
            type: 'POST',
            url: '/submit/',
            headers: {'X-CSRFToken': '{{ csrf_token }}'},
            data: formData,
            dataType: "json",
            success: function (response) {
                if (response.success) {
                    $('#success-message').show();
                } else {
                    $('#error-message').show();
                }
            },
             error: function (xhr, status, error) {
        console.log(error);
    }
        });
        $(".textarea-input")[0].value = '';
        $(".date-input")[0].value = '';
        $(".time-input")[0].value = '';
    });
});

Upvotes: 0

Views: 60

Answers (1)

Magitrek
Magitrek

Reputation: 567

If you're reproducing this in a non-production environment, you can set DEBUG=True in the settings file. Then when you make the call from your browser, the response will include details about what the issue is. You can also set the ADMINS variable to send exception tracebacks to the specified emails when they're encountered. More details here.

You can view the data being sent and received in the developer tools of the browser you are using.

Upvotes: 1

Related Questions