1

I'm trying to send this ajax request to python (with django framework):

$.ajax({
    url: '/search/',
    type: 'post',

    data: {
        mname: mname,
        fname: fname
    },
    success: function (data) {
      console.log("result from python: " + data.result);
    }
});

The view from django views.py:

def my_search(request): before sending here
    if request.method == 'POST':
        mname = request.POST['mname']
        fname = request.POST['fname']

But after sending data I'm getting:

Exception Type: MultiValueDictKeyError

Exception Value: 'mname'

I followed this answer and changed codes like this:

Ajax data part:

data: {
    json_data: JSON.stringify({ info: {'mname':mname,'fname': fname} })
},

views.py:

data_string = request.POST.get('json_data')
data_dict = json.loads(data_string)
mname = data_dict['info']['mname']
fname = data_dict['info']['fname']

But now I get:

Exception Type: TypeError

Exception Value: the JSON object must be str, not 'NoneType'

This obviously somehow related to the first try error which means data sent from ajax is not received by python.

How can I solve this issue?

UPDATE

I used Django Documentations about AJAX And updated my code like this:

var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
var mname = $("#sname").val();
var fname = $("#fname").val();
var json_data = {
            "mname": mname,
            "fname": fname
        };

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);
        }
    }
});

$("#search-btn").click(function(event){
    event.preventDefault();
    $.ajax({
        url: '/search/',
        type: 'post',
        dataType : "json",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(json_data),
        success: function (data) {
          console.log("result from python: " + data.result);
        }
    });
});

Also this post suggests a code to check POST data which I tried an got nothing as output

for key in request.POST:
    print(key)
    value = request.POST[key]
    print(value)

This works where I post data without ajax using form action, But here it gets me nothing.

Any Idea?

Ghasem
  • 14,455
  • 21
  • 138
  • 171

1 Answers1

0

I get the same error when both mname and fname are undefined. Which can be explained by the following code:

obj_str = JSON.stringify({
    mname: undefined,
    fname: undefined,
});

obj_str === "{}"    // true

JSON doesn't support undefined as data type so it simply ignores it when converting the object to string. Same happens with the unsupported types: functions and dates. The result is your AJAX request sending an empty object which explains the error you are getting in your view.

Try testing with hard-coded values:

data: {
    mname: "Smith",
    fname: "John"
},
ikkuh
  • 4,473
  • 3
  • 24
  • 39