How to send other variable datas along with new FormData() inside AJAX? - ajax

Here I am sending the upload files into FormData() to be accessed in expressjs. And it is working perfectly.
$(".commonForm").submit(function (e) { //For Submitting the Uploaded Files
e.preventDefault();
if(validateForm($(this).attr('name'), text))
{
$.LoadingOverlay("show");
var formData = new FormData(this);
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: formData,
processData: false,
contentType: false,
dataType: "json",
success: function(response){
if (response.status == '200') {
$.LoadingOverlay("hide");
swal({
title: "Excellent!",
text: "Files submitted successfully!",
icon: "success",
button: "Ok",
showCancelButton: true
}).then((result) => {
if (result) {
window.location.reload();
}
});
}
},
error: function (e) {
console.log("some error", e);
}
});
}
});
But along with that I want to send one another field data along with formData.
var text = 'Done';
How to send this along with formData in data ?
I am trying this:
data : {
formData:formData,
text:text
}
But then I don't think that I will be able to retrieve the uploaded files data directly with req.files
UPDATE:
route code/expressjs
router.post('/api/upload/:cid',function(req,res,next){
console.log("req.body.text = " + req.body.text + req.query.text);
upload2(req,res,function(err) {
if(err) {
console.log("Error is important = "+ err);
}
else
{
console.log("Uploaded successfully.");
}
})
})
MULTER CODE:
var upload2 = multer({storage: storage2, limits: { fileSize: 1024 * 1024 * 1 }}).array('FileUploadForClient',4);
HTML HANDLEBAR FORM CODE:
<form name="{{this.status}}" class="commonForm" enctype="application/x-www-form-urlencoded" action="/api/upload/{{this.commonID}}" method="post">
<td class="col-sm-2">
<div class="center">
<select name="sourcesSelect" id="{{this.commonID}}" data-notUse="{{this._id}}" data-Id4AddtasksBigpaths="{{this.Id4AddtasksBigpaths}}" class="custom-select sources" placeholder="{{this.status}}" style="font-size:20px; background: {{this.background}}; color: white;" {{this.statusDisabled}}>
<option value="0" >In Progress</option>
<option value="1" >Done</option>
<option value="2" >Rejected</option>
</select>
</div>
</td>
<!-- <td class="col-sm-2"><span id="deadline" style="font-size:14px"><input type="text" class="form-control" value="{{this.deadline}}" readonly/></span></td> -->
<td class="col-sm-1">
<!-- <input type="file" class="btn btn-light" name="FileUploadForClient" multiple required/> -->
<input type="file" id="{{this._id}}" class="form-control" name="FileUploadForClient" multiple required {{this.statusDisabled}} />
</td>
<td>
<button type="submit" class="btn btn-primary btn-block col-sm-2" style="font-size:16px" {{this.statusDisabled}}>Submit</button>
</td>
</form>

Use the method append to add another parameter to the request
var formData = new FormData(this);
formData.append('text', 'text to send in the request ');

Related

Use Ajax post select modal in PartialView of ASP.NET Core MVC is null

Ajax code
$(function(){
var form = $(this).parents('.modal').find('form');
var actionUrl = form.attr('action');
var sendData = new FormData(form.get(0));
$.ajax({
url: actionUrl,
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
...
},
error: function (message) {
alert(message);
}
})
})
}
In the partial view, I use select object #EmpSelect to add value and text to select object #RolesList, then use ajax post ID, Title, isVirtualGroup and RolesList to controller.
But the RolesList is always null, how can I do fix it?
javascript code
$('#AddRolesGroup').click(function () { $('#EmpSelect :selected').map(function (row, item) { console.log(item.text); $('#RolesList').append("<option value='" + item.value + "'>" + item.text + "</option>") }); });
View about select object part
<div id="area">
<select id="EmpSelect" class="form-select col-md-12" size="8"
multiple aria-label="EmpSelect">
</select>
<button class="btn" type="button" id="ClearSelect">Clear Select Roles</button>
<select asp-for="RolesList" asp-items="Model.RolesList" class="form-select col-md-12" size="8"
multiple aria-label="RolesList">
</select>
</div>
You need to make sure the select is in the form and make sure you have selected values.Here is a demo:
<form id="form1">
<div id="area">
<select id="EmpSelect" class="form-select col-md-12" size="8"
multiple aria-label="EmpSelect">
</select>
<button class="btn" type="button" id="ClearSelect">Clear Select Roles</button>
<select id="RolesList" name="RolesList" class="form-select col-md-12" size="8"
multiple aria-label="RolesList">
<option value="1">role1</option>
<option value="2">role2</option>
<option value="3">role3</option>
</select>
</div>
</form>
<button onclick="postdata()">postdata</button>
js:
function postdata() {
var sendData = new FormData($("#form1").get(0));
$.ajax({
url: "PostData",
method: 'post',
data: sendData,
processData: false,
contentType: false,
cache: false,
success: function (redata) {
//
},
error: function (message) {
alert(message);
}
})
}
action:
public IActionResult PostData(string[] RolesList)
{
return Ok();
}
result:

Ajax Submitting form Twice

I have a form in a modal window that allows a user to resend a confirmation email. When the form is submitted, the confirmation email is sent twice, instead of once. Everything else is working exactly as it should.
Form is pretty standard:
<form enctype="multipart/form-data" id="ReMailf" name="ReMailf" role="form" data-toggle="validator">
<fieldset>
<div class="row">
<p>You may enter a different email than your original if you wish. However, the original email will remain as the main contact on your application.</p>
<label class="desc" for="prim_email"> Email </label>
<input id="prim_email" name="prim_email" type="email" class="form-control" value="<?php echo $tE['prim_email']; ?>" data-error="Please Enter A Valid Email Address" required/>
<div class="help-block with-errors"></div>
</div>
<div class="row">
<input id="submitForm" name="submitForm" class="btn btn-success" type="submit" value="Resend Conformation "/>
<input name="uniqid" type="hidden" value="<?php echo $tE['unqID']; ?>"/>
<input name="ReMAIL" type="hidden" value="ReMAIL"/>
</div>
</fieldset>
</form>
… and here's the handler:
$(document).ready(function () {
$("#ReMailf").on("submit", function(e) {
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
});
e.preventDefault();
});
$("#submitForm").on('click', function() {
$("#ReMailf").submit();
});
});
I've read a number of other post about this, and tried some of the suggestions, but nothing is working. It either doesn't submit at all, or submits twice.
This is the only form on the page...
Suggestions please?
It is because you are using a button or submit to trigger the ajax event. Use this instead:
$(document).ready(function() {
$("#ReMailf").on("submit", function(e) {
e.preventDefault(); //add this line
var postData = $(this).serializeArray();
// var formURL = $(this).attr("action");
$.ajax({
url: '_remail.php',
type: "POST",
data: postData,
success: function(data, textStatus, jqXHR) {
$('#myModal .modal-header .modal-title').html("YOUR EMAIL HAS BEEN RESENT");
$('#myModal .modal-body').html(data);
// $("#ReMailf").remove();
},
error: function(jqXHR, status, error) {
console.log(status + ": " + error);
}
or you can just use a simple form with action and method. It will do the job

AJAX - upload image with ajax without form on laravel

i try to make upload image with ajax without form, when i am sent data without the image, data successfully submitted to the database, but when i am adding an image, when i try to submit, no response at all,
this is my template code :
<input type="hidden" name="lesson_id" value="{{-- $lessons->id --}}">
<input type="hidden" name="parent_id" value="0"> -->
<div class="form-group">
<label>Komentar</label>
<textarea rows="8" cols="80" class="form-control" name="body" id="textbody0"></textarea>
</div>
<ul class="right">
<input type="file" name="image" id="image" />
<img id="myImg" src="#" />
<button type="button" class="btn btn-primary" onClick="doComment({{ $lessons->id }},0)" >Kirim</button>
and this is my script for submit data :
function doComment(lesson_id, parent_id) {
var body = $('#textbody'+parent_id).val();
var image = $('#image').prop('files')[0];
if (body == '') {
alert('Harap Isi Komentar !')
}else {
var postData =
{
"_token":"{{ csrf_token() }}",
"lesson_id": lesson_id,
"parent_id": parent_id,
"image": image,
"body": body
}
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="token"]').attr('value')
}
});
$.ajax({
type :'POST',
url :'{{ url("lessons/coments/doComment") }}',
dataType: 'json',
data : postData,
beforeSend: function(){
// Show image container
swal({
title: "Sedang mengirim Komentar",
text: "Mohon Tunggu sebentar",
imageUrl: "{{ asset('template/web/img/loading.gif') }}",
showConfirmButton: false,
allowOutsideClick: false
});
{{-- $("#loader").show(); --}}
},
success:function(data){
if (data.success == false) {
window.location.href = '{{ url("member/signin") }}';
}else if (data.success == true) {
$('#textbody'+parent_id).val('');
swal({
title: "Komentar anda sudah terkirim!",
showConfirmButton: true,
timer: 3000
});
getComments();
}
}
});
}
}
Can any one help me?
postData = new FormData();
if(!!file.type.match(/image.*/)){
postData.append("image", file);
$.ajax({
type : 'POST',
url : '{{ url("lessons/coments/doComment") }}',
data : postData,
dataType: 'json',
processData: false,
contentType: false,
success: function(data){
alert('success');
}
});
}else{
alert('Not a valid image!');
}

Node JS Form Sumit using Ajax

I am new in Node JS , I want to submit a form using ajax like all we are doing in PHP/CakePHP but here i am facing a problem.
HTMl code
<form role="form" action="javascript:;" id="myform">
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter email">
</div>
<button type="submit" class="btn btn-default" id="enter">Submit</button>
</form>
My AJAX code is
$('.btn').click(function(e){
e.preventDefault();
var data = $('#myform').serialize();
$.ajax({
url: '/ajax',
type: 'POST',
cache: false,
data: JSON.stringify(data),
contentType: 'application/json',
success: function(data) {
console.log(data);
console.log(JSON.stringify(data));
},
error: function(jqXHR, textStatus, err){
alert('text status '+textStatus+', err '+err);
}
})
});
app.js code
app.post('/ajax', bodyParser(), function (req, res){
var obj = {};
console.log('body: ' + JSON.stringify(req.body));
var input = JSON.stringify(req.body);
var data = {
name : input.name,
email : input.email
};
var query = db.query("INSERT INTO users set ?",data, function(err, rows){
console.log(query.sql);
if (err)
console.log("Error inserting : %s ",err );
res.send({'success' : true, 'message' : 'Added Successfully'});
});
});
But when i submit this form then it generate an error in node console like
SyntaxError: Unexpected token "
at parse (D:\man_node\node_modules\body-parser\lib\types\json.js:83:15)
I think that, I am not 100% sure, that you should replace var data = $('#myform').serialize(); with var data = $('#myform').serializeArray();

Fancybox form submit with ajax

I have fancybox, where I want to submit a form. Also I want to handle that form by PHP code which is inside the same page. Below is my code.
function lunchModal(itemID){
jQuery('.share').on('click', function(){
$data = '<div class="shareModal" ><div class="modal-header"><h3>Share Form Submission</h3></div> \
<form action="" class="shareForm" method="post">\
<div class="modal-body">\
<div class="control-group">\
<label for="inputEmail" class="control-label">Enter Share Email</label>\
<div class="controls">\
<input type="email" id="inputEmail" placeholder="Share Email" name="email">\
<input type="hidden" value="'+itemID+'" id ="documentID">\
</div>\
</div>\
</div>\
<div class="modal-footer">\
<div class="controls">\
<button type="submit" class="btn btn-primary" id="submit">\
<i class="icon icon-envelope"></i>Share</button>\
</div>\
</div>\
</form>\
</div>';
jQuery.fancybox({
height : '55%',
autoDimensions: false,
width: '70%',
scrolling: 'auto',
padding: '20px',
title: false,
content: $data,
transitionIn: 'elastic',
transitionOut: 'elastic',
easingIn : 'easeOutBack',
easingOut : 'easeInBack',
centerOnScroll: 'true',
onComplete: submitForm()
});
item_id = false;
});
};
function submitForm() {
jQuery('#submit').on('submit', function(e) {
e.preventDefault();
//var dataString = {
// 'action' : 'shareDocument'
//};
var email = jQuery('#inputEmail').val();
var id = jQuery('#documentID').val()
var dataString = 'email='+email+'&documentID='+id;
//jQuery.extend(true, dataString, form_data);
console.log(dataString);
jQuery.fancybox.showActivity();
jQuery.ajax({
url: window.location.pathname,
type: 'POST',
data: dataString,
beforeSend: function() {
console.log(dataString);
},
success: function(data) {
alert('Document shared successfully');
}
});
return true;
});
}
Now my problem is When I submitting the form, the page is reloading, although I have used ajax form submit. Can anyone help me in this regard?
button type="submit"
this will reload ur page bcz ur submitting value to the declared page.
so you have to change ur code like below
input type="button" onclick="submitForm()"
this wont reload ur page.

Resources