Im confused why it returns None when I print the value that comes from ajax, I used request.POST.get("ajaxvalue") to get the value from ajax requests but it didn't work, can anyone know what's the problem I encountered? it's very helpful for me.
views.py
#csrf_exempt
def updateStatus(request):
if request.method=="POST":
taskId = request.POST.get('id')
source = request.POST.get("sources")
target = request.POST.get('targets')
print(taskId);
print(source);
print(target);
return JsonResponse({'datas': 'test'})
html ajax
$.ajax({
data: {
id,
'sources':0,
'targets':1
},
url: "{% url 'updateStatus' %}",
type: 'POST',
cache: false,
contentType: false,
processData: false
})
.done(function(data){
console.log("success");
});
urls.py
urlpatterns = [
path('updateStatus/',views.updateStatus, name='updateStatus'),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
I want to send a JsonResponse of a queryset from Django views to JQuery but I am not getting any data from the JQuery side.
This is my views file add_field_views.py :
from django.http import JsonResponse
def drop_down_requests(request):
text = request.POST['text']
print("---->", text)
from captiq.financing_settings.models import ChoiceGroup
response = ChoiceGroup.objects.get(slug="Ja/Nein")
output = JsonResponse(response,safe=False)
print("output -", output)
return output
this is where I declared the URL in urls.py inorder for the Jquery to GET the data from the views :
urlpatterns = [
path('my-ajax-test/', add_field_views.drop_down_requests, name='ajax-test-view'),
]
project urls.py:
frontend_urls = []
for module_name, module_data in FRONTEND_MODULES.items():
frontend_urls.append(re_path(
module_data['url'],
XFrameSameOriginView.as_view(template_name=module_data['view']),
name=module_name))
urlpatterns = i18n_patterns(
path('admin/', admin_site.urls),
path('admin/log_viewer/', include(
('log_viewer.urls', 'log-viewer'), namespace='log-viewer')),
path('admin/docs/', include('docs.urls')),
path('_nested_admin/', include('nested_admin.urls')),
path('accounts/', include(
('accounts.urls', 'accounts'), namespace='accounts')),
path('api-auth/',
include('rest_framework.urls', namespace='rest_framework')),
)
api_v1_patterns = [
path('financing/', include(
('financing.urls', 'financing'), namespace='financing')),
path('financing-settings/', include(
('financing_settings.urls', 'financing_settings'),
namespace='financing_settings')),
path('partners/', include(
('partners.urls', 'partners'), namespace='partners')),
path('accounts/', include(
('accounts.urls', 'accounts'), namespace='accounts')),
path('customers/', include(
('customers.urls', 'customers'), namespace='customers')),
]
urlpatterns += [
path('api/v1/', include((api_v1_patterns, 'api'), namespace='api')),
path('', RedirectView.as_view(url='loan-application/auth')),
path('notifications/', include(
'notifications.urls', namespace='notifications')),
] + frontend_urls
if settings.ENABLE_ROSETTA:
urlpatterns += i18n_patterns(
path('admin/rosetta/', include('rosetta.urls')),
)
if settings.DEBUG:
urlpatterns += static(
settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
then is my JQuery which is waiting for the queryset data or JSON data :
window.addEventListener('load', function () {
(function ($) {
"use strict";
$(document).ready(function () {
$("#id_depending_field").change(function (event) {
console.log("am here man");
const valueSelected = this.value;
$.ajax({
type: "POST",
url: 'my-ajax-test/',
data: {
csrfmiddlewaretoken:
document.getElementsByName('csrfmiddlewaretoken')[0].value,
text: valueSelected
},
success: function callback(response) {
console.log("____________", response)
}
});
})
});
})(django.jQuery);
});
With the code above am not able to get JSON data in JQuery, Instead I get a weird HTML output below :
<link rel="stylesheet" type="text/css" href="/static/css/notifications.css">
.
What am I doing wrong here ?
when you use relative path it is easy to lead your urls to wrong place. at your page your ajax will call for /en/admin/financing_settings/field/add/my-ajax-test/.
you can save exact url on your html page with data-* attribute.
In your example add data-ajax_url attribute to your #id_depending_field (or any other element)
data-ajax_url="{% url "api:financing_settings:ajax-test-view" %}" - url must be like this as i understand your routing
and then in your ajax code instead of url: 'my-ajax-test/', use url: $(#id_depending_field).data('ajax_url')
this will always give you exact url from any page where you load your .js file. And later if you decide to refactor your project and change url path it will keep all changes for you without changing html or js code
Use absolute URL when sending AJAX request:
$.ajax({
type: "POST",
url: '/my-ajax-test/',
data: {
...
})
Apparently, you were sending it to /en/admin/financing_settings/field/add/my-ajax-test/ cause it was relative
I am working in site which display the details of a contact registered in my app, the error I have is when retrieving the data does not show and cannot find the Ajax request, any help would be appreciated
urls.py
from django.urls import path
from app_2 import views as app2
urlpatterns = [
#app_2
path('user', app2.userPanel),
path('get_user_info', app2.getUserInfo, name = 'get_user_info'),
]
Script in user.html
<script type="text/javascript">
$(document).ready(function(){
$("#users").change(function(e){
e.preventDefault();
var username = $(this).val();
var data = {username};
$.ajax({
type : 'GET',
url : "{% url 'get_user_inf' %}",
data : data,
success : function(response){
$("#user_info table tbody").html(`<tr>
<td>${response.user_info.first_name || "-"}</td>
<td>${response.user_info.last_name || "-"}</td>
<td>${response.user_info.email || "-"}</td>
<td>${response.user_info.is_active}</td>
<td>${response.user_info.joined}</td>
</tr>`)
},
error : function(response){
console.log(response)
}
})
})
})
</script>
You should add Ajax in your urlpatterns to specify what are you requesting:
urlpatterns = [
#app_2
path('user', app2.userPanel),
path('Ajax/get_user_info', app2.getUserInfo, name = 'get_user_info'),
]
and also there is an error in your code:
type : 'GET',
url : "{% url 'get_user_info' %}",
data : data,
success : function(response)
i have a problem, i think the ajax doesn't reach the matched view. This is the ajax I'm trying to send
$.ajax(
{
url : 'ajax/create_lobby/',
data: {
'creator' : data.message.creator,
'opponent' : data.message.opponent,
},
headers:{
"X-CSRFToken": csrftoken
},
dataType: 'json',
success: function (data){
alert("Sended ajax request");
}
}
)
where var csrftoken = $("[name=csrfmiddlewaretoken]").val();
The main urls.py contains this:
urlpatterns = [
path('chat/', include('chat.urls')),
path('admin/', admin.site.urls),
#this is what is not working
re_path(r'^ajax/create_lobby/$', quizViews.createLobby, name = "create_lobby"),
path("lobbies/", include('lobbies.urls')),
path("lobby/", include('quiz.urls')),
path('', include('accounts.urls')),
]
So i took care of matching urls more restrictive first.
This is the matched view by the url:
#csrf_exempt
def createLobby(request):
creator = request.GET.get("creator", None)
opponent = request.GET.get("opponent", None)
print(creator)
print(opponent)
data = {
'creator' : creator,
'opponent' : opponent
}
return JsonResponse(data)
This is the info i get in pycharm's console:
HTTP GET /lobbies/ajax/create_lobby/?creator=mihai&opponent=alexandru 200 [0.09, 127.0.0.1:56867]
If i try to send via POST method i get in console the next message but i don't understand why.
Forbidden (CSRF token missing or incorrect.): /lobbies/ajax/create_lobby/
The ajax seems to not be fired and i can't see the problem. Can you help me, i'm new to ajax. Thank you!
I have a camera Speed Dome Intelbras VIP 5220 SD IR that I can move its position (PTZ function) using python code. However, I want to move its position using a button on the Webpage. I create a webpage using Django, so I want to click on the button and I want my camera to move after that, but I do not know how to call my python function using Django. I found some keywords like Django Channels, Ajax and WebSockets, but everything looks very complicated.
To do this I did this so far:
HTML:
<script>
$(document).ready(function(){
$("button").click(function(){
//alert("Botao foi clicado");
$.ajax({
type: "POST",
url: "/ajax_move_camera/",
data:{
"var1":"val1"
},
dataType: 'json',
sucess: function(data){
alert("Sucess");
},
error: function(data){
alert("Error")
}
})
});
});
</script>
VIEWS.py
def ajax_move_camera(request):
x=10
data={}
return JsonResponse(data)
URL.py
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^$', views.ajax_move_camera, name='ajax_move_camera')
]
A rough draft on how you can approach this
your_template.html
<html>
... stuff ...
<button id="camera_move_btn">Move Camera</button>
... stuff ...
<script>
function call_this_function_on_btn_click() {
$.ajax({
type: "POST",
url: "/ajax_move_camera/",
data: {
"var1": "val1"
"csrfmiddlewaretoken", "{{ csrf_token }}"
},
dataType: 'json',
success: function(data) {
... something comes back ...
}
})
}
</script>
views.py
def ajax_move_camera(request):
... do something ...
data = {}
return JsonResponse(data)
you will have to match the ajax url to the view method in your url.py file and remember to include Jquery as I used their ajax method.
If you don't want to add Jquery you can look into XMLHttpRequest which will do the request.
Im trying to post a simple ajax to 'signup' function in django but keep getting 404, I think it has to do with my url dispatcher and I need some help please..
my ajax looks like this:
$('#signupBtn').click(function() {
$.ajax({
type: 'POST',
url : '/signup',
dataType: "json",
data : {
userId : $('#signupEmail').val(),
userPassword : $('#signupPassword').val()
},
beforeSend: function() {
$('#signupBtn').hide();
},
error: function(xhr,errmsg,err) {
$('#signupBtn').show();
$('#signupEmail').val("");
$('#signupPassword').val("");
alert(xhr.status);
},
success : function(json) {
$('#signupBtn').show();
$('#signupEmail').val("");
$('#signupPassword').val("");
alert(json['u']);
}
});
return false;});
my views.py lookes like this:
def signup(request):
userid = request.POST.get('userId')
userpass = request.POST.get('userPassword')
data = { 'u' : userid, 'p' : userpass}
return JsonResponse(data)
and my app urls lookes like this:
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^signup$', views.signup, name='signup'),]
what is my problem? and how do i fix it?
thanks.
Two things could be going wrong.
Missing CSRF token in API call. https://docs.djangoproject.com/en/1.11/ref/csrf/
Not properly serialized data. You need to use data=JSON.stringify({dictionary});
SOLVED!
should have indid put an extra / in the end.