Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django/ajax: Unable to get Ajax post data in the views.py

Tags:

ajax

post

django

I had a problem getting ajax post data from django backend, I don't know how to pass the value, please help.

In html I have simply this:

<form id="get_vulns_from_family">
    <label for="family_content">Enter a family name to display the NVTs</label>
    <input id="family_content" />
    <input type="submit" value="search" />
</form>

In javascript I wrote this:

$(function() {
    $("#get_vulns_from_family").submit(function(event) {
        var family_text = $("#family_content").val();
        var family_data = {"family": family_text};
        $.ajax({
            url: "/template_conf/get_vulns_from_family",
            type: "POST",
            data: family_data,
            success: function(response) {
                console.log(response);
            },
            error: function(response) {
                console.log("failed!");
            }
        });
        // prevent default posting of form
        event.preventDefault();
    });
});

In Django method corresponding to url /template_conf/get_vulns_from_family, I tried this:

def get_vuln_from_family(request):
    family = request.POST['family']
    # some other operations to get value for variable "json_data"
    return HttpResponse(simplejson.dumps(json_data))

But django said: MultiValueDictKeyError: "Key 'family' not found in <QueryDict: {}>", which means the POST dictionary is empty. Am I using the wrong way to get post data? If so what should I do? Thanks.

like image 319
Shang Wang Avatar asked Dec 27 '22 13:12

Shang Wang


1 Answers

your url "/template_conf/get_vulns_from_family" is missing a trailing slash. django will typically redirect this to "/template_conf/get_vulns_from_family/", dropping the POST data

like image 73
second Avatar answered Dec 29 '22 03:12

second