Search code examples
javascriptjqueryajaxdjangodjango-csrf

getting POST <my_url> 500 (OK), when using $.ajax POST to send json to django view


Edite: refined the code according to advice in comments but still no luck

Update: thanks ThiefMaster after following your advice I found a bug in my view function but after fixing it now I get in django debug

Forbidden (403)

CSRF verification failed. Request aborted. Help Reason given for failure: CSRF token missing or incorrect.


I trying to use jquery ajax to send json data to django

here is my js code

$("#send").click(function () {
    var events = $('#calendar').fullCalendar('clientEvents');
    console.log(events);
    var filter = [];
    filter[0] = 'start';
    filter[1] = 'end';
    filter[2] = 'title';
    events = JSON.stringify(events, filter, '\t');
    console.log(events);
    $.ajax({
        type: "POST",
        data: {events: events},
        url: <my_url>,
    });
});

on chrome devtool every thing is ok until the last $.ajax()

it throw this error Failed to load resource: the server responded with a status of 403 (OK)

If any one can figure out what I'm doing wrong please go ahead

thanks in advance


Solution

  • data: "events" should be data: events. Your server might not like a non-json payload.

    You also want to add contentType: 'application/json' since you want to post json, not form-encoded values. If you do expect form-encoded values on the server-side though, use data: {events: events} to get a POST data field events containing the JSON string.