How to submit two forms with their Ajax with one button - javascript

I have two forms one with product details like price, description and name. And the other with images, they both have different Ajax but they send data to the same route. I want to submit them with one button. So if I click a submit button it should submit all data at once which are price, name, image etc. How can I do this if possible?
Blade file
//Form1
<form id="form1">
<input type="hidden" value="{{csrf_token()}}" id="token"/>
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name"
placeholder="Enter product name">
<label for="price">Price</label>
<input type="text" class="form-control" name="price" id="price"
placeholder="Enter product price">
</form>
//Form2
<form id="file_form" method="post" enctype="multipart/form-data">
<input type="hidden" value="{{csrf_token()}}" id="token"/>
<label for="images">Choose Images</label>
<input id="files" type="file" class="" name="files[]" multiple />
</form>
//Submit Button
<input type='button' class="btn btn-primary" value="Submit" id="btn"/>
Javascript
//Form1 javascript
var token = $("#token").val();
$(document).ready(function(){
$("#btn").click(function(){
var url = '{{ route('product.store') }}';
var form = $('form')[0];
var formData = new FormData(form);
formData.append('_token', token);
$.ajax({
url: url,
data: formData,
type: 'POST',
cache: false,
contentType: false,
processData: false,
success:function(data){
if($.isEmptyObject(data.error)){
$("#msg").html("Product has been added successfull");
$("#msg").fadeOut(3000);
}
}
});
});
//Form 2 Javascript
$("#btn").click(function (e) {
e.preventDefault();
file_area = $('.file-area');
progressbar = $('.progress-bar');
status_bar = $('#status');
image_list = $(".image-list");
status_bar.css('display', 'block');
status_bar.html('<div class="fa-3x">' +
'<i class="fas fa-spinner fa-pulse"></i>' +
'</div>');
if (selected_files.length < 1) {
status_bar.html('<li class="error">Please select file</li>')
} else {
var data = new FormData();
data.append('_token', token);
for (var i = 0, len = selected_files.length; i < len; i++) {
data.append('files[]', selected_files[i]);
}
fiel_feild = $('#files');
$.ajax({
url: '{{ route('product.store') }}',
type: 'POST',
data: data,
contentType: false,
cache: false,
processData: false,
success: function (response) {
result = JSON.parse(response);
if (result['status'] == 'error') {
status_bar.html(result['error']);
} else if (result['status'] == 'success') {
selected_files = [];
image_list.html('');
file_area.css('display', 'none');
status_bar.html('<li class="success">File uploaded successfully.</li>');
}
}
});
return false;
}
});

Related

How to submit a form with file uploads with ajax

I have a long multistep form. which have text inputs and an upload file option. I'm trying to submit it to PHP with Ajax. I have tried FormData but I'm not sure how to send other select and text input fields.
https://developer.mozilla.org/en-US/docs/Web/API/FormData
How can I do this?
const addListingForm = $('#add-listing-form');
addListingForm.on('submit', function (e) {
console.log('Submitted');
const formData = new FormData(document.getElementById('add-listing-form'));
$.ajax({
url: `${SITE_URL}/private/shared/process`,
type: 'post',
data: formData,
processData: false,
contentType: false,
success: function (resp) {
console.log(resp);
},
error: function (err) {
console.log(err);
},
});
e.preventDefault();
});
<form action="" method="post" enctype="multipart/form-data" id="add-listing-form">
<input type="text" name="title" id="title" class="custom-input" />
<input type="text" name="tagline" id="tagline" class="custom-input" />
<input type="file" name="halal-certificate" class="custom-file-input" id="halal-certificate">
<input type="file" name="list-photos[]" multiple class="custom-file-input" id="list-photos">
<button type="submit">
Submit
</button>
</form>
try this
let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0];
let formData = new FormData();
formData.append("file1", firstFile);
formData.append("title", title );
//and add more
or
let title = document.getElementById("title").value;
let firstFile= document.getElementById("list-photos[]").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
formData.append("file1", firstFile);
formData.append("title", title );
req.open("POST", '/upload/image');
req.send(formData);

How can i send file and more info same time in flask? [duplicate]

This question already has answers here:
How to use FormData for AJAX file upload?
(9 answers)
Closed 3 years ago.
i have this code for upload file to flask.
client side:
<form id="upload-file" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Select a file</label>
<input name="file8" type="file">
</fieldset>
<fieldset>
<button id="upload-file-btn" type="button">Upload</button>
</fieldset>
</form>
<script>
$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-file')[0]);
$.ajax({
type: 'POST',
url: '/uploading',
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('Success!');
},
});
});
});
</script>
server side:
#app.route('/uploading', methods = ['POST'])
def uploading():
if request.method == 'POST':
file = request.files['file8']
if file and a
this code upload file and work. How can i send more info to flask same time ?like time = 2020 , age=20 , ...
i find my answer but i cant answer to my question, so i write my ans here:
i use header,send more info like id , ... with user (but this is unsafe):
client side:
<script>
$(function() {
$('#upload-file-btn').click(function() {
var form_data = new FormData($('#upload-file')[0]);
form_data.append('username', 'Chris');
//form_data.append ('id',$('#upload-file')[0]);
console.log(form_data);
$.ajax({
type: 'POST',
url: '/uploading',
data: form_data, headers: {
'Id': 2528,'age':20
},
contentType: false,
cache: false,
processData: false,
success: function(data) {
console.log('Success!');
},
});
});
});
</script>
server side:
#app.route('/uploading', methods = ['POST'])
def uploading():
if request.method == 'POST':
file = request.files['file8']
id=request.headers['Id']
age=request.headers['age']
Put the data in the form, then pass the form to new FormData instead of just the file input.
e.g.
<form id="upload-file" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Select a file</label>
<input name="file8" type="file">
</fieldset>
<fieldset>
<button id="upload-file-btn">Upload</button>
</fieldset>
<input type=hidden name=time value=2020>
<input type=hidden name=age value=20>
</form>
and
$("form").on("submit", function (e) {
e.preventDefault();
const form = this;
const form_data = new FormData(form);
// etc
});

How do I detect submitted button with ajax and php?

I have a form on my front-end and when the submit button is clicked I want to send the details to my get-emp.php file without page reload.
The code looks like this:
index.html
<form class="form-emp-details hide" action="">
<div class="form-group">
<label for="">First name:</label>
<input type="text" class="form-control input-emp-firstname" name="input_emp_firstname">
</div>
<div class="form-group">
<label for="">Last name:</label>
<input type="text" class="form-control input-emp-lastname" name="input_emp_lastname">
</div>
<div class="form-group">
<label></label>
<button type="submit" class="btn btn-default btn-submit-1" name="submit_emp_details">Save</button>
</div>
</form>
custom.js
$(".form-emp-details").("submit", function(e) {
var input_first_name = $(".input-emp-firstname").val();
$.ajax({
type: "POST",
url: "get-emp.php",
data: {
input_emp_firstname:input_first_name,
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});
});
get-emp.php
if(isset($_POST['submit_emp_details'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
I want to display the submitted form data on get-emp.php file but it seems that I am not able to detect the submitted button and echo the form data on.
My goal is to capture all form data with a single request variable or identifier $_POST['submit_emp_details']
Any help is greatly appreciated. Thanks
$("#MyformId").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(),
success: function(data)
{
// success..
}
});
});
You passing the POST data of firstname and lastname by:
input_emp_firstname
input_emp_lastname
so, you need to change the $_POST['submit_emp_details'] to $_POST['input_emp_firstname'] on file get-emp.php to
<?php
if(isset($_POST['input_emp_firstname'])) {
$firstname = $_POST['input_emp_firstname'];
echo $firstname;
}
Edit 2:
$.ajax({
type: "POST",
url: "get-emp.php",
cache: false,
data: {
submit_emp_details: {
input_emp_firstname:input_first_name,
input_emp_lastname:input_last_name
}
},
success: function(data) {
console.log(data)
},
error: function(xhr,status,error) {
console.log(error);
}
});

CSRF token missing in Django form submission

I am trying to submit a form via ajax.My template is as follows:-
<form method="POST" id="form1" class="SignUP signupform">
<div class="classheading">Sign-up</div>
{% csrf_token %}
<input type="text" name="user" placeholder="Username" class="sinput" required="true" />
<input type="text"name="email" placeholder="Email" class="sinput" required="true"/>
<input type="password"name="password"placeholder="Password" class="sinput" required="true"/>
<input type="password"placeholder="Re-enter Password" class="sinput" required="true"/>
<button type="submit" class="subform">Sign Up</button>
</form>
while ajax view submitting this form is:-
$(document).ready(function(){
$('#form1').submit(function(){
console.log('form is submitted');
var csrftoken = $("[name=csrfmiddlewaretoken]").val();
var formdata={
'username':$('input[name=user]').val(),
'email':$('input[name=email]').val(),
'password1':$('input[name=password]').val(),
'password2':$('input[name=password1]').val(),
};
console.log("Formvalue is taken");
$.ajax({
type:'POST',
url:'/Submit/signingup',
data:formdata,
dataType:'json',
encode:true,
headers:{
"X-CSRFToken": csrftoken
},
})
.done(function(data){
console.log(data);
});
event.preventDefault();
});
});
On backend, i'm submitting this form using Django.Corresponding View is as follows:-
#csrf_protect
def signup(request):
if request.method == 'POST':
form = SignupForm(request.POST)
if form.is_valid():
user = form.save(commit=False)
user.is_active = False
user.save()
current_site = get_current_site(request)
mail_subject = 'Activate your blog account.'
message = render_to_string('acc_active_email.html', {
'user': user,
'domain': current_site.domain,
'uid':urlsafe_base64_encode(force_bytes(user.pk)).decode(),
'token':account_activation_token.make_token(user),
})
to_email = form.cleaned_data.get('email')
email = EmailMessage(
mail_subject, message, to=[to_email]
)
email.send()
return HttpResponse("Confirm your email.")
else:
return JsonResponse({'success': False,'errors': [(k, v[0]) for k, v in form.errors.items()]})
But it's showing 403 error.In command prompt, it's showing "CSRF_TOKEN missing or incorrect".
What could be the possible error?
put csrf_token right after from open tag like this. and try
<form method="POST" id="form1" class="SignUP signupform">{% csrf_token %}
try this
$.ajax({
url: url ,
dataType: "json",
type: "POST",
data:{
data: val ,
csrfmiddlewaretoken: "{{ csrf_token }}",
},
success: function(data){
console.log(data)
}
})

Image is not inserted with data using ajax jquery in asp.net MVC

I'm trying to insert data to database using ajax with Jquery. My data is inserted without ajax perfectly but when i use ajax, there is something wrong with image. it get the file null in the controller in post method.
This is my Form in the View.
<form id="InsertForm" name="InsertForm" enctype="multipart/form-data">
<div class="form-group">
<label for="Name">Name</label>
<input type="text" class="form-control" name="StudentName" id="name" />
</div>
<div class="form-group">
<label for="LastName">Last Name</label>
<input type="text" class="form-control" name="StudentLastName" id="last" />
</div>
<div class="form-group">
<label for="Address">Address</label>
<input type="text" class="form-control" name="StudentAddress" id="address" />
</div>
<div class="form-group">
<label for="Gender">Gender</label>
<input type="text" class="form-control" name="Gender" id="gender" />
</div>
<div class="form-group">
<label for="Image">Image</label>
<input type="file" class="form-control" id="StudentImage" name="StudentImage" />
</div>
<button id="saveclick" type="submit" name="save">Save</button>
</form>
This is my Script in the View for inserting data with image.
<script>
$(document).ready(function () {
$("#saveclick").click(function (e) {
var student = {
StudentName: $("#name").val(),
StudentLastName: $("#last").val(),
StudentAddress: $("#address").val(),
Gender: $("#gender").val(),
StudentImage: $("#StudentImage").val().split('\\').pop()
};
//var formdata = new FormData($('InsertForm').get(0));
//var Student= $("#InsertForm").serialize();
var jsonData = JSON.stringify(student);
alert(jsonData);
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Student", null)',// Insert Action Method in Student Controller.
contentType: "application/json; charset=utf-8",
dataType: "json",
enctype: 'multipart/form-data',
data: jsonData,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
return false;
});
});
</script>
This is my Controller action Method in Student Controller.
[HttpPost]
public JsonResult Insert(Student student)
{
if (ModelState.IsValid)
{
Student stu = new Student();
stu.StudentName = student.StudentName;
stu.StudentLastName = student.StudentLastName;
stu.StudentAddress = student.StudentAddress;
stu.Gender = student.Gender;
HttpPostedFileBase file = Request.Files["StudentImage"];
file.SaveAs(HttpContext.Server.MapPath("~/Images/") + file.FileName);
stu.StudentImage = file.FileName;
db.Students.Add(stu);
db.SaveChanges();
return Json(student);
}
else
{
ModelState.AddModelError("", "Inavlid Data Inserted");
}
return Json(student);
}
Thanks if you solve my this problem.
try following
<script type="text/javascript">
$(document).ready(function () {
$("#saveclick").click(function (e) {
var data = new FormData();
var files = fileUpload.files;
fileData.append("StudentImage", files[0]);
fileData.append("StudentName",$("#name").val());
/* add all values as above one by one for LastName,Gender,Address*/
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Student", null)',// Insert Action Method in Student Controller.
contentType: "application/json; charset=utf-8",
processdata: false,
data: data,
type:"POST"
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
return false;
});
});
</script>
Here is the solution that solve my great problem. We need to append the ForamData in any variable.
<script>
$(document).ready(function () {
$("#saveclick").click(function (e) {
// Create FormData object
var fileData = new FormData();
var fileUpload = $("#StudentImage").get(0);
var files = fileUpload.files;
// Looping over all files and add it to FormData object
//for (var i = 0; i < files.length; i++) {
// fileData.append(files[i].name, files[i]);
//}
fileData.append("StudentImage", files[0]);
fileData.append("StudentName", $("#name").val());
fileData.append("StudentLastName", $("#last").val());
fileData.append("StudentAddress", $("#address").val());
fileData.append("Gender", $("#gender").val());
$.ajax({
type: "POST",
url: '#Url.Action("Insert", "Student", null)',
data: fileData,
processData: false,
contentType: false,
success: function (data) {
if (data.success) {
alert(data.message);
}
},
error: function (xhr) {
alert('error');
}
});
return false;
});
});
</script>

Categories