I met some problems when I try to send the POST request using ajax in Django. I already research some topics here, but still can't find the way to solved them.
Here is my javascript code that follow this solution:
$.ajax({
url: '{% url home %}',
data: {selected_folders: formData,
csrfmiddlewaretoken: '{{ csrf_token }}'},
dataType: "json",
type: "POST",
});
I also try the solution from Django
$("form").submit(function() {
var csrftoken = $.cookie('csrftoken');
$.ajax({
url: '{% url home %}',
data: {selected_folders: formData,
csrfmiddlewaretoken: csrftoken},
dataType: "json",
type: "POST",
});
});
Here is my view.py
def home(request):
if request.method == 'POST':
Call_Other_Class()
return render_to_response('home.html')
My goal is to send the POST request from home.html to itself, and when home.html get the POST request, it will call other classes to do something else. I am not sure where to put the CSRF token in the template and if my code in view.py is correct or not.
Thanks for your reading and solve my problems.
Edit:
I edited my javascript code to:
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
var csrftoken = Cookies.get('csrftoken');
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajax({
url: '{% url home %}',
data: {selected_folders: formData},
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
},
dataType: "json",
type: "POST",
});
});
</script>
HTML:
<form>
<ul>
<li id='key1'></li>
<li id='key2'></li>
</ul>
</form>
still doesn't work.
For Js:
$("form").submit(function() {
$.ajax({
url: '{% url home %}',
data: {selected_folders: formData,
csrfmiddlewaretoken: $("[name = csrfmiddlewaretoken]"),
dataType: "json",
type: "POST",
});
});
For view.py:
def home(request):
if request.method == 'POST' and request.is_ajax():
Call_Other_Class()
return render_to_response('home.html')
The best solution is using the online documentation.
From what I recall:
first call a GET in Ajax and in the answer, force ensure_csrf_cookie decorator
then keep the CSRF cookie, you have all the detail explanation here.
Related
i have issue to send data in flask from js. I try use ajax.
AJAX code
$.ajax({
type: "GET",
contentType: "application/json;charset=utf-8",
url: "/getmethod/data",
traditional: "true",
data: JSON.stringify({data}),
dataType: "json"
});
Python code
def get_javascript_data(data):
content = request.get_data('data')
jsonify(content)
If u got some tips or tricks please tell me.
new_item = $('#input').val() //value I want to send
$.ajax({
url: '/set_value',
type: 'POST',
data: new_item,
success: function(response){
$('#main').text(response)
}
})
in flask:
new_item = request.get_data()
I am trying to update data asynchronously. Currently, if I refresh the page, only then I see new data in the console log.
My ajax script:
$.ajax({
url: '{% url 'messages' %}',
datatype: 'json',
type: 'GET',
success: function(body) {
console.log(body)
}
});
My view:
inbox = Messages.objects.filter(receiver=user).order_by('-timestamp')
serialized_inbox = serializers.serialize('json', inbox)
return HttpResponse(serialized_inbox, content_type='application/json')
I receive template error "Could not parse the remainder: '{{movie_id}}' from '{{movie_id}}'" when passing the varriable to ajax. This variable works in template, but ajax cannot get it thru. Variable contains id which is required to pass to my views function.
ajax call:
$.ajax({
url: "{% url 'make-order' {{movie_id}} %}",
type: 'POST',
data: new_array,
processData: false,
contentType: "application/json",
dataType: "json",
headers: {"X-CSRFToken":'{{ csrf_token }}'},
success: function (result) {
console.log(result.d)
window.location.href = "{% url 'confirmation' %}"
},
error: function (result) {
console.log(result);
}
});
urls:
path("make-order/<int:pk>", views.make_order, name="make-order"),
views:
def make_order(request, movie_id):
if request.method == "POST" and request.is_ajax():
data = json.loads(request.body)
print(movie_id)
return HttpResponse(200)
else:
return redirect(request, 'home')
Why cant I save this, I get 400 (Bad Request),
and on headers response i get The CSRF token could not be verified.
$(document).ready(function() {
$("a#copylink").click(function (e) {
e.preventDefault();
var data = $('#campaign-form').serialize();
$.ajax(
{
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
data: data,
success: function(data){
alert(data);
}
}
)
});
});
on backend:
public function actionCampaignSave()
{
var_dump($_POST);
}
You can pass the [headers] parameter in your ajax call like this.
$.ajax({
url : 'campaignsave',
method : 'POST',,
headers : {
'X-CSRF-TOKEN' : $('input[name="token"]').val()
}
dataType : 'json',
data : data,
success : function(response) {
console.log(response);
}
});
Just make sure you've place {!! csrf_field() !!} on your [view] blade template to append the $(input[name="token"); html tag to get the token value to get the CSRF token as well. Hope this helps
Pass csrf token using headers property on ajax
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
headers: { 'X-CSRF-TOKEN': 'token' }
data: data,
success: function(data){
alert(data);
}
});
Try this it may help you
$.ajax({
type: "POST",
url: 'campaignsave',
data: {test : data},
success: function(data) {
alert(data);
}
});
I have a simple input box in a form the value of which I'm trying to send to django via Ajax post, but I'm getting a 500 error ValueError at /rest/
Cannot use None as a query value
<form onsubmit="return false;">
{% csrf_token %}
Search:<input type="text" name="artist" id="artist" />
<button class="updateButton" onclick="createlist()">submit</button>
</form>
<script>
function createlist(){
$.ajax({
type: "POST",
url: "/rest/",
dataType: "json",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
artist: $('#artist').val()
},
success: function(data){
$('body').append(data.results);
}
});
}
</script>
View:
def rest(request):
artistname = request.POST.get("artist") # <- problem here?
response_data = {}
query_results = Art.objects.filter(artist__contains=artistname)
response_data['results'] = query_results
return HttpResponse(json.dumps(response_data), content_type="application/json")
When I check the headers under Form Data it shows artist: da vinci which is what I typed in. Where is the train getting derailed?
copy, pasted your code and worked for me.
You can try and changing the way you send the POST request.
$.ajax({
type: "POST",
url: "/rest/",
dataType: "json",
data: {artist: $('#artist').val() },
headers: {
'X-CSRFTOKEN': "{{ csrf_token }}",
},
success: function(data){
$('body').append(data.results);
}
});
I figured out the problem. My app/urls.py file was sending the url to the wrong function. I thought the /rest/ url was going to the views.rest function, but for some reason /rest/ was being sent to views.get_search_entry which does something completely different with post requests.
from django.conf.urls import patterns, url
from myapp import views
urlpatterns = patterns('',
url(r'^$', views.get_search_entry, name='get_search_entry'),
url(r'^results/', views.get_search_entry, name='result'),
url(r'^rest/', views.rest, name='rest'),
)
Then I had to serialize the queryset before dumping to json to send over the wire.