mochi mochi - 1 year ago 66
Ajax Question

send url to ajax's success () from Django backend

I want to send data from HTML view to Django backend to process and then the backend will send an url back the to HTML view which will redirect the user to another page. It's like this:

Page 1 ----user's input data --- Ajax --- > backend --- process --- a url to page 2 --- Ajax --> page 2

The problem is that, I don't know how to send the URL back Ajax after processing user's data, so I have to redirect by using window.location.href = '/' . But I think the code is not clean this way. I wonder if there is a way to send url to Ajax's success from backend.

Here is the code n the HTML :

function doSomething(data){
type: "POST",
data: {
'data' : data,

success: function (response) {
window.location.href = '/';
error: function (data) {

Please help me. Thank you!

Answer Source

In your processing view:

from django.http.response import JsonResponse
def whatever_your_view_name_is(request):
    (data processing...)
    return JsonResponse({'url': the_url_to_page_2)

then in your JS:

        success: function (response) {
            window.location.href = response.url;