简体   繁体   中英

Sending data from a Django template to views.py via Ajax

I am sending some data from html template to views.py via ajax.From the id sent to views.py I am creating sql records. However I was wondering if there is any way to send data from views.py to template to notify that the data is added to sql.

code-

$('#tn1').click(function(){
          var msg='';
          alert('inside alert');
          if ($('textarea#message') != "") {
            var message = $('#notesarea').val();
            alert(message);
            msg=message;
          }


          $.ajax({
        url: 'post_note',
        data: {
          'note': msg
        },

        success: function (data) {
          alert(data)
        }
      });

views.py

def post_note(request,id):
    post_id = request.GET['note']
    print(post_id)
    //sql insertion code,once its done i want to notify to the front end..print some alert message.
    return render(request, './profile.html')

You should use something like JSONResponse in your view, then you data will appear in success function

 success: function (data) {alert(data)}

You can do this using JQuery Ajax in the template and by creating an "API view" in your views.py that is basically just a regular view that returns a JSONResponse after checking to verify the request is Ajax. As an example of the "API" option, using JQuery:

In your views.py file (using the GET method which you should only use if the note is short, will fit into the URL bar, and if you don't have major security concerns, otherwise see the POST example at bottom):

    from django.http import JsonResponse

    def post_note_api(request):
          data = {}
          if request.GET.get('post_note', None) is not None:
              post_note = request.GET.get('post_note')
              # save the note and indicate success
              data['result'] = True
              data['message'] = "Note posted successfully"
              ...
          if request.is_ajax():
             return JsonResponse(data)
          else:
             return HttpResponseBadRequest()
     

In your urls.py:

...
path('/api/post_note/', post_note_api, name="post_note_api"),
...

In your template (if you are using the GET method):

  <script type="text/javascript">
$("#tn1").click(function(){
    var message = $("#myTextArea").val();
    $.ajax({ url: '{% url 'post_note_api' %}?post_note=' + message,
                        type: "GET",
                        dataType: "json",
                        cache: false
               }).done(function(data) {
                    if (data.result === true){
                        alert(data.message);
                   }
               });
          });
       });
</script>

If you are using the POST method instead of GET (which is probably the better option here):

<script type="text/javascript">
        $("#tn1").click(function(){
            var csrfToken = $( "input[name='csrfmiddlewaretoken']");
            var message = $("#myTextArea").val();
                $.ajax({ url: '{% url 'post_note_api' %}',
                                    type: "POST",
                                    dataType: "json",
                                    data: {'post_note':message, 'csrfmiddlewaretoken':csrfToken.val()},
                                    cache: false
                           }).done(function(data) {
                                if (data.result === true){
                                    alert(data.message);
                               }
                           });
                      });
                  });
            </script>

For the POST method, in your view just change request.GET.get('post_note')... to request.POST.get('post_note')... like so:

        from django.http import JsonResponse

        def post_note_api(request):
              data = {}
              if request.POST.get('post_note', None) is not None:
                  post_note = request.POST.get('post_note')
                  # save the note and indicate success
                  data['result'] = True
                  data['message'] = "Note saved successfully"
                  ...
              if request.is_ajax():
                 return JsonResponse(data)
              else:
                 return HttpResponseBadRequest()

When you are sending data via POST don't forget to pass along your CSRF token as in the example above. This assumes you have a form on the page you can get it from, otherwise you can use something like this to get it:

function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = cookies[i].trim();
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
var csrftoken = getCookie('csrftoken');

If you don't want to deal with the CSRF token, you can mark the view with the @csrf_exempt decorator and remove the ' csrfmiddlewaretoken ' data element from the Ajax call in the template, but it may not be ideal or the most secure. An example of that:

    from django.views.decorators.csrf import csrf_exempt
    from django.http import JsonResponse

    @csrf_exempt()
    def post_note_api(request):
           ...

Now, without knowing more, this is basically just pseudocode (plus I just wrote this off the top of my head so it may have errors). If you post more details I can update my answer, but I think this should get you started.

I have used below for sending data from HTML to views.py and then return a success response back to HTML. Hope this can be helpful:)

HTML Code:

<a href="{% url 'save' %}"><button class="button primary fit small" onclick="saveContent()">Save</button></a>

Javascript Code:

<script>
function saveContent(){
var code =editor.getSession().getValue();
var URL = "{% url 'save' %}";
var data = {'code': code};
$.post(URL, data, function(response){ // This is the main function that will help you
    if(response === 'success'){ window.location.reload(); }
    else{ alert('Error! :('); }
});
}
</script>

View.py:

def save_content(request):
    if request.method == 'POST':
        if 'code' in request.POST:
            file_data = request.POST['code']

return HttpResponse('success')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM