0

I have a Django form that makes use of the AJAX. The form works as intended. The problem now is that Django form errors are not shown when invalid input is entered. I followed the Django forms API as described here. Is there a possible way out of this issue?

main.js

$(document).ready(function(){
    $("#itemForm").on('submit', function (e) {
        e.preventDefault();
        var serializedData = $(this).serialize();
        $.ajax({
            type: 'POST',
            url: "post/ajax/myURL/",
            data: serializedData,
            success: function (data) {
                if($('input[type="checkbox"]').prop("checked") == true){
                    // some codes here
                    $("#itemsTable tbody").prepend(
                        // some codes here
                    )
                    console.log("Checkbox is checked. Modal will not be closed");
                }
                else if($('input[type="checkbox"]').prop("checked") == false){
                    // some codes here
                    console.log("Checkbox is unchecked. Modal will now be closed");
                }
            },
            error: function (jqXHR, textStatus, errorText, data) {
                for (var name in data) {
                    for (var i in data[name]) {
                        $('#ajaxErrorMessage').fadeIn().text(errorText) ;
                    }
                }
                setTimeout(function() {
                    $('#ajaxErrorMessage').fadeOut("slow");
                }, 5000 );
                console.log(data.message)
                // more console logs here
            }
        })
    });
});

views.py

def create_item(request):
    # request is sent via ajax
    if request.is_ajax and request.method == "POST":
        form = ItemForm(request.POST)
        data = {}
        if form.is_valid():
            data = form.save()
            # serialize the new item object in json
            data = serializers.serialize('json', [data, ])
            # send data to the client side
            return JsonResponse({"data": data}, status=200)
        else:
            # raise form errors if there is any
            return JsonResponse(data=form.errors.as_json(escape_html=False), safe=False, status=400)
    form = ItemForm()
    return HttpResponse(data=form.errors.as_json(escape_html=False), safe=False, status=400)

1 Answer 1

1

The error function of jQuery.ajax() only receives three arguments (Reference https://api.jquery.com/jquery.ajax/), namely:

jqXHR jqXHR, String textStatus, String errorThrown

If you want the data returned from the ajax call you need to access it from jqXHR:

error: function (jqXHR, textStatus, errorText) {
    let data = jqXHR.responseJSON;
    // If above line does not work, might not since you don't specify `dataType: "json"` use below line
    // let data = $.parseJSON($xhr.responseText);
    // YOUR CODE HERE
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.