html form in Django returns none - javascript

I am trying to save this HTML form in my table in the database, but I am getting "None" error. I have been on this for some hour. Please any help will be appreciated
Please, how do i fix this
The is the HTML order.html i created
<form action="" method="post" id="payment-form">
<input type="text" class="form-control" id="first_name"
name="first_name"
value="{{request.user.first_name}}">
<textarea type="text" class="form-control" id="address" name="address"
placeholder="1234 Main St" required></textarea>
<button id="submit" class="btn btn-success lg w-100 fw-bold" >
Proceed to Payment
</button>
</form>
Here is my views.py
def add(request):
basket = Basket(request)
if request.POST.get("action") == "post":
order_key = request.POST.get("order_key")
user_id = request.user.id
baskettotal = basket.get_total_price()
first_name = request.POST.get("first_name")
last_name = request.POST.get("last_name")
address = request.POST.get("address")
print(first_name, last_name, address)
order = Order.objects.create(
first_name = first_name,
address=address,
total_paid=baskettotal,
)
order_id = order.pk
response = JsonResponse({"success": "Order created"})
return response
The js file
<script type="text/javascript">
function makePayment(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "order:add" %}',
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
action: "post",
},
success: function (json) {
console.log(json.success)
},
error: function (xhr, errmsg, err) {},
});
}
</script>

First of all you don't have to post extra value action to determine post request you just have to use request.method it will return you all available method you can check for specific method by adding check like this
if request.method == "POST":
note : allways use capitalized method while adding this check
and I'm not sure where you're calling makePayment() function and whatever data you're trying to access in your python script you've to pass it through ajax{data:{}} like this
function makePayment(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "order:add" %}',
data: {
csrfmiddlewaretoken: "{{csrf_token}}",
order_key : "your order key",
first_name : $('#first_name').val(),
last_name : $('#last_name').val(),
address : $('#address').val()
},
success: function (json) {
console.log(json.success)
},
error: function (xhr, errmsg, err) {},
});
}
and than access it like this
def add(request):
basket = Basket(request)
if request.method == "POST":
order_key = request.POST.get("order_key")
#....all other fields

Related

Request with Ajax from java script not working

I have this button in my HTML code :
<button type="submit" id="post-form" class="btn btn-primary" onclick="send()">Send</button>
And the java script code with function send() :
function send() {
$.ajax({
type: 'POST',
url: "http://app.localhost/feedback",
dataType: "json",
data : {
feedback: $('#feedback').val(),
email: $('#email').val(),
},
success : function(json) {
$('Backdrop').hide();
console.log("requested access complete");
}
});
}
And in my views from django project I have the function related to entry-point /feedback. But the execution never arrives at the success step.
And also from postman I can send the request but from js it is not working.
The view related to my entry point is :
#csrf_exempt
def feedback(request):
if request.method == 'POST':
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
fromField = body['email']
subject = 'New FeedBack from {}'.format(fromField)
body = body['feedback']
sendEmail("ex#ex.co", subject, body,
replyTo=['ex#ex.co', 'ex.ex#gmail.com'])
return redirect('/')
Is that button a form submit button?
If so, you don't need the button's onclick event.
Try the following.
<form id="yourForm">
<button type="submit" id="post-form" class="btn btn-primary">Send</button>
</form>
$("#yourForm" ).submit(function() {
$.ajax({
type: 'POST',
url: "http://app.localhost/feedback",
dataType: "json",
data : {
feedback: $('#feedback').val(),
email: $('#email').val(),
},
success : function(json) {
$('Backdrop').hide();
console.log("requested access complete");
}
});
});
Hope this helps.

Data is not submitting through Ajax is not Submitting

here is ajax code
$('#form').on('submit', function(e){
$.ajaxSetup({
headers: {
"X-CSRFToken": document.querySelector('[name=csrfmiddlewaretoken]').value,
}
});
$.ajax({
type : 'POST',
url: "{% url 'HealthTest' %}",
data: {
first_name : $('#first_name').val(),
deparment : $('#deparment').val(),
Reg_No : $('#Reg_No').val(),
Health_status : $('#Health_status').val(),
dataType: "json",
},
success: function(data){
$('#output').html(data.msg) /* response message */
},
failure: function() {
}
});
});
This form code
{% csrf_token %}{{form.as_p}}
when i press submit in my pages this error message pop up in console window
enter image description here
I Tried different solution but it is not working for me. I am new to this Thank in advance.
First configure the urls.py:
from .views import functionpost
urlpatterns = [
path('<url>', functionpost),
]
On Python views.py side:
from django.http import JsonResponse
def functionpost(self, request):
if request.method == 'POST':
context = {'informations':{'info1': request.POST['information_1']},
'info2': request.POST['iformation_2']}
return JsonResponse(context)
On html the post forms goes:
<form id="post-form" method="POST">
{% csrf_token %}
<div class="input-group form-group">
<input type="text" class="form-control form-control-sm"
id="information_1">
</div>
<div class="input-group form-group">
<input type="text" class="form-control form-control-sm"
id="information_2">
</div>
<button type="submit" class="main-btn">Button</button>
</form>
js:
$.ajax({
type:'POST',
url:"<intire_url>",
data: {
information1:$('#information_1').val(),
information2:$('#information_2').val(),
csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(),
},
success: function(data) {
alert(data.informations['info1'] + data.informations['info2']);
}
});

how do i remember the radio button selection in django

i'm trying to make sure that even if the user refresh the page or goes back and comes back to that page, the radio button is still the same as what the user selects.
N.B: the value of the radio button is saved in sessions
<div class="col-md-1 ps-md-1">
<input class="align-middle h-100" type="radio" name="deliveryOption" id="{{option.id}}"
value="{{option.id}}">
</div>
my ajax
$('input[type=radio][name=deliveryOption]').on('change', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: '{% url "checkout:cart_update_delivery" %}',
data: {
deliveryoption: $(this).val(),
csrfmiddlewaretoken: "{{csrf_token}}",
action: "post",
},
success: function (json) {
document.getElementById("total").innerHTML = json.total;
document.getElementById("delivery_price").innerHTML = json.delivery_price;
},
error: function (xhr, errmsg, err) {},
});
});
</script>
my view
def cart_update_delivery(request):
cart = Cart(request)
if request.POST.get("action") == "post":
delivery_option = int(request.POST.get("deliveryoption"))
delivery_type = DeliveryOptions.objects.get(id=delivery_option)
updated_total_price = cart.cart_update_delivery(delivery_type.delivery_price)
session = request.session
if "purchase" not in request.session:
session["purchase"] = {
"delivery_id": delivery_type.id,
}
else:
session["purchase"]["delivery_id"] = delivery_type.id
session.modified = True
response = JsonResponse({"total": updated_total_price, "delivery_price": delivery_type.delivery_price})
return response

i'm writng regist html ,django + ajax,partial load page,but memory is increased and the page is stuck

django veiews
def regist(request):
hashkey = CaptchaStore.generate_key()
image_url = captcha_image_url(hashkey)
captcha = {'image_url': image_url, 'hashkey':hashkey}
if request.POST:
username = request.POST['username']
password = request.POST['password']
password1 = request.POST['password1']
key = request.POST['hashkey']
capt = request.POST['captcha']
if username != '' and password != '' and password1 != '':
if len(password) >= 6:
if captchautil.is_valid(capt, key):
check_user = User.objects.filter(username=username)
if not check_user:
if password == password1:
user = User.objects.create_user(username=username, password=password)
userprofile = UserProfile.objects.create(user=user, name=username, level='Bronze')
msg = '注册成功,现在去登录吧'
else:
msg = '密码不一致,请重新输入'
else:
msg = '用户名已存在,请重新输入'
else:
msg = '请输入正确的验证码'
else:
msg = '密码长度至少6位'
else:
msg = '请输入用户名与密码'
return HttpResponse(msg)
return render(request, 'regist.html', locals())
html code
<form action="/regist/" method="post" id="myForm">
{% csrf_token %}
<input type="text" id='username' name="username">
<input type="password" id='password' name="password">
<input type="password" id='password1' name="password1">
<input id='captcha' name="captcha" required>
<input value="{{hashkey}}" type="hidden" name="hashkey" id='hashkey'>
<button type="submit" name="click" id='click'>注册</button>
script code:
$(document).ready(function(){
$.ajax({
type: "POST",
url: "{% url 'regist' %}",
data: {
"username": username,
"password": password,
"password1": password1,
"key": hashkey,
"capt": captcha,
"csrfmiddlewaretoken": '{{ csrf_token }}',
},
dataType: "text",
success:function(response){
alert(response);
$("#myForm").submit();
},
});
My intention is to load the returned results directly into 'div', without loading all html.
But when I submit it, the whole page gets stuck directly, and the browser memory goes up. Only when I close the page can I get back to normal.
and i'm try ajax return false,but it will happen again
html code:
$.ajax({
type: "POST",
url: "{% url 'regist' %}",
data: {
"username": username,
"password": password,
"password1": password1,
"key": hashkey,
"capt": captcha,
"csrfmiddlewaretoken": '{{ csrf_token }}',
},
dataType: "text",
success:function(response){
alert(response);
$("#myForm").submit();
},
});
return false;
I think the reason for this is that Ajax didn't submit the data. I didn't see the message in the server request log, and it has been creating new variables, causing the browser memory to increase and the page to get stuck. But I haven't found the line where it happened.
Hope your answer can solve the problem.thk

Magento newsletter ajax request returns null

I am trying to send a newsletter subscription request to Magento, but It returns null and nothing happens.
I've searched around and found very different URLs to post the request. And also grabbed the code from the file from base template.
In fact, maybe I am not sending the correct parameters or whatever.
This is the code in use:
<form method="post" id="newsletter-form">
<input type="hidden" class="url" value="<?php echo $this->getUrl('newsletter/subscriber/new') ?>">
<input id="newsletter" type="text" name="email" placeholder="RECEBA NOVIDADES" value="" class="input-text myFormInput" maxlength="128" autocomplete="off" style="width: 188px !important">
<button type="submit" id="ajax-newsletter-submit" title="CADASTRAR"
class="button myFormButton" style="margin-top:20px;margin-left: -107px !important;width: 103px">CADASTRAR</button>
</div>
</form>
Javascript:
var newsletterSubscriberFormDetail = new VarienForm('newsletter-form');
$j(function() {
$j("#ajax-newsletter-submit").click(function() {
var email =$j("#newsletter").val();
var url=$j(".url").val();
var dataString = 'email='+ email;
if(email=='') {
$j("#newsletter").focus();
} else {
var a = email;
var filter = /^[a-zA-Z0-9_.-]+#[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{1,4}$/;
if(filter.test(a)){
$j.ajax({
type: "POST",
url: url,
data: dataString,
success: function(){
alert('Assinatura realizada com sucesso!');
$j("#newsletter").val('');
}
});
} else {
$j("#newsletter").focus();
}
}
return false;
});
});
Try this code,
var val_form = new VarienForm('your form id');
jQuery("#your form id").submit(function(e)
{
if (val_form.validator && val_form.validator.validate())
{
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
alert('success');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('Failure');
}
});
this.reset(); //form field reset
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
}
});

Categories

Resources