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())
Related
I need to update html tag text, based on respond from backend. I am using Django server to run the app. In the backend, I am running a timer, measuring the amount of time, the process had taken. I need to get this amount of time to frontend, and display it.
class Timer():
def __init__(self):
self._start_time = datetime.datetime.now().replace(microsecond=0)
print(self._start_time)
def elapsed_time(self):
return (datetime.datetime.now().replace(microsecond=0) - self._start_time).seconds
urls.py:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^$', views.home, name='home'),
url(r'^$', views.output, name='output')
]
views.py:
def output(request):
time = timer.elapsed_time()
return time
And my html looks this so far:
<td class="value" id="elapsed-time">00:00</td>
<script>
var urlMappings = {
url_elapsed_time : "{% url 'output' %}"
}
$.ajax({
type: "POST",
url: urlMappings.url_elapsed_time
}).done(function(data){
console.log("Done");
}).fail(function(data){
console.log("Fail");
});
</script>
So far, I am only getting 403 error message. Any help?
You can try with this process...
$.ajax('yourRrquestURL',{
method: 'POST',
data: formData,
processData: false,
contentType: false,
success:function () {
console.log("Done");
},
error:function () {
console.log("Fail");
}
);
or
$.ajax('yourRrquestURL',{
method: 'GET',
processData: false,
contentType: false,
success:function () {
console.log("Done");
},
error:function () {
console.log("Fail");
}
);
I need to pass two different datas using ajax.
I've got this:
$('#sendcover').on('click',function(){
$.ajax({
type: "POST",
url: "{{ url('articles_changecover') }}",
data: new FormData($('#test')[0]),
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
});
<form name="test" id="test" method="post" enctype="multipart/form-data">
<input type="text" value="{{article.id}}" name="id" />
<input type="file" name="cover">
<button id="sendcover" type="submit" class="saveData">Save</button>
</form>
I need to pass two var's with data:
id and cover
id - sends {{article.id}}
cover - sends image
(and on the backend side it's uploading img and converting it - but it's already done by someone else)
Could somebody help me how to do it properly? I've never did such thing, and I can't find any working answer. :(
You could send it as an splitted up object like
data: {
myId: id,
myCover: cover
}
but currently you send the whole form that actually should look like
$('form#test').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: "POST",
url: "{{ url('articles_changecover') }}",
data: formData
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
});
And viewing the source looks fine to send...at least for me ^^
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 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.