Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

225
Visualizações
Calling view via ajax with submit button works, but hitting enter key just displays ajax dictionary

I have a todo list app adds a Task object to the database and appends it to the page, it is working without a problem. However, it only works when I click the submit button, if I hit the enter key, I just see the ajax data in my browser as such:

 {"task": {"id": 1, "title": "example task", "completed": false}}

and I am curious as to why this is and if there is a way to change this functionality? The tutorial I'm following mentioned that on my form I must use <button type="button"> and not <input type = "submit"> because the ladder will "send the forms data directly to the TaskList view, but we want to use another way of sending requests so we need to disable this behavior." I imagine that is what is happening when I hit the enter key?

Code:

html:

<form id = "createTaskForm" method="post" data-url = "{% url 'task_list_url' %}">
  {% csrf_token %}
  {% for field in form %}
    {{ field }}
  {% endfor %}
  <button id = "createButton" type="button">Sumbit</button>
 </form>
    
    
<div id = "taskList">
  {% for task in tasks %}
     {{task.title}}
  {% endfor %}
</div>

JavaScript/jQuery:

$(document).ready(function(){

  $('#createButton').click(function() {
    // Get form data
    let serializedData = $('#createTaskForm').serialize();


    // Now pass it to TaskList view
    $.ajax({
      url: $("#createTaskForm").data('url'),
      data: serializedData,
      type: 'post',
      success: function(response) {
        $("#taskList").append(`${response.task.title}`)
      }
    })
  });
});

Python specific: models.py:

class Task(models.Model):
    title = models.CharField(max_length=200)
    date = models.DateTimeField(auto_now_add=True)
    completed = models.BooleanField(default=False)

urls.py:

path('tasks/', TaskList.as_view(), name = 'task_list_url')

views.py:

class TaskList(View):
    def get(self, request):
        form = TaskForm()
        tasks = Task.objects.all()
        return render(request, 'task/task_list.html', {'form': form, 'tasks': tasks})

    def post(self, request):
        form = TaskForm(request.POST)
        if form.is_valid():
            new_task = form.save()
            # send task object as json response, this return value is what is in success: function(response)
            return JsonResponse({'task': model_to_dict(new_task)}, status=200)
        else:
            return redirect('task_list_url')

Thanks for any help with this.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

You're calling your ajax function onclick which is why it's working when you click on button if you want to call ajax request on enter or on click then you've to use onsubmit change your code like this

$(document).ready(function(){

  $('#createTaskForm').on("submit", function() {
    // Get form data
    let serializedData = $('#createTaskForm').serialize();


    // Now pass it to TaskList view
    $.ajax({
      url: $("#createTaskForm").data('url'),
      data: serializedData,
      type: 'post',
      success: function(response) {
        $("#taskList").append(`${response.task.title}`)
      }
    })
  });
});
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda