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.
Related
im on my 2nd week trying to learn Python+Django and wanted to make a litte project. But im getting stuck on some JS-bs. I don't know JS well at all and would need some help.
I want to pass the ID ("Value" in the button) of the selected button as data in the Ajax function, but can't really get this to work.
How do i pass the value to the Ajax function? I want to use the value in the "id" variable in views.
Thank you!
HTML - I want to pass an ID of selected pressed button.
{% for product in products %}
<button type="button" id="submit" class="btn" value="{{product}}">{{product}}</button>
{% endfor %}
Javascript To the Ajax POST function here.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var data = new FormData();
$(document).on('click', '#submit', function(e) {
data.append('action', 'toggle_button')
data.append('csrfmiddlewaretoken', '{{ csrf_token }}')
$.ajax({
type: 'POST',
url: '{% url "toggle_button" %}',
data: data,
cache: false,
processData: false,
contentType: false,
enctype: 'multipart/form-data',
})
})
</script>
Django view file
from django.http import HttpResponse, request
from django.shortcuts import render
from django.http import JsonResponse
def home_view(request):
context = {
"products": ["Button1", "Button2", "Button3", "Button4"],
}
return render(request, "home.html", context)
def toggle_button_view(request):
if request.POST.get('action') == 'toggle_button':
token = request.POST.get('csrfmiddlewaretoken')
id = request.POST.get("id")
#print (token)
print (id)
return render(request, "home.html")
It is because you are not passing the ID to the view.
I modified your JS event to handle the $(this) variable that contains the object that called the event:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var data = new FormData();
$(document).on('click', '#submit', function(e) {
data.append('action', 'toggle_button')
data.append('csrfmiddlewaretoken', '{{ csrf_token }}')
data.append('id', $(this).val())
$.ajax({
type: 'POST',
url: '{% url "toggle_button" %}',
data: data,
cache: false,
processData: false,
contentType: false,
enctype: 'multipart/form-data',
})
})
</script>
Notice how I added data.append('id', $(this).val())
I am trying to post a JSON object from my client side Javascript to my Django View.
I receive a "500 (Internal Server Error)" When attempting to Post. Does this have to do with the CSRF token? And how can I get around this?
My AJAX
$.ajax({
type: 'POST',
dataType: 'json',
url: '/demo/saved/',
data: {'data': JSON.stringify(finalSelection)},
success: function() {
console.log("Success")
}
});
views.py
def show(request):
data = json.loads(request.POST.get('data', ''))
context = {
'data': data
}
return render(request, 'bill/saved.html', context )
urls.py
urlpatterns = [
path('bill/', views.bill_view, name = 'bill-view'),
path('saved/', views.show, name = 'selected-view'),
]
Appreciate any help!
Assuming its really the CSRF problem you mentioned, since you didn't post the 500 error output, you can simply add the csrf token to your data that is sent in POST request:
$.ajax({
...
data: {
'data': JSON.stringify(finalSelection),
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
...
});
I am trying to post data to Laravel backend with ajax, however I am getting 'CSRF token mismatch' error.
First, I've placed token in html (in body but outside its form because it's not the whole form, its only 2 elements to be posted):
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
Then in 'document ready', I try to post the data with ajax.
data["_token"] = jQuery('#token').val();
// Also tried this:
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': jQuery('#token').val()
}
})
console.log(data) // returns the array with _token: "esOKmY8Tpr4UvhTYMhWcWui0rpvYEjJ3es7ggics"
jQuery.ajax({
type: "POST",
url: '/my-route',
data: data,
success: function() {
console.log("A");
}
});
The data which I want to post are little chunk of a bigger form, and with using this approach, I can autocomplete form. The little chunk of html inputs are not inside any other sub-form. Maybe this can be the case?
- Form:
- A: bla // to be posted
- B: hello // to be posted
- C: smt else // no post
but getting the values are working okay
Route:
Route::post('/my-route', 'AdminController#theFunction')->middleware('admin');
Edit: I changed <input> to <meta> tag
I had the same problem
try to put include CSRF tag in your meta like so
<meta name="csrf-token" content="{{ csrf_token() }}" />
and read it in your ajax code like so :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
Last Update
Please modify your url variable like so :
jQuery.ajax({
type: "POST",
url: '/my-route'+'?_token=' + '{{ csrf_token() }}',
data: data,
success: function() {
console.log("A");
}
});
Try This
var formData = new FormData();
formData.append("_token", "{{ csrf_token() }}");
$.ajax({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
url: 'save_search',
data: formData,
processData: false,
type: 'POST',
success: function ( data ) {
alert( data );
}
});
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.
I have a web application from which I want to pass a text box value into a flask application.But, when I print out the request object in flask I do not get the data.Can you kindly help me out.Here are the codes:
Flask Server:
#app.route('/send_data', methods=['GET', 'POST'])
def send_data():
print request
if request.method == "POST":
#Operations with the data received
else:
return jsonify(txt="Nothing received");
HTML CODE:
<div id="div_submit">
<form name="form_submit">
<textarea cols="100" rows="1" id="txt_query">
</textarea>
<br>
<br/>
<input type="submit" value="Submit" onclick="send_query()">
</form>
</div>
Javascript:
function send_query()
{
var qry=document.getElementById("txt_query").value;
//alert(qry);
var contentType = "application/x-www-form-urlencoded";
var ajax=$.ajax({
type: "POST",
url: "http://0.0.0.0:8080/send_data",
data: JSON.stringify(qry),
dataType: "json"
}).done(function(data){
alert("success");
});
ajax.fail(function(data){
alert("fail");
});
}
You are posting JSON data; set the content type to application/json and use the request.get_json() method to load the data:
var ajax=$.ajax({
type: "POST",
url: "http://127.0.0.1:8080/send_data",
data: JSON.stringify({query: qry}),
dataType: "json",
contentType: "application/json; charset=UTF-8"
})
where the URL has to be meaningful; 0.0.0.0 is okay for servers (it means 'bind to all interfaces') but you are probably running this on localhost, so use that to begin with.
In your view use:
data = request.get_json()
query = data['query']
You need to use a request in your flask app to receive the data:
http://flask.pocoo.org/docs/quickstart/#the-request-object