Ajax post giving error in Django view - ajax

I am using the following view for my Ajax post function and the call is repeatedly failing. I can seem to get what is wrong here. Can anybody point it out
def interview(request):
if request.is_ajax():
if request.method == 'POST':
name = request.POST.get('name', False)
email = request.POST.get('email', False)
skype_id = request.POST.get('skype_id', False)
phone = request.POST.get('phone', False)
time_slot_1 = request.POST.get('time_slot_1', False)
time_slot_2 = request.POST.get('time_slot_2', False)
time_slot_3 = request.POST.get('time_slot_3', False)
recipients = ['abc#gamil.com']
subject = 'Interview Appointment'
message = "The following person has registered for interview \n Name: %s \n Email: %s \n Skype Id: %s \n Phone: %s \n Slot-1: %s \n Slot-2: %s \n Slot-3: %s" % ( name, email, skype_id, phone, time_slot_1, time_slot_2, time_slot_3)
from django.core.mail import send_mail
send_mail(subject, message, sender, recipients)
return_message = "Sent mail"
return HttpResponse(return_message,mimetype='application/javascript')
My javascript is also pretty straightforward, but I don't know why am I getting error message
var email_val = $("#emailp").val();
var skype = $("#skypeId").val();
var phone = $("#phone_no1").val();
var t1 = $("#time_slot1").val();
var t2 = $("#time_slot2").val();
var t3 = $("#time_slot3").val();
$.ajax({
type: "POST",
url: "/interviews/interview_form/",
data: {
'name': name_val,
'email': email_val,
'skype_id': skype,
'phone': phone,
'time_slot_1': t1,
'time_slot_2': t2,
'time_slot_3': t3,
},
success: function(){
alert("call successful");
$('#complete').html("Form has been Submitted");
},
error: function(){
alert("call failed");
$('#error').html("Form could not be Submitted! Please try again");
},
});
Any insights are welcome.

You need to submit the CSRF token as well, to prevent XSS attacks. The most straightforward way in your code would be to add csrfmiddlewaretoken: '{{ csrf_token }}' to your data dictionary. Also, make sure your view is returning a context_instance so that the CSRF token is available.

Related

POST request not behaving as intended

I've been trying to get my button to send a POST request to the submitted URL, which does a write back to the database. The application looks like the POST request gets sent, but after hitting the button my URL never changes and the print at the submitted URL appears to be an empty set.
This is my jquery/ajax call for the button:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<button class="btn btn-primary my_select" type="submit">Request Access</button>
<script>
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var phi = $('#phi').val();
var accesslevelid = $('#accesslevelid').val();
$.ajax({
url: "{% url 'submitted' %}",
headers: { 'X-CSRFToken': '{{ csrf_token }}' },
data: {
phi: phi,
accesslevelid: accesslevelid,
},
type: 'POST',
success: function (result) {
// do something with result
},
});
});
});
</script>
I'm expecting my POST of the Application List, PHI flag, and Access Level gets sent as a POST to my submitted URL. My view for submitted is the following:
def submitted(request):
owner = User.objects.get (formattedusername=request.user.formattedusername)
checkedlist = request.POST.getlist('report_id')
coid = User.objects.filter(coid = request.user.coid).filter(formattedusername=request.user.formattedusername)
facilitycfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 1).values_list('cfo_ntname', flat = True)
divisioncfo = QvDatareducecfo.objects.filter(dr_code__exact = coid, active = 1, cfo_type = 2).values_list('cfo_ntname', flat = True)
print (f"checkedlist prior to post:{checkedlist}")
selectedaccesslevel = request.POST.get('accesslevelid')
selectedphi = request.POST.get('phi')
if request.method == 'POST':
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00')
requestsave.save()
print (f"postlist:{checkedlist}")
print (f"accesslevel:{selectedaccesslevel}")
print (f"phi:{selectedphi}")
return JsonResponse({'is_success':True})
My post looks like it occurs when I press my button:
[]
[12/Dec/2017 08:54:45] "POST /account/submitted/ HTTP/1.1" 200 1149
However, the URL doesn't switch to submitted. My list for checkedlist appears to be an empty set. When visiting submitted and having my print statements occur, i get nothing like the POST never occurred.
My form action is the following:
<form action = "{% url 'submitted' %}" form method = "POST">
{% csrf_token %}
{{ form.as_p}}
ajax is build to do background client server operation or load part of the page dynamic to avaid heavy requests
Example
most of social medias feeds use ajax. when you scroll the view a ajax request is send to server to retrieve the next feed .
in your case the data is posted to server successfully. but change the URL is not available by server at this point but you can do this with a trick ...
in your view.py file
from django.http import JsonResponse
if request.method == 'POST':
for i in checkedlist:
requestsave = QVFormAccessRequest(ntname = owner.formattedusername, first_name = owner.first_name, last_name = owner.last_name, coid = owner.coid, facility = owner.facility, title = owner.title
,report_id = i, accesslevel_id = selectedaccesslevel, phi = selectedphi , access_beg_date = '2017-01-01 00:00:00', access_end_date = '2017-01-31 00:00:00')
requestsave.save()
print (checkedlist)
print(selectedaccesslevel)
print(selectedphi)
return JsonResponse({'is_sucess':True})
this JsonResponse object will send back the data ajax.
success: function (result) {
if(result.is_sucess){
document.location = 'you url to direct page at' //
}
},
this job can be done using direct post to url and then redirecting to other url i. will leave this for now

Multiple ajax requests kill django server

I have a single view which scrolls through user data. There are next and previous buttons to scroll. When user presses next, ajax sends the user id to the django view and displays the data.
If user clicks the next button two or three times consecutively (which they usually do), the calls get aborted and server is killed.
$("#new").click(function() {
$.ajax({
type:'POST',
url:'/new/',
data:{
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val()
},
success:searchSuccess,
dataType: 'html'
});
});
function searchSuccess(data, textStatus, jqXHR)
{
$('#myForm').html(data);
}
This is the view.
def master_detail_next(request):
def decrement_voucher_id(form_id):
voucher_id = str(int(form_id) - 1).zfill(4)
return voucher_id
if request.method == 'POST':
form_id = request.POST['voucher_id']
voucher_id = decrement_voucher_id(form_id)
voucher_id = get_decremented_voucher_id(voucher_id)
else:
voucher_id = ''
# Inline forms
author = TmpPlInvoice.objects.get(voucher_id=voucher_id)
author_form = TmpForm(instance=author)
BookFormSet = inlineformset_factory(TmpPlInvoice, TmpPlInvoicedet,
exclude=('emp_id', 'voucher', 'lineitem', 'id',),
form=TmpFormDetForm, )
formset = BookFormSet(instance=author)
totalform = TmpFormTotal(instance=author)
postform = CheckPostedForm(instance=author, posted=author.posted)
return render(request, 'form.html', {'form': author_form, 'formset': formset, 'formtotal': totalform, 'postform': postform})
How can i avoid that? What is that i am doing wrong?

Django Ajax Form Works but Throws 500 (Internal Server Error)

I've researched this to death, but have not found exactly what I need to get the last part of my form completed.
I have a simple 2-field form in my footer for newsletter signup. I am utilizing an inclusion_tag since I need to include the form on every page.
The form works; with a couple of hitches, for arguments sake, it works, I hit submit and the email is sent to me. The problem is that I am getting a 500(internal server error) in console on the ajax url. I am assuming that its not really supposed to redirect to the url, but rather just process the form. Below is my code; I hope someone can easily point out my issues. Thanks.
Inclusion Tag
#register.inclusion_tag('includes/cta_form.html', takes_context=True)
def footer_newsletter_signup(context):
title = 'Newsletter Signup'
form = CTASignupForm()
context = {
'form': form,
'title': title,
}
return context
Ajax
$('#sendSignupForm').click(function (e) {
e.preventDefault();
var mForm = $('#signupForm').serialize();
console.log(mForm);
$.ajax({
type: 'POST',
url: '{% url 'pages:cta_signup' %}',
data: mForm,
success: function (data) {
$("input").val('')
},
error: function (data) {
$("input").addClass('error')
}
})
})
cta_form.html
<form action="{% url 'pages:cta_signup' %}" method="POST" id="signupForm">
{% csrf_token %}
{{ form.name }}
{{ form.email }}
<button class="btn btn-black no-margin-bottom btn-small" type="submit" id="sendSignupForm">Submit</button>
</form>
View
def cta_signup(request):
if request.method == "POST":
form = CTASignupForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
subject = 'This is a response from Soledad Footer Signup Form'
from_email = settings.DEFAULT_FROM_EMAIL
recipient_list = [from_email, 'charles#netfinity.net']
ctx = {
'subject': subject,
'name': name,
'email': email
}
message = get_template('email_forms/cta_signup_email.html').render(Context(ctx))
msg = EmailMessage(subject, message, from_email=from_email, to=recipient_list)
msg.content_subtype = 'html'
msg.send()
messages.success(request, "Thank you, we received your message")
if form.errors:
json_data = json.dumps(form.errors)
return HttpResponseBadRequest(json_data, content_type='application/json')
else:
raise Http404
Screenshot of Console Error
A view must always return a response. You don't, if the form is valid; that's a server error.
Return HttpResponse() at the end of the is_valid block.

not getting response from ajax call in codeigniter

I am trying to check if the user name is available for use using ajax and codeigniter. I have problem to get the response from the codeingniter controller in my js. file but without success.
Here is the controller function, relevant to the question:
if ($username == 0) {
$this->output->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}
Rest assured that I do get 1 if username already exists in thedatabase and 0 if it does not exist.
I have the following js.file
// list all variables used here...
var
regform = $('#reg-form'),
memberusername = $('#memberusername'),
memberpassword = $('#memberpassword'),
memberemail = $('#memberemail'),
memberconfirmpassword = $('#memberconfirmpassword');
regform.submit(function(e) {
e.preventDefault();
console.log("I am on the beggining here"); // this is displayed in console
var memberusername = $(this).find("#memberusername").val();
var memberemail = $(this).find("#memberemail").val();
var memberpassword = $(this).find("#memberpassword").val();
var url = $(this).attr("action");
$.ajax({
type: "POST",
url: $(this).attr("action"),
dataType: "json",
data: {memberusername: memberusername, memberemail: memberemail, memberpassword: memberpassword},
cache: false,
success: function(output) {
console.log('I am inside...'); // this is never displayed in console...
console.log(r); // is never shonw in console
console.log(output); is also never displayed in console
$.each(output, function(index, value) {
//process your data by index, in example
});
}
});
return false;
})
Can anyone help me to get the username value of r in the ajax, so I can take appropriate action?
Cheers
Basically, you're saying that the success handler is never called - meaning that the request had an error in some way. You should add an error handler and maybe even a complete handler. This will at least show you what's going on with the request. (someone else mentioned about using Chrome Dev Tools -- YES, do that!)
As far as the parse error. Your request is expecting json data, but your data must not be returned as json (it's formatted as json, but without a content type header, the browser just treats it as text). Try changing your php code to this:
if ($username == 0) {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => true)));
} else {
$this->output->set_content_type('application/json')->set_output(json_encode(array("r" => false, "error" => "Username already exits")));
}

Ajax and Django render_to_response (How to render to response inside success function)

Currently I am trying to implement a login validation system. I am using ajax so that users can get a response without being redirected to another page. My ajax function sends email and password that user has inputted, and get message in callback function, which can be in three types: email, password, or the actual HttpResponse object. But I have no idea how to render the given http response object using ajax and jquery. Is location.href an option? I am pasting the code below.
In javascript:
function loginSubmit(email, password) {
var d= "email=" + email + "&password=" + password;
$.ajax({
url: "/login",
type: "POST",
dataType: "text",
data: d,
success: function(m) {
if (m == "email") {
$("#emailMessage").html("There is no account associated with this email address.");
$("#emailError").show();
$("#emailError").fadeOut(5000, function() {});
} else if (m == "password") {
$("#emailMessage").html("There is no account associated with this email address.");
$("#emailError").show();
$("#emailError").fadeOut(5000, function() {});
} else {
}
}
});
}
in view function:
def login(request):
json = request.POST
e = json['email']
p = json['password']
u = User.objects.filter(email=e)
if (len(u)):
up = User.objects.filter(email=e, password=p)
if (len(up)):
return render_to_response('profile.html', context_instance=RequestContext(request))
else:
data = "password"
c = RequestContext(request, {'result':data})
t = Template("{{result}}")
datatype=u"application/javascript"
return HttpResponse(t.render(c), datatype)
else:
data = "email"
c = RequestContext(request, {'result':data})
t = Template("{{result}}")
datatype=u"application/javascript"
return HttpResponse(t.render(c), datatype)
p.s. Currently I am using a dummy template and HttpResponse to send data to the ajax success callback function. Is there a more efficient way to accomplish this (send back json data)? I will wait for your replies guys!
from django.contrib.auth import authenticate, login as auth_login
def login(request):
# Use authentication framework to check user's credentials
# http://djangosnippets.org/snippets/1001/ for auth backend
user = authenticate(
email = request.POST['email'],
password = request.POST['password'], )
if user is not None:
# Use Auth framework to login user
auth_login(request, user)
return render_to_response('profile.html',
context_instance=RequestContext(request))
else:
# Return Access Denied
# Never return bad email/bad password. This is information leakage
# and helps hackers determine who uses your platform and their emails.
return HttpResponse("Failed: Bad username or password", status=403)
function loginSubmit(email, password) {
$.ajax({
url: "/login",
type: "POST",
data: {email:email, password:password},
success: function(data) {
var returned_html = $(data);
$("#target_profile_area").clear().append(returned_html);
},
error: function(jqXHR) {
if (jqXHR.statusCode == 403) {
$("#loginMessage").text("Your login details are incorrect");
} else {
$("#loginMessage").text("Error Contacting Server");
}
$("#loginError").show();
$("#loginError").fadeOut(5000, function() {});
}
});
}

Resources