Data is not submitting through Ajax is not Submitting - javascript

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']);
}
});

Related

html form in Django returns none

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

Send a value of foreach loop form using ajax in laravel

I'm trying to send value from form to controller but the error that faced me all forms send value as a first form id I want each form to send the data inside it when I press the send button, but what happens is that everyone sends its content based on the first ID of the form;
blade code
#forelse($matches as $match)
<form class="ajaxform">
#csrf
<div class="wrapper-new1">
<input type="text" class="form-control" name="record_one" id="validationCustom18" value="{{$match->record_one}}" required>
<input type="text" class="form-control" name="record_two" id="validationCustom18" value="{{$match->record_two}}" required>
<input type="hidden" class="form-control" name="id" value="{{$match->id}}" id="validationCustom18" >
</div>
<button type="submit" style="margin-top: 4px;" class="btns">تغيير نتيجة المباراة </button>
</form>
#empty
<div class="alert alert-danger"> لا يوجد مباريات لعرضها الان </div>
#endforelse
ajax code
$('.btns').on("click", function(event){
event.preventDefault();
let record_one = $("input[name=record_one]").val();
let record_two = $("input[name=record_two]").val();
let id = $("input[name=id]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: "/admin/team/matchesList/"+id+"",
type:"POST",
data:{
record_one:record_one,
record_two:record_two,
id :id,
_token: _token
},
success:function(response){
console.log(response);
if(response) {
$('.success').text(response.success);
$(".ajaxform")[0].reset();
}
},
});
});
$('.btns').on("click", function(event){
event.preventDefault();
let form = $(this).closest('.ajaxform');
let record_one = form.find("input[name=record_one]").val();
let record_two = form.find("input[name=record_two]").val();
let id = form.find("input[name=id]").val();
let _token = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: "/admin/team/matchesList/"+id+"",
type:"POST",
data:{
record_one:record_one,
record_two:record_two,
id :id,
_token: _token
},
formElement:form,
success:function(response){
console.log(response);
if(response) {
$('.success').text(response.success);
this.formElement[0].reset();
}
},
});
});

Sending image from Form in FormData with Ajax doesn't appear on server side (Flask python)

I want to create Bootstrap Modal that has a form with textarea and image, and send that to the server.
My form on modal looks like this:
<form id="formData" method="POST" enctype="multipart/form-data">
<fieldset class="form-group">
<div class="form-group">
<textarea class="form-control" id="content" name="content" required></textarea>
</div>
<div class="form-group">
<label for="image">Got any photo?</label>
<input class="form-control-file" id="image" name="image" type="file">
</div>
</fieldset>
<button class="btn purple-btn-outline-modal" type="submit">Add</button>
</form>
The AJAX I'm using:
var form = document.forms.namedItem("formData");
form.addEventListener('submit', function (ev) {
var oData = new FormData(form);
oData.append('image', $('#image')[0].files[0])
for (var p of oData) {
console.log(p); // <- logs image in oData correctly
}
$.ajax({
url: '/test/',
type: 'POST',
method: 'POST',
data: oData,
enctype: 'multipart/form-data',
cache: false,
contentType: false,
processData: false,
success: function (data) {
},
});
ev.preventDefault();
}, false);
But on the server side (Python Flask) the image is not in request form:
#main.route('/test/', methods=['POST'])
def test():
if request.method == 'POST':
app.logger.debug(request.form) # ImmutableMultiDict([('content', 'my sent content')])
app.logger.debug(request.form['content']) # 'my sent content'
app.logger.debug(request.form['image']) # <- KeyError: 'image'
return jsonify(...)
What is wrong?
SOLVED.
Solution by #v25:
request.files['image']
worked.

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

ajax Uncaught ReferenceError: post is not defined at HTMLButtonElement.<anonymous>

Have no idea what it could be. Please help me release this ajax commentaries. I have never done this before. HTML form for input text and some ids:
<form id="send_comment" method="POST" action="write_comment.php">
<input hidden type="text" id="c_post_id" name="c_post_id" value="<?=$_GET["id"]?>">
<input hidden type="text" id="c_user_id" name="c_user_id" value="<?=$user_id?>">
<div class="form-group shadow-textarea">
<textarea class="form-control z-depth-1" type="text" id="c_text" rows="3" placeholder="Write comment here..." name="c_text" required pattern="^[a-zA-Z0-9\s]+$"></textarea>
</div>
<div class="col-md-12 text-center">
<button id="make_comment" class="btn btn-default" name="make_comment" type="submit" value="Submit"><i class="fas fa-check" style="font-size: 35px;"></i></button>
</div>
</form>
PHP processing:
if($_POST["make_comment"]) {
$c_post_id = $_POST["c_post_id"];
$c_user_id = $_POST["c_user_id"];
$c_text = $_POST["c_text"];
$date = date("m/d/y G:i:s<br>", time());
$sql = "INSERT INTO `comments` VALUES ('$c_post_id','$c_user_id',null,'$c_text','$date')";
if ($connect->query($sql) === TRUE) {
header("Location: http://thecobnmod.com/post.php?id=$c_post_id");
}
else {
exit( "Error: " . $sql . "<br>" . $conn->error);
}
}
JS ajax:
function funcSuccess (data) {
$("#comment_ajax").text(data);
}
function funcBefore (){
$("#comment_ajax").text("Loading comment...");
}
$(document).ready(function(){
$("#make_comment").bind("click", function () {
event.preventDefault();
$.ajax({
post: $("#c_post_id").val(),
user: $("#c_user_id").val(),
text: $("#c_text").val(),
url: "write_comment.php",
type: "POST",
data: {
c_post_id:post,
c_user_id:user,
c_text:text
},
dataType: "html",
beforeSend: funcBefore,
success: funcSuccess
});
});
});
Post id comes fro GET request to input field. I thought it could be a problem but not. now I really do not know what's wrong. Please help.
I strongly recommend consulting the documentations: Ajax doc
Ajax doesn't have post property AFAIK!
I'm not sure what you wanted to do, but here is a simple ajax example:
$.ajax({
url: 'here/is/some/url',
type: 'post',
data: {
some_key: 'value1',
other_key: 'value2',
/*...*/
},
dataType: 'html',
beforeSend: function() {/*...*/}
success: function(result) {/*...*/},
error: function(error) {/*...*/}
});

Categories

Resources