Home > database >  getting null value when posting data to django using ajax
getting null value when posting data to django using ajax

Time:09-16

Am trynig to post data from an input to my django view to do some processing on this data ,which is a text, and am using AJAX but I get the input NULL in my view

$(document).on('submit', '#post-form',function(e){
    $.ajax({
        type:'POST',
        url:'{% url "index" %}',
        data:{
            inp:$('#qst').val()   
            csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
            action: 'post'
        },
        dataType: 'json',
        success:function(json){
            document.getElementById("post-form").reset();
            $(".messages_area").append('<div class="messages__item messages__item--visitor">' json.inp '</div>')
            $(".messages_area").append('<div class="messages__item messages__item--operator">' json.answer '</div>')
            
        },
        error : function(xhr,errmsg,err) {
        console.log(xhr.status   ":"   xhr.responseText); // provide a bit more info about the error to the console
    }
    
});
});

And this is my view

from .predict_model import respond
def chat(request):
    context={}
    inp=""      
   response_data = {}

    if request.method == 'POST' and request.is_ajax:
        inp = request.POST.get('inp')
        answer=respond(inp)
        response_data['answer'] = answer
        response_data['inp'] = inp
        

        return JsonResponse(response_data)

            
    
        
    return render(request, 'templates/rhchatbot/index.html',context )

But when I print the inp value I get : {'inp':null}

And here is the form where am getting the input:

<form class="chatbox__footer"   method="POST" id='post-form' >{% csrf_token %}
                    <img src="{% static 'images/icons/emojis.svg' %}" alt="" class="icon">
                    <img src="{% static 'images/icons/microphone.svg' %}" alt="" class="icon">
                    <input id='qst' type="text" placeholder="Write a message..." >
                    <button class="send-btn" alt="send-btn" type='submit'>
                        <img src="{% static 'images/send.png'%}">
                    </button> 
                    <img src="{% static 'images/icons/attachment.svg' %}" alt="" class="icon">
                </form>
            </div>

 
   

CodePudding user response:

First you have to add name attribute to the input field:

<input id='qst' type="text" placeholder="Write a message..." name="inp">

then you can try the following:

$("#post-form").submit(function (e) {
    e.preventDefault();
    var serializedData = $(this).serialize();
    $.ajax({
         type: 'POST',
         url: "{% url 'index' %}",
         data: serializedData,
         success: function (json) {
              document.getElementById("post-form").reset();
              $(".messages_area").append('<div class="messages__item messages__item--visitor">' json.inp '</div>')
              $(".messages_area").append('<div class="messages__item messages__item--operator">' json.answer '</div>')

         },
         error: function (xhr,errmsg,err) {
              console.log(xhr.status   ":"   xhr.responseText);
         }
     })
})
  • Related