Olivier Morissette Olivier Morissette - 5 days ago 6
Ajax Question

Http302 Response when using Ajax to post to Django view

I'm trying to build a web app that takes input using ajax. The input is sent server-side to Django and I'm having a hard time with getting the url to redirect properly. I understand that the issue at the moment has something to do with the django translation application.

Here's the relevant sections.

Ajax

$(document).ready(function(){
$('#applicant_form').on('submit', function(event){
event.preventDefault() //this will stop the file from submitting the form manually.
$.ajax({
url :'/save_applicant/', // the endpoint
type : "POST", // http method
data : { the_post : "Yay" }, // data sent with the post request
dataType: "json",
// handle a successful response
success : function(json) {
console.log("success"); // another sanity check
},

// handle a non-successful response
error : function(xhr,errmsg,err) {
$('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
" <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
}
});
});
});


HTML/DJANGO TEMPLATES

<form method = "POST" action = "" class="form bgform" id="applicant_form">
{% csrf_token %}
{{ applicant_form|crispy }}
<input class="btn btn-default" type="submit" name="Save" />
</form>


views.py

def save_applicant(request):
if request.method =='POST':
id = None
if 'applicant' in request.session:
id = request.session['applicant']

applicant_form = ApplicantForm(request.POST)
if applicant_form.is_valid():
session_applicant = applicant_form.save(commit=False)
if id:
session_applicant.id = id
else:
session_applicant.save()
request.session['applicant'] = session_applicant.id
return HttpResponse(json.dumps({'status':'applicant_saved'}), content_type='application/json')

else:
return HttpResponse(applicant_form.errors.as_json(),content_type='application/json')

else:
return HttpResponse(json.dumps({'status':'not_post'}),content_type='application/json')


urls.py

from django.conf.urls import include, url
from django.contrib import admin
from django.conf.urls.i18n import i18n_patterns

urlpatterns = [
]
urlpatterns += i18n_patterns(
url(r'^$', 'plan_b_profile.views.home', name='home'),
url(r'^save_applicant/','plan_b_profile.views.save_applicant',name='save_applicant'),
url(r'^admin/', include(admin.site.urls)),
)


Command Line

[21/Aug/2015 20:53:43]"POST /save_applicant HTTP/1.1" 302 0
[21/Aug/2015 20:53:43]"GET /en/save_applicant/ HTTP/1.1" 200 22 <---- HOW TO FIX THIS


Thanks Again!

Answer

I think that best solution for this problem will be to dynamically assign post url in JavaScript.

Rewrite your template, so you can store somewhere your URL reversed by django, for example in action of form:

<form method = "POST" action="{% url "save_applicant" %}" class="form bgform" id="applicant_form">
    {% csrf_token %}
    {{ applicant_form|crispy }}
    <input class="btn btn-default" type="submit" name="Save" />
</form>

And post AJAX to that URL instead of static one, it will be already with language prefix, so redirect won't happen:

$(document).ready(function(){
  $('#applicant_form').on('submit', function(event){
    event.preventDefault() //this will stop the file from submitting the form manually.
    $.ajax({
        url :$(this).attr('action'), // the endpoint
        type : "POST", // http method
        data : { the_post : "Yay" }, // data sent with the post request
        dataType: "json",
        // handle a successful response
        success : function(json) {
            console.log("success"); // another sanity check
        },

        // handle a non-successful response
        error : function(xhr,errmsg,err) {
            $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+
                " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom
            console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console
        }
    });
  });
});
Comments