Ajax Submitting form Twice - ajax

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

Related

Ajax call is being accidently triggered

I'm creating a login page and at the bottom of the pop-up form, there is another button that takes you to the registration page. The issue appears to be that when navigating to the new page it all sits under the original sign-in form which uses an ajax call to check if the user exists so when they try to submit the registration form it then calls that ajax call from the sign-in form.
Sign-in form
<div id="myForm">
<form onsubmit="return false;" id="loginForm">
<h1>Login</h1>
<label for="email"><b>Email</b></label>
<input type="email" id="email" placeholder="Enter Email" name="email" required>
<label for="psw"><b>Password</b></label>
<input type="password" id="psw" placeholder="Enter Password" name="psw" required>
<div id="message" class="alert-danger"></div>
<br />
<button type="submit" id="submit" class="btn">Login</button>
<button type="button" class="btn cancel" onclick="closeForm();">Close</button>
</form>
<div class="d-inline">
<button class="btn-info">#Html.ActionLink("User Registration", "SignUp", "SignUp_SignIn")</button>
</div>
</div>
Then the ajax call is
$(document).ready(function () {
$("form").on('submit', function (event) {
var data = {
'email': $("#email").val(),
'psw': $("#psw").val()
};
$.ajax({
type: "POST",
url: 'SignUp_SignIn/CredentialCheck',
data: data,
success: function (result) {
if (result == true) {
$("#message").text("Login attempt was successful");
}
else {
$("#message").text("Email/Password didn't match any results");
}
},
error: function () {
alert("It failed");
}
});
return false;
});
});
After looking at the comments I realized that the reason that the login form was being called from the layout.cshtml so when the ajax call was being called it was grabbing all the form tags that existed on any page that was loaded up. After changing the ajax so it was calling a specific id for the login form instead of form it allowed for proper actions to take place.
An example of what I'm refusing to
$(document).ready(function () {
$("form").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});
The above will try to redirect you on the submit of any form that is loaded up, but if we go through and change the way it accesses the form like below then it will only work if the one specific form is submitted.
$(document).ready(function () {
$("#loginForm").on('submit', function (event) {
$.ajax({
type: "POST",
url: url,
data: data,
success: function (result) {
//Do stuff
}
});
});
});

How to send other variable datas along with new FormData() inside 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 ');

input(file) and input (text) send with one ajax

html
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector"/>
<input type="file" id="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
js/ajax
var fileVar = null;// global var to store file info
$(document).ready(function(){
$('#dataForm').on('submit', function(e) {
e.preventDefault();
SendData();
});
$('#fileSelector').on('change',function(ev){
fileVar = null;
fileVar = new FormData();
$.each(ev.target.files, function(key, value)
{
fileVar.append(key, value);
});
});
});
function SendData(){
var formData = new FormData($("#dataForm")[0]);
// should i add the filerVar like this ?
// formData.append("Image", fileVar);
$.ajax({
type: "POST",
url: "checkinput.php",//you need to add this '?files part' to URL
data: formData,// use fileVar here now
cache: false,
processData: false,
// contentType: false,
success:function(data)
{
console.log(data);
console.log("success");
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log("failure");
}
});
}
php
print_r($_POST);
print_r($_FILES);
my intention is to send input(file) and input(text) in one ajax , i can get the input file value if i add ajax data with fileVar , but i cant get my input text value i have no idea why , can anyone tell me what i did wrong ?
var formData = new FormData($("#dataForm")[0]) is the way to get both to one ajax but i cant get any input text value.
anyone can teach me how to make this work ?
I think you need to specify input name attributes:
<body>
<form method="post" action="" id="dataForm" enctype="multipart/form-data">
<input type="text" id="textSelector" name="textSelector"/>
<input type="file" id="fileSelector" name="fileSelector"/>
<button name="sub-comfirm" class="btn-selection-content" type="submit" id="sub-comfirm">Send</button>
</form>
</body>
Hope that helps.

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