1

I have a modal where a user can add a new Category. When the user adds a new Category and receives a response from the AJAX request I would like to use the response data to update some of the existing page data. Problem is that my form is not allowing e.preventDefault() but rather just refreshing the page after it receives a response:

JQuery AJAX:

function addCategory(e) {
    let post_url = '{% url "policies-categories-form" %}'
    $.ajax({
        url: post_url,
        type:'POST',
        data: $('#addCategoryForm').serialize(),
        success: function(response){
            console.log(response);
            // document.getElementById('editCategoriesContainer').innerHTML = data;
        },
        error:function(){
            console.log('Error');
        },
    });
};

Form (which is loaded using JQuery, only after a user clicks a button:

{% load crispy_forms_tags %}
<!--Add new category form-->
<div class="form-row mt-4 mb-4">
    <div class="form-group col-md-12 mb-0">
        {{ form.title|as_crispy_field }}
    </div>
</div>
<div class="form-row mt-4 mb-4">
    <div class="form-group col-md-12 mb-0">
        {{ form.parent|as_crispy_field }}
    </div>
</div>
<div class="form-row mt-4 mb-4">
    <div class="form-group col-md-12 mb-0">
        {{ form.groups|as_crispy_field }}
    </div>
</div>
<div class="form-row mt-4 mb-4">
    <div class="form-group col-md-12 mb-0">
        <button class="btn btn-warning btn-block"
                id="addCategoryBtn"
                onclick="addCategory(this)"
                type="submit">
            <span class="fas fa-plus"></span> Add Category
        </button>
    </div>
</div>

View:

@login_required
def policies_categories_form(request):
    if request.method == 'POST' and request.is_ajax():
        form = PoliciesCategoryForm(request.POST, company=request.tenant)
        if form.is_valid():
            form.save()
            categories = PoliciesAndProceduresCategory.objects.exclude(parent__isnull=False).values()
            return JsonResponse({'success': True, 'categories': list(categories)})
        else:
            return JsonResponse({'success': False, 'error': form.errors})
    else:
        form = PoliciesCategoryForm(company=request.tenant)
        context = {'form': form}
        template = 'policies/policies_categories_form.html'
        return render(request, template, context)

How do I stop it from refreshing the page?

Thanks!

David Alford
  • 2,044
  • 3
  • 12
  • 35
  • 1
    Easy fix : change `type="submit"` to `type="button"`or try [this](https://stackoverflow.com/questions/1276870/how-to-pass-an-event-object-to-a-function-in-javascript) way. – Swati Apr 28 '21 at 04:16
  • add e..preventDefault(); in addCategory() function at the top. – Harsimranjit Singh Apr 28 '21 at 04:22
  • I did. did not work. Button needed to be changed as @Swati stated. then I also changed it to : `onclick="addCategory(event)"` and all is well. Thanks! – David Alford Apr 28 '21 at 04:23

0 Answers0