Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

216
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!