redirect not happening

Hello,

I have an increment function in views.py that sends and receives data. At each data reception it increments a value and when this value reaches a threshold it redirects to a page, page2.html

I have the request indicating that it accesses page2 but nothing happens. I always stay on page 1

goToPage2
"POST incremente HTTP/1.1" 302 0
"GET page2 HTTP/1.1" 200 1395

views.py

from django.http import JsonResponse
def page1(request): 
    # load and init data
    request.session["nb"] = 0
   context={"nb": 0} 
   return render(request, 'page1.html',)

def incremente(request): 
    request.session["nb"] = request.session.get("nb") +1
    if(request.session.get("nb") < 5):
         return JsonResponse({"nb": request.session.get("nb")})
    else: 
         print("goToPage2")  
         return redirect("p2")

def page2(request):
    return render(request, "page2.html")  

page1.html

<body>
 <h1 id="title"> </h1>

    <form id="myForm" method="POST">
        {% csrf_token %}
        <button id="submit" type="submit">Valider</button>
    </form>

 <script type="text/javascript">
  document.getElementById("title").textContent = "{{nb}}"

const form = document.getElementById('myForm')
form.addEventListener('submit', sendData);
function sendData(event){
    event.preventDefault();
    const csrf  = $('input[name="csrfmiddlewaretoken"]').val()
    $.ajax({
        type: "POST",
        url: 'incremente', // 
        data: { csrfmiddlewaretoken : csrf, "result": "data" },
        dataType: "json",
        success: function (data) {
              document.getElementById("title").textContent = data["nb"] },
        failure: function () {alert("failure");}
    })
}
</script>
 
</body>   

urls.py

from django.urls import path, re_path
from . import views
urlpatterns = [
    path('page1', views.initQuiz, name="p1"),
    re_path(r'^incremente
, views.incremente),
    path('page2',views.page2,name="p2"),
]

If you’re making the POST through an AJAX call, then it’s up to your handler to do the redirect. A JavaScript AJAX call will not, by itself, cause a full page refresh.

Hello,

I moved the ajax code that was in the js file to the html file and i added this:

const form = document.getElementById('myForm')
form.addEventListener('submit', sendData);
function sendData(event){
     ...
    $.ajax({
        ...
        success: function (data) {
             if(data["nb"] < 5){
              document.getElementById("title").textContent = data["nb"] 
            }
             else{ window.location.assign("{%url 'p2'%}") }
        ...
    })
}

I am redirected to page 2. Thank you for your help

The code didn’t work if i stayed in the js file, I got a url containing this %7B%25url%20’p2’%25%7D
i guess the template language didn’t work in a separate file.

1 Like

See ajax request url syntax error in javascript file - #2 by KenWhitesell for a brief explanation about .js files and render.

In your specific case, you could even return the desired url in the original response as part of the data being returned.

Hey,
If your redirect links are not working, try the following methods to solve the problem:

  • Check your redirect links manually if they contain any unwanted characters or any file format. Remove them and input new, corrected links in the Destination field or the Request field of Simple 301 Redirects plugin.
  • Clear your browser cache before copying the URL.
  • Make sure your WordPress website is updated.

This is the short and quick method to when redirect not working. You can follow this pipeline.