Nader Hosny
Nader Hosny

Reputation: 13

Django - template reloads after ajax response

I'm sort of new with Django and I ran through an issue. I'm sending a post request to django view and return the function back with HttpResponse in order to change my template's div contents to the passed value from my view. The issue is: once ajax responds and changes it's div's value; the page instantly reloads. Do you guys have any idea why?

Views.py

def index(request):
if request.is_ajax():
    print("request is ajax")
    details = request.POST.get('id')
    return HttpResponse(details)
else:
    return HttpResponse("Failed)

base.html

<button id="checkres">Check result</button>
<form name="testform" id="testform" method="post">
    {% csrf_token %}
    <input type="text" id="rowfield">
    <input type="submit">
</form>

 $("#testform").submit(function (event){
    $row_num = $('#rowfield').val()
    $("#responseresult").text('checking');
    $.ajax({
        type: "POST",
        url: "/bot",
        data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num},
        success: function(data){
            $("#responseresult").text(data);
            alert(data);
        }
    });
});

Upvotes: 1

Views: 268

Answers (2)

BATMAN
BATMAN

Reputation: 373

Try this for your view

def index(request):
if request.is_ajax():
    print("request is ajax")
    details = request.POST.get('id')
    return JsonResponse(details, safe=False)
else:
    return JsonResponse("Failed" safe=False)

You need to prevent submit as well.

 $("#testform").submit(function (event){
    $row_num = $('#rowfield').val()
    $("#responseresult").text('checking');
    $.ajax({
        type: "POST",
        url: "/bot",
        data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num},
        success: function(data){
            $("#responseresult").text(data);
            alert(data);
        }
    });
    event.preventDefault(); // prevents the page from refreshing.
});

Upvotes: 0

Nalin Dobhal
Nalin Dobhal

Reputation: 2342

Your javascript submit event not calling event.preventDefault(), that's the reason that after ajax response, the is refreshing. Change your javascript function to:

 $("#testform").submit(function (event){
    $row_num = $('#rowfield').val()
    $("#responseresult").text('checking');
    $.ajax({
        type: "POST",
        url: "/bot",
        data: {csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), id: $row_num},
        success: function(data){
            $("#responseresult").text(data);
            alert(data);
        }
    });
    event.preventDefault(); // prevents the page from refreshing.
});

Further read about preventDefault()

Upvotes: 2

Related Questions