0

I am new to Django trying to develop a chatting web project and stuck. Can someone help me which approach I should use? I want to pass textbox data to Python without changing URL and I am not able to pass it. My Javascript code

$("#button").click(function(){
var msg = $('#textbox').val();  
$("<div class='user' id='user'>"+msg+"</div>").insertBefore('.insert_after');
$('.msg_body').scrollTop($('.msg_body')[0].scrollHeight);

I used this ajax code below. However I am not able to retrieve the result in views.py file

$('.ajaxProgress').show();
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/bot/",
        dataType: "json",
        async: true,
        data:{
            csrfmiddlewaretoken: '{{ csrf_token }}',
            message: $('#textbox').val()
        },
        success: function(json){
            $('#test').html(json.message);
            $('.ajaxProgress').hide();
        }
    });
    $('#textbox').val("");

    });

can someone please explain how can I use it in views.py. I am getting a Forbidden error of csrf_token,

  • Forbidden (CSRF token missing or incorrect.): /chat/get this is the error message which I am viewing after running the code. – Soham Kapoor Jul 29 '18 at 05:42
  • as you mentioned you have forbidden error in `/chat/get` then add snippet of that – Onk_r Jul 29 '18 at 06:26
  • Possible duplicate of [Issue with ajax call csfr token](https://stackoverflow.com/questions/51489089/issue-with-ajax-call-csfr-token) – Oh Great One Jul 29 '18 at 08:28

2 Answers2

0

In your js code there is small bug

$(document).ready(function() {
  $("#button").click(function(){
    //some code
    var msg = $('#textbox').val();  
    $('#textbox').val("");                 /*if you are assigning "" to textbox */
    $.ajax({
      type: "POST",
      url: "/bot/",
      dataType: "json",
      async: true,
      data:{
          csrfmiddlewaretoken: '{{ csrf_token }}',
          message: msg                                   /*then here you have to use msg*/
      },
      success: function(json){
        //further code
      }
    });
    $('#textbox').val("");
  });
});

and talking about Forbidden error of csrf_token you have to refer this to resolve

refer working code here

Onk_r
  • 836
  • 4
  • 21
  • Thank you Onk_r. I did put {{csrf_token }} inside my form tag , and added the python code .... However I am still getting the same error – Soham Kapoor Jul 29 '18 at 06:25
  • I am getting an alert box with message as "errorForbidden" I refered success code from that working code which is passing this alert. Not sure why this message is appearing and in console "Forbidden (CSRF token missing or incorrect.)" is displayed. – Soham Kapoor Jul 29 '18 at 06:41
  • can you please connect with me and check if you can help – Soham Kapoor Jul 29 '18 at 07:20
  • your url field in ajax is going wrong you just have to add path after `/` like `/bot/` – Onk_r Jul 29 '18 at 07:33
  • still same error in my machine . though I can see msg is properly pushed in your shared code . Can I share my screen through app to show you the error ? – Soham Kapoor Jul 29 '18 at 07:43
  • I lost the link can you please share the drive link again of working code – Soham Kapoor Jul 30 '18 at 14:51
0

Yeah many people receive this kind of error, put at the end of your html. If you have a base.py which all of your templates extend from, you can also put it in there. This solves the AJAX csrf_token issue. This is probably a duplicate answer, but I cannot find my other post with this code.

{% csrf_token %}
<script type="text/javascript">
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();

function csrfSafeMethod(method) {
    // these HTTP methods do not require CSRF protection
    return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});
</script>

Edit: Found my other post.

Oh Great One
  • 374
  • 2
  • 17