skip to Main Content

I need to get database objects on the HTML only when the the SUBMIT is clicked and not on page load. I currently have an AJAX script running on the same form where it returns the text entered in textbox onto the HTML when submit is clicked. I want this feature to stay as well as add a new feature of retrieval of data. Below are some of the code snippets I am using:

views.py

@csrf_exempt
def chat(request):
    resps   = Responses.objects.all()
    context = {'resps' : resps}
    return render(request, "chat.html", context)

urls.py

path('chat/', views.chat,  name='chat'),

chat.html

<form id="testForm" name="test-form" class="test-form" action="" method="POST">{% csrf_token %}
  <input id="texting" name="texting" type="text" class="test-text" placeholder="Test here"/>
  <div class="footer">
    <input type="submit" value="SEND">
</form>
</div>
{% for r in resps %}
<div>
  <p>{{r.response}}</p>
</div>
{% endfor %}

................................................

<script type="text/javascript">
      $(document).on('submit','#testForm', function(e){
        e.preventDefault();

        $.ajax({
          type  : 'POST',
          url   : '/chat/',
          data  :{
            text : $('#texting').val(),
            csrfmiddlewaretoken: $('input[text=csrfmiddlewaretoken]').val()
          },
          success : function(){
            // alert("Done!");
            document.getElementById("userSpeaks").innerHTML = document.getElementById('texting').value;
          }
        });
      });
  </script>

Any help would be appreciated. I just need a way out to print the model objects on each click of the submit button and not automatically on page load. Thanks in advance.

2

Answers


  1. Please change the line

    csrfmiddlewaretoken: $('input[text=csrfmiddlewaretoken]').val()
    

    to

    csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val()
    
    Login or Signup to reply.
  2. So you will have to send your querylist as a json object if you want it to be sent through ajax

    from django.http import JsonResponse
    from django.core.serializers import serialize
    
    @csrf_exempt
    def chat(request):
        data = {
                'resps': serialize("json", Responses.objects.all())
            }
            
        return JsonResponse(data)
    

    and you success will look something like this

    success : function(data){
                // alert("Done!");
                resps = JSON.parse(data.resps);
                var htmldata=""
                for(var x in resps){
                htmldata+="<p>"+resps[x].fields.xyz+"</p>"
                }
    
    
                $("#userSpeaks").html(htmldata);
              }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search