0

I have a button on a webpage that I would like to have a form pop up when clicked. The problem is, I have no idea how to pass information for html with ajax. I can successfully pass database information with ajax like so:

View:

def ajax_shipping(request):
    id_quote = request.GET.get('quote', None)
    quote = HomeTable.objects.filter(id=id_quote).values_list('quote_num_id', flat=True)
    items = ItemDetails.objects.filter(quote_num_id=quote).values_list('item', 'quan', 'shipped')
    detail_list = []
    for x in items:
        detail_list.append(x)
    data = {
        'item': detail_list
        }
    return JsonResponse(data)

JQuery and Ajax:

$("#id_iden").on('change', function(){
    if ($(this).val() !== ""){
      var qn = $(this).val()
      $.ajax({
        url: "/ship/ajax-shipping/",
        data: { 'quote': qn },
        dataType: 'json',
        success: function(data){
          if (data.item[0]){
            $('#id_item1').val(data.item[0][0])
            $('#id_quan1').val(data.item[0][1])
            $('#id_ship1').val(data.item[0][2])
            var bo = (data.item[0][1]) - (data.item[0][2])
            $('#id_bo1').val(bo)
          }
        }
     })
   }
})

However, I have no idea how to send form and html information while making it popup. I am looking for a tutorial or some guidance so I can achieve this. Thanks.

5
  • I didn't completely understand what you want, but if you want to setup the popup form based on input from source window you should take a look on this link. Commented May 10, 2017 at 17:57
  • That's the idea, but I am wondering if it is possible to do with Ajax becuase I will need to send database information to it Commented May 10, 2017 at 18:02
  • @Evan you need to send info from database to form or the other way around? Commented May 10, 2017 at 19:53
  • @doru I need to send form and html information to Ajax, if that makes sense Commented May 10, 2017 at 19:58
  • @Evan I suppose you want to send info using AJAX to the django view. You don't need ajax to pop up a form. Commented May 10, 2017 at 20:00

1 Answer 1

2
  1. You should use a modal and the easiest way is to use the bootstrap framework which includes a modal plugin.
  2. Probably you want something like this. You have a button on the page which, when clicked ,pops up a modal and in the modal you have a form and another button which, when clicked, sends the form data using AJAX to the handler view.
  3. To send data to your view you have to use the post method in your AJAX code and when you use post you have to send a crsftoken for django to validate the form.

Let's say you have the url to use with ajax /ajax/send-data-through-ajax/ and your form submit button has a class send-data and two input fields with classes name-data and pass-data than you can send this data through AJAX like so:

$(document).ready(function() {

    // AJAX POST
    $('.send-data').click(function(){
      console.log('am i called');

        $.ajax({
            type: "POST",
            url: "/ajax/send-data-through-ajax/",
            dataType: "json",
            data: { "name": $(".name-data").val(),"password": $(".pass-data").val() },
            success: function(data) {
                alert(data.message);
            }
        });

    });


    // CSRF code
    function getCookie(name) {
        var cookieValue = null;
        var i = 0;
        if (document.cookie && document.cookie !== '') {
            var cookies = document.cookie.split(';');
            for (i; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // 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');

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


});

and in your view.py file:

import json
from django.http import Http404, HttpResponse

def ajax_data(request):
    if request.is_ajax() and request.POST:
        data = {'message': "{} added".format(request.POST.get('name'))}
        return HttpResponse(json.dumps(data), content_type='application/json')
    else:
        raise Http404

You have to add ajax url to your urls.py file

url(r'^ajax/send-data-through-ajax/$', views.ajax_data, name = 'ajax-data')

More info on using django and AJAX you can find here:

  1. Basic Ajax
  2. Django by Example
  3. Django JavaScript Integration: AJAX and jQuery
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.