I'm writing Ajax code to hit the database to edit model instances. But the code is not working well. The first alert statement does work, but not the other alert statements. Code in success or error does not respond. Everything seems good. I have no idea how this happened though.
book/detail.html:
<script>
$(document).ready(function () {
$("#add").click(function() {
alert('clicked');
$.ajax({
url: '{% url "cart:add_to_cart" %}',
// handle a successful response
success: function (response) {
alert("Testing.");
("#cartButton").text("Cart" + "(" + response.quantity + ")");
},
error: function (response) {
alert('Got an error');
}
});
});
});
</script>
cart.view.py:
def add_books(request):
c = Cart.objects.get(user=request.user)
q = request.GET.get('quantity')
book_id = request.GET.get('bookID')
<some code here>
response = {
'quantity': BooksInCart.objects.filter(cart=c).aggregate(item_quantity=Sum('quantity'))['item_quantity']
}
return JsonResponse(response)
cart.urls:
app_name = 'cart'
urlpatterns = [
path('add_books/', views.add_books, name='add_to_cart')
]
If you are changing data in the database, you should be using a post-type request. Include method: 'POST' and the csrf token in your ajax call and then check for for a post-type request in your view:
if request.method == 'POST':
To set the csrf token put {% csrf_token %} in your template in order to render the token, and then user JQuery to load the token value into the data portion of the ajax call:
data = {'csrfmiddlewaretoken': $('[name="csrfmiddlewaretoken"]').val()}
Related
Does anyone know why I am getting 500 internal error when I try to call an Ajax function? I tried to send the response from view.py to Ajax function in 2 ways: JsonResponse (see else from view.py) and also with HttpResponse (see if from View.py).
My Hmtl form does have a csrf_token, so I added the header in ajax function, but still got 500 internal erorr. The data is saved into database but the response is not sent to ajax function.
View.py
## Ajax
#login_required
def SubmitModal(request):
if request.method == 'POST':
text = request.POST['Text']
date = request.POST['DatePicker']
time = request.POST['TimePicker']
T = SText()
T.User = request.user
T.Text = text
T.STime = date + ' ' + time
T.save()
return HttpResponse(json.dumps({'success': True}), content_type="application/json")
else:
return JsonResponse({'success': False})
file that contains ajax
$(document).ready(function () {
// Show the modal window when a button is clicked
$('#open-modal').click(function () {
$('#modal').modal('show');
});
// Close the modal window when a button is clicked
$('.close-modal').click(function () {
$('#modal').modal('hide');
});
// Handle the form submission
$('#modal-form').submit(function (event) {
event.preventDefault(); // Prevent the form from being submitted
var formData = $(this).serialize(); // Get the form data
// Submit the form data to the server using an AJAX request
$.ajax({
type: 'POST',
url: '/submit/',
headers: {'X-CSRFToken': '{{ csrf_token }}'},
data: formData,
dataType: "json",
success: function (response) {
if (response.success) {
$('#success-message').show();
} else {
$('#error-message').show();
}
},
error: function (xhr, status, error) {
console.log(error);
}
});
$(".textarea-input")[0].value = '';
$(".date-input")[0].value = '';
$(".time-input")[0].value = '';
});
});
If you're reproducing this in a non-production environment, you can set DEBUG=True in the settings file. Then when you make the call from your browser, the response will include details about what the issue is. You can also set the ADMINS variable to send exception tracebacks to the specified emails when they're encountered. More details here.
You can view the data being sent and received in the developer tools of the browser you are using.
Currently I am using Flask and Jquery and getting a 500 Internal Server Error response in my console. When I post with Ajax to the url on flask, shouldn't it be able to be received? I don't understand why I am getting this error.
Jquery
$('.movie').click(function(){
console.log(this);
$(this).toggleClass('green blue').promise().done(function(){
if ($(this).html() == "Add Movie"){
$(this).html("Added");
}
});
id = $(this).val();
//get information from API
$.ajax({
url: "/profile",
dataType: 'json',
async: true,
data: {id: id},
success: function(data) {
}
});
Python/Flask
#app.route("/profile", methods = ["GET"])
def profile(id):
print("mydata is: ", request.args['id'])
if request.args.get:
print("this API is reached")
id = request.args.get['id']
url_movie = 'https://api.themoviedb.org/3/movie/{}?api_key=78cb6b67a99ce26e6d6619c617d9c907&language=en-US'.format(id)
r = requests.get(url_movie)
code = r.json();
return jsonify(code)
500 is a server error. There is something wrong with the request execution at server side only.
i have problem with ajax when i send a request from my form it doesn't get the value from the form
this is my view code
def create(request):
if request.method == 'POST':
msg_text = request.POST.get('the_massage')
data = {}
form = ChatApp(message=msg_text, user=request.user)
form.save()
data['message']=form.message
data['user']=form.user.username
return JsonResponse(data)
else:
return JsonResponse({'nothing coming thrue'})
it shod get the_massage variable but it give me null value
this is my ajax function :
$(function () {
$('#main-form').on("submit" ,function () {
console.log("create function is here");
var form = $(this);
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: {the_massage:$('#msgbox').val()},
dataType: 'json',
success: function(json) {
console.log(json);
console.log('success');
},
error: function(error){
console.log('we have error');
},
});
});
});
when i console log the value it just come through in the console
please help me
and show me this in the console :
Resource interpreted as Document but transferred with MIME type
application/json: "http://localhost:8000/create/".
Call the function in your event:
$('#main-form').on("submit" ,function (event) {
event.preventDefault();
console.log('submited');
console.log($('#msgbox').val())
created();
});
I see many possibles problems here.
1) just for dev propose, delete #login_required (if you have) from your view and add #csrf_exempt to avoid this problem on dev.
2) Please look inside request.body on your view.
3) if point 1 and 2 doesn't work, please put the server response of this call: POST localhost:8000/create 403 (Forbidden)
this is the write answer : i solve this and its on git hub now https://github.com/mhadiahmed/tinypice
The main reason of django + ajax 403 error is absence of csrf token, but in my case it's present and almost the same ajax function works fine. I'll also attach backend view function handling the response using djangorestframework.
$.ajax({
url: '/authsteptwo/',
type:'POST',
dataType: 'json',
data: { phone_number : phone_number, email : email, csrfmiddlewaretoken: "{{ csrf_token }}" },
success: function () {
// alert('succes');
setTimeout(
function()
{
alert('fine');
}, 0);
},
error : function() {
alert('fck');
}
})
view
#api_view(['POST', ])
def auth_step_two(request):
if request.method == 'POST':
phone_number = request.data['phone_number']
email = request.data['email']
# user = request.user.UserProfile
# user.email = email
# user.phone_number = phone_number
# user.save()
else:
print("WTF")
return Response(request.data)
console:
Failed to load resource: the server responded with a status of 403 (FORBIDDEN)
Are there any other reason which can cause 403 error ?
EDIT: I tried just to call ajax function out of all condition in the beggingign of the page, just after and it worked. But calling the same function onclick(without real data, so it's not related) fails wth 403 or also falls on jQuery click event. Very weird. Any suggestions what could it be?
EDIT: Oh, I figured out that no ajax function in fact working after first ajax auth call executed. I attach the code of first call which works and after that nothing works. Help me understand why?
$.ajax({
url: '/authfb/',
type:'POST',
dataType: 'json',
data: {"fb_first_name": fb_first_name, "fb_last_name": fb_last_name, "fb_username": fb_username, "fb_email":fb_email, "fb_id":fb_id, "fb_link":fb_link, csrfmiddlewaretoken: "{{ csrf_token }}" },
success: function () {
// alert('succes');
setTimeout(
function()
{
$('#hide_group').hide();
$('#show_group').show();
$('.loading_white_wall').fadeOut();
$('.greeting_title_name').html(fb_first_name);
if(fb_email){
$(".email_input").prop("value", fb_email);
}
else{
$(".email_input").prop("placeholder", 'E-mail');
}
}, 1000);
},
error : function(data) {
$('#hide_group').hide();
$('#error_group').show();
$('.loading_white_wall').fadeOut();
}
})
And also the exact code of handler, there is much but possible something somehow related, but most likely no much use of it:
#api_view(['POST', ])
def authfb(request):
require_more_data = True
if request.method == 'POST':
first_name = request.data['fb_first_name']
last_name = request.data['fb_last_name']
fb_username = request.data['fb_username']
fb_id = int(request.data['fb_id'])
fb_link = request.data['fb_link']
username = fb_username.replace(' ', '')
print(fb_link)
print (type(fb_id))
# print(username)
password = '11442358'
user = auth.authenticate(username=username, password=password)
# print(type(username))
# print(type(password))
if user is not None:
auth.login(request, user)
username = auth.get_user(request).username
print ('logged in succesfully')
# user1 = UserProfile.user.objects.get(username=username)
# if (user1.userprofile.phone_number):
# print ("hello")
# email = auth.get_user(request).UserProfile.email
# if phone_number and email:
# require_more_data = False
else:
user = User.objects.create_user(username=username, password=password)
userprofile = UserProfile.objects.create(user=user, first_name=first_name, last_name=last_name)
user = auth.authenticate(username=username, password=password)
auth.login(request, user)
print (userprofile)
else:
print("WTF")
return Response(request.data)
I found a solution in one of my old projects. If someone explains why this works and previous is wrong, I'll mark as correct.
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
var csrftoken = getCookie('csrftoken');
$.ajaxSetup({
headers: { "X-CSRFToken": getCookie("csrftoken") }
});
in ajax call
data: {"fb_first_name": fb_first_name,'csrfmiddlewaretoken': getCookie('csrftoken') },
I am doing the login throgh ajax. jquery function is working fine but its not going to the ajax url. So django view is not getting executed.
Ajax.html
$(function()
{
localStorage['domain'] = "http://122.172.64.142";
var domain = localStorage['domain'];
$('#fac1').on('click', function () {
var username = $("#username").val();
var password = $("#pwd").val();
data = {
name: username,
password: password
};
alert(domain);
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});
return false;
});
});
My django views.py
#csrf_exempt
def login_android(request):
print "i am in view"
if request.method == "POST":
print "you are in method"
username = request.POST['name']
password = request.POST['password']
login_api(request,username,password)
#return HttpResponseRedirect('/home/')
messages.success(request, 'You Loged In Successfully')
response = json.dumps(username)
return HttpResponse(response, mimetype="application/json")
When i click on login button i am getting alert but its not getting entered to view. Url is correct.
I would first recommend using Chrome with the developer tools console open.
You could change you alerts for console.log().
When your trying window.location = 'file:///android_asset/www/posts.html';
You are trying to access a local resource. If I post that in my Chrome developer tools I get back
Not allowed to load local resource: file:///android_asset/www/posts.html
If you would use window.location.replace("a url to your view"); this will work like a HTTP redirect.
for more information redirect page
and you should be able to see your view.
I was made a silly mistake. I provided a wrong domain address on this page. Now it worked.
localStorage['domain'] = "http://122.172.64.142";
This address was wrong. Thats why it was not able to enter in to the view.
You forgot dataType ajax param
$.ajax({
url: domain + "/login/login_android_here/",
type: "POST",
data: data,
dataType : 'json', //dataType param IS MISSING
success: function (response) {
alert("success");
window.location = 'file:///android_asset/www/posts.html';
},
error: function () {
alert('some error in login');
}
});