[Django]-Send a javascript variable to django view

2👍

You have two way – using form and using ajax for sending data.

Assume that you have data called result_data in js.

First, use existing form

In this way, you have to update your inner data to form field (i.e. make hidden result_data field to send form data).

<form name='urlForm' method="post" action="{% url 'create_url'%}" id="create" >
    {% csrf_token %}
    <input type="text" id="myurl" name="field"/>
    <input type="hidden" name="result_data" value="" id="js_data_input">
    <input type="submit" name="submit" value="Submit">
</form> 

Then you add javascript code to add your result_data to your hidden input value. Maybe like this..
(I’m not good at javascript, so make it your own way)

<script>
    $('#js_data_input').val(result_data)
</script>

Then just submit your form with this data.

Second, use ajax

If you send your data without submit form (it means that not reload/escape current page), you can use ajax.

When using ajax, you have to make other view that receive your ajax request.

If you don’t know about ajax, please check w3school or other web site.

This is example for send result_data using ajax

  $.ajax({
    type: "POST",
    url: '/your/path/to/ajax_view/url/',
    data: {
      'result_data': result_data,
      'csrfmiddlewaretoken': '{{ csrf_token }}'
    },
    dataType: "json",
    success: function(response) {
      if (response.result == 'ok') {
        alert(response.message);
      } else {
        alert('Failed');
      }
    }
  })

You have to add csrfmiddlewaretoken. Else, you got 403 forbidden error. You can make csrfmiddlewaretoken by js or just using {{ csrf_token }} from django.

Leave a comment