Home > other >  Calling view via ajax with submit button works, but hitting enter key just displays ajax dictionary
Calling view via ajax with submit button works, but hitting enter key just displays ajax dictionary

Time:02-21

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.

CodePudding user response:

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}`)
      }
    })
  });
});
  • Related