Node JS Form Sumit using Ajax - 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();

Related

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

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

variable is not found inside ajax

<div class="modal-body">
<form>
<div class="form-group">
<label for="email" class="col-form-label">Email address:</label>
<input type="email" class="form-control" id="signUpEmail" name="email">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Password:</label>
<input type="password" class="form-control" id="signUpPassword" name="password" onchange="check_pass()">
</div>
<div class="form-group">
<label for="pwd" class="col-form-label">Confirm Password:</label>
<input type="password" class="form-control" id="signUpConPassword" name="password" onchange="check_pass()">
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary" id="signUpSubmit" disabled="true" >Sign Up</button>
</div>
</div>
</div>
</div>
<script type="text/javascript">
function check_pass()
{
//alert(document.getElementById('signUpPassword').value);
if (document.getElementById('signUpPassword').value ==
document.getElementById('signUpConPassword').value) {
document.getElementById('signUpSubmit').disabled = false;
}
else
{
document.getElementById('signUpSubmit').disabled = true;
}
}
$('#signUpSubmit').click(function()
{
//alert("signup completed");
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: $email,
password: $password
},
success: function() {
alert('Email Sent');
}
});
});
</script>
This code snippet shows ReferenceError: $email is not defined when I click on the signupSubmit button although I defined the variable inside the function.
I also try
var email=document.getElementById('signUpEmail').value;
var password = document.getElementById('signUpPassword').value;
but, same error. I guess there is a problem in variable declaration. What is the correct form of variable declaration inside the function?
You have to change the $email and $password to email ,password
$.ajax({
url: 'signup.php',
type: 'POST',
data: {
email: email,
password: password
},
success: function() {
alert('Email Sent');
}
});
Remove the $
data: {
email: $email,
password: $password
},
The data being passed has two properties - "email" and "password", the values of the properties are stored in the variables email and password.
Your code should look like this:
/* Remove these two lines */
var email=document.getElementById('signUpEmail');
var password = document.getElementById('signUpPassword');
...
data: {
"email": $("#signUpEmail").val(),
"password": $("#signUpPassword").val()
}
The $ is the jQuery function call, and the "#signUpEmail" is the selector for the element with an id of "signUpEmail". The val() method will return the value of the input.
document.getElementById("something").value
is the same as
$("#something").val()
If you're using jQuery for the Ajax, you might as well use it to get the values.

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.

AJAX form submission issue in Internet Explorer

For some reason the newsletter sign-up form bar I'm creating is not working as it should in IE. In fact, it's not working at all. If you visit the link below in Chrome or Firefox it works like it should, but in any version of IE it doesn't.
Anyone have any leads to fix this?
Here's the code, summarized:
$(function() {
$('#name').textboxhint({
hint: 'First Name'
});
$('#email').textboxhint({
hint: 'Email Address'
});
$("#submitButton").click(function() {
// VALIDATE AND PROCESS FORM
var name = $("#name").val();
var email = $("#email").val();
var dataString = 'name='+ name + '&email=' + email;
// HANDLE DATA: SHOW ERROR IF FIELDS ARE BLANK
if (name=='' || name=='First Name' ){
$('.errorIconName').show();
return false;
}
if (email=='' || email=='Email Address'){
$('.errorIconEmail').show();
return false;
}
else {
$.ajax({
type: "POST",
url: "#",
data: dataString,
success: function(){
$('#signupWidget').fadeOut(400).hide();
$('#thankyouText').fadeIn(700).show();
$('.errorIcon').fadeOut(200).hide();
$('#signupWrap').delay(3000).fadeOut(800);
}
});
}
return false;
});
});
and...
<form action="" method="post">
<span id="sprytextfield1" class="pr20">
<input name="name" id="name" type="text"/>
<div class="errorIconName" style="display:none"></div>
</span>
<span id="sprytextfield2" class="pr20">
<input name="email" id="email" type="text"/>
<div class="errorIconEmail" style="display:none"></div>
</span>
<span>
<input type="submit" name="widgetButton" id="submitButton" value="SUBMIT"/>
</span>
</form>

Resources