Reputation: 65
I'm trying to access some string from django models using ajax. I'm new to ajax and i don't know where I'm going wrong.
Here is Jquery code :-
$(document).ready(function () {
$("input.ssd").click(function () {
var lsid = $(this).attr("id");
lsid = Number(lsid);
$.ajax({
type: "POST",
url: "/a_solution/",
data: {
l_sid: lsid,
},
success: console.log("success")
datatype: 'html',
error : console.log("oops! something went wrong"),
});
});
});
Here is url mapping in urls.py
:
url(r'^a_solution/$', views.a_detail, name = 'a_detail'),
PS :- jquery.min.js:2 POST http://127.0.0.1:8000/a_solution/ 403 (Forbidden) jquery.min.js:2 XHR failed loading: POST "http://127.0.0.1:8000/a_solution/"
.
Upvotes: 0
Views: 1089
Reputation: 3610
By default all POST requests are protected against CSRF (cross-site request forgery). So you must send the csrfmiddlewaretoken
along with your Ajax request data.
Usually what I do is render the csrf token somewhere in the template (if you have a form put it inside a form, but since it's an Ajax request, the place doesn't really matter).
{% csrf_token %}
Then in your jQuery code you can access it. Also, in the Ajax call, success
and error
expects a function (using the console.log()
call may cause an error, not sure):
$(document).ready(function () {
$("input.ssd").click(function () {
var lsid = $(this).attr("id");
lsid = Number(lsid);
var csrf = $("[name='csrfmiddlewaretoken']").val();
$.ajax({
type: "POST",
url: "/a_solution/",
data: {
'l_sid': lsid,
'csrfmiddlewaretoken': csrf
},
success: function (data) {
console.log("success");
console.log(data);
},
datatype: 'html',
error: function () {
console.log("oops! something went wrong");
}
});
});
});
Upvotes: 3