Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

269
Vistas
Django + Ajax: why does it redirect to a new URL and renders the response on browser?

Based on my understanding, ajax could be used to prevent the page from reloading/refreshing/redirecting after submitting a request to the server. However, my code will redirect to display the JSON response. I used e.preventDefault() and it didn't work. Is there anything that I am doing wrong?

My Django code looks like this: views.py:

def projects(request):
    if request.method == 'POST':
        task_id = request.POST.get('task_id')
        myUser = User.objects.get(pk=request.user.id)
        myTask = Task.objects.get(pk = task_id)
        myTask.claimed.add(myUser) #add the user to the task
        return JsonResponse({'status': 'ok'})

    projects = Project.objects.all()
    tasks = Task.objects.all()
    open_tasks = tasks.filter(status='Created')
    proj_dict = {}
    context = {
        'projects' : projects,
        'tasks' : tasks,
        'open_tasks' : open_tasks,
    }
    return render(request, 'projects/projects.html', context)

My HTML:

<form action="{% url 'projects:' %}" method="POST" class='join-form' id='{{task.id}}'>
    {% csrf_token %}
    <input type="hidden" name="task_id" value={{task.id}}>
    <button type="submit" class=" claim-font claim-button">
        Join
    </button>
</form>

Tha ajax call:

<script>
    $(document).ready(function () {
        $('#join-form').on('submit', function (e) {
            e.preventDefault();
            e.stopPropagation();
            const url = $(this).attr('action');
            console.log("here we are");
            const task_id = $(this).attr('id');
            $.ajax({
                type: 'POST',
                dataType: "json",
                headers: { 'X-CSRFToken': csrftoken },
                url: url,
                data: {
                    csrfmiddlewaretoken: '{{ csrf_token }}',
                    task_id: task_id,
                },
                success: function (response) {
                    alert(data);
                    console.log("here we are");
                },
                error: function (response) {
                    console.log('error', response);
                    alert("shit")
                }
            })
            return false;
        });
    });
</script>

Seems like ajax will make sure that my browser doesn't redirect/reload/refresh after the submit button is clicked, and only the server-side changes. However, my browser turns out to be displaying: {"status": "ok"}

Any insights are greatly appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

I noticed that you have class attribute for your form. Change your JQuery selector from $('#join-form') to $('.join-form') for class attributes

<script>
    $(document).ready(function () {
        $('.join-form').submit(function(e) {
            e.preventDefault();
          // write your code here
         });
        
    });
</script>
about 4 years ago · Juan Pablo Isaza Denunciar

0

You need to change button type from "submit" to "button"

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda