Sent data through POST method to show in AJAX request - python

Ajax method to post and passing a string to the views.py, the post method in the views.py can receive values from ajax but I cannot get the results value to print back in the ajax success method.
I have tried to return HTTPresponse, redirect, render but nothing seem to work for me.
//Ajax//
$("#viewData").click(function(event){
$.ajax({
type: "POST",
data: {
tempData : "permView",
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success: function(result) {
console.log('{{ result }}')
},
});
event.preventDefault()
});
});
//Python//views.py
class SpreadSheetView(TemplateView):
template_name = 'spreadsheet.html'
def get(self, request, *args, **kwargs):
return render(request, self.template_name, {'type': '86'})
def post(self, request):
if request.POST['tempData'] == 'permView':
return render(request, self.template_name, {'result': "test result"})

You are encountering one of these two problems:
You might be getting an error in your view and cannot notice it since you do not cover error case in your ajax request. Just update your ajax request call like this and see if you are getting an error.
You are not specifying dataType parameterto your request, which causes ajax to incorrectly guess your response type.
To cover these two items, update your request such as:
$.ajax({
type: "GET",
dataType : 'html', # or other types, depending on your needs.
data: {
tempData : "permView",
csrfmiddlewaretoken: '{{ csrf_token }}',
},
success: function(data, status) {
console.log(data)
console.log(status)
},
error: function(xhr, status, error) {
console.log(status);
console.log(error);
}
});

Related

find out when user leaves a page in django

I have an ajax function that sends requests to a Django view every second:
function get_updates() {
$.ajax({
url: full_path,
type: 'GET',
data: {latest_pk: latest_pk},
success: function(json) {
...
},
complete: function(data) {
setTimeout(get_updates, 1000);
}
});
}
get_updates();
get method of the view is like this:
def get(self, request, *args, **kwargs):
if request.GET:
# If there are GET parameters, use them to return updates.
response = self.get_updates(request.GET.get("latest_pk"))
return JsonResponse(response)
else:
# Otherwise if the url is simply requested,
# return the rendered chat page.
return super().get(request, *args, **kwargs)
How can I execute some code in Django, after requests stopped being sent? I need to save the time of the last request.
Try this in javascript there is event called ."beforeunload".
This is just an idea how you can achieve it
<script>
window.addEventListener("beforeunload",function(){
$.ajax({
url: full_path,
type: 'GET',
data: {latest_pk: latest_pk},
success: function(json) {
// add your other logic here
}
});
});
</script>

Django view not getting ajax request

I have a script in my template that tries to send data to a django view during onbuttonclick event. My problem is that the request doesn't seem to make it to the view. The browser console sees the request properly and all, but the django view does't even return true when i call request.is_ajax().
request.method returns GET instead of POST, and the data is empty. This behavior is persistent regardless of the request type.
html
<a onclick="setGetParameter(this)" pid="some_id">Some Text</a>
.js
<script>
var csrftoken = Cookies.get('csrftoken');
function setGetParameter(el){
var stuff = $(el).attr('pid');
$.ajax({
type: 'POST',
headers: { "X-CSRFToken": csrftoken },
url: '/view_url/',
data: {'datatopass': stuff},
success: function(response){
alert(response);
}
});
}
</script>
urls.py
path('view_url/', views.test),
path('', views.home),
views.py
def test(request):
output = request.is_ajax()
return HttpResponse(output)
In Django 3.1 is_ajax() method is deprecated. See Miscellaneous Django 3.1
So for Django >= 3.1 you can do it like that:
if request.headers.get('x-requested-with') == 'XMLHttpRequest':
is_ajax = True
else:
is_ajax = False
And make sure that the following line added in AJAX request headers:
"X-Requested-With": "XMLHttpRequest"
I would be use jQuery click method:
<a pid="some_id">Some Text</a>
<script>
var csrftoken = Cookies.get('csrftoken');
function setGetParameter(el){
var stuff = $(el).attr('pid');
$.ajax({
type: 'POST',
headers: { "X-CSRFToken": csrftoken },
url: '/view_url/',
data: {'datatopass': stuff},
success: function(response){
alert(response);
}
});
}
$(document).ready(function(){
$('a[pid]').click(function(){
setGetParameter(this);
});
});
</script>
Also I would be use JsonResponse objects:
from django.http import JsonResponse
def test(request):
output = request.is_ajax()
return JsonResponse({'is_ajax': output})
In order to serialize objects other than dict you must set the safe parameter to False:
response = JsonResponse([1, 2, 3], safe=False)
After days of beating my head against a wall, I chose to go with a different implementation. It appears I can only render the data on the page that initially sent the request.

Failed to load resource: the server responded with a status of 403 (Forbidden)?

i am posting javascript localstorage object to backend(django). I am passing it through ajax.
this is the code in frontend.
function checkout_(){
console.log("checkout");
for(v in list1){
object=Object.values(localStorage)[v];
object = JSON.parse(object)
}
//ajax here
console.log(object.length);
$.ajax({
url: '{% url "chout" %}',
data: {
'object': object
},
method: "POST",
dataType: 'json',
success: function (data) {
alert("success");
}
});
i have given this function to a button via onclick.
<button class="bg-danger text-white " onclick="checkout_()">Go To Checkout Counter</button>
when i click on this button this error "Failed to load resource: the server responded with a status of 403 (Forbidden)" happens.
in the views.py this is the code.
views.py
def checkoutnow(request):
return render(request, "mart/checkout.html")
I hope this detail is enough to explain the problem..Thankyou
You have to pass csrfmiddlewaretoken also in the post call because of csrf middleware set in the settings
const csrf = "{{ csrf_token }}";
and add this key, value pair to your data:
data: {'csrfmiddlewaretoken':csrf, 'object': object },
You can skip this and just use GET instead of POST if feasible.

Ajax call is not going to view function django

Hi I am sending request to a django view but its not accessing view function . Both are in same app . And I am using debugging tool so I tried to debug but on my view no call is received and
My ajax call code is like this
$.ajax({
url: '/edit_profile/',
type: 'get', // This is the default though, you don't actually need to always mention it
success: function(data) {
alert(data);
},
failure: function(data) {
alert('Got an error dude');
}
});
url.py
path('edit_profile/', views.edit_profile , name="edit_profile"),
view.py
def edit_profile(request):
print(request)
print(request)
if request.method == 'POST':
return render(request, 'authenticate/edit_profile.html', context)
I am debugging but call is not received in this view function .
You can see live demo here REPL
First do this if you don't want that your view check the csrf token. This can be done by using decorator #csrf_exempt.
view.py
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def edit_profile(request):
print(request)
if request.method == 'GET':
return render(request, 'authenticate/edit_profile.html')
url.py
path('edit_profile/', views.edit_profile , name="edit_profile"),
ajax request
$.ajax({
url: '/edit_profile/',
type: 'GET',// This is the default though, you don't actually need to always mention it
data:{},
success: function(data) {
alert(data);
},
failure: function(data) {
alert('Got an error dude');
}
});

Can't get AJAX POST working in Django

I can't do a POST ajax request in Django. If I do a GET request, it works fine. I think it may be a csrf token problem, but I can get it to work
My view:
#login_required
def add_share_points(request):
user = request.user
profile = request.user.profile
if request.method == 'POST':
value = 5.0
# Premia o usuário ao compartilhar conteúdo
VirtualCurrencyTransaction.objects.create(
user=request.user,
reason=2,
description='Você completou seu perfil',
value=value
)
return "ok"
My AJAX request:
$('.my-button').on('click', function(e) {
e.preventDefault();
var pointsCount = $(this).hasClass('homepage-facebook-share') ? 3 : 2;
$.ajax({
type:"POST",
url: "/add_share_points",
data: {
points: pointsCount,
}
}).done(function() {
alert('Posting completed.');
}).fail(function(){
alert('Error while posting.');
});
});
In my script, I also have this setting:
function csrfSafeMethod(method) {
return (/^(GET|HEAD|OPTIONS|TRACE)$/).test(method);
}
$.ajaxSetup({
crossDomain: false,
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader('X-CSRFToken', CSRF_TOKEN);
}
}
});
What is wrong with my code? It gave my a 500 error code, but no further explanation in the logs.
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.

Categories