[Answered ]-Can't get AJAX POST working in Django

2๐Ÿ‘

โœ…

I will point out several things to correct, some are just ways to do it in a django manner and not problems.

In your view

 return HttpResponse(
            json.dumps({'result': 'ok',}),
            content_type="application/json"
        )

In your ajax

url: "/add_share_points",

should be:

url : {% url '<name in url.py>' %},

and you need to add (to the data object):

 csrfmiddlewaretoken: '{{ csrf_token }}'

Inside the ajax request, insert this after data:

// handle a successful response
success : function(json) {
     if (json.result=== 'ok'){
         console.log('It works!');
     }else{
         console.log('Something wrong with response');
     }
// handle a non-successful response
error : function(xhr,errmsg,err) {
    console.log(err);
}

In your script

instead of CSRF_TOKEN use '{{ csrf_token }}'

Please use my suggestions and give me feedback and I will update the answer. The two with csfrtoken are probably the problems your having. If you put Django in Debug mode it will be easyer to find out.

My Suggestion

Create a form with what you need to post to gain some features in the validation process.

Leave a comment