Ajax Form Submit using jQuery - html

I am working with a form that I want to submit with ajax to a api that sends email to the email mentioned in it and the api was working in postman with raw data but I can't get it to work with the form using jQuery and ajax so if you guys can tell me why my function is not working and sending the email it will be of great help to me
Function for form submit:-
$(function() {
$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
// additional error messages or events
},
submitSuccess: function($form, event) {
event.preventDefault(); // prevent default submit behaviour
// get values from FORM
var name = $("input#name").val();
var email = $("input#email").val();
var phone = $("input#phone").val();
var message = $("textarea#message").val();
var firstName = name; // For Success/Failure Message
// Check for white space in name for Success/Fail message
if (firstName.indexOf(' ') >= 0) {
firstName = name.split(' ').slice(0, -1).join(' ');
}
$this = $("#sendMessageButton");
$this.prop("disabled", true); // Disable submit button until AJAX call is complete to prevent duplicate messages
$.ajax({
"url": "http://178.18.243.33:8089/email/sendmailusingtemplate",
"method": "POST",
"timeout": 0,
"headers": {
"Content-Type": "application/json"
},
"data": JSON.stringify({
"to": "nkulhari96#gmail.com",
"cc": "services#gmail.com",
"template": "contact_us_001",
"name": "name",
"email": "email",
"mobile": "phone",
"message": "message"
}),
},
cache: false,
success: function() {
// Success message
$('#success').html("<div class='alert alert-success'>");
$('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-success')
.append("<strong>Your message has been sent. </strong>");
$('#success > .alert-success')
.append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
error: function() {
// Fail message
$('#success').html("<div class='alert alert-danger'>");
$('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×")
.append("</button>");
$('#success > .alert-danger').append($("<strong>").text("Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!"));
$('#success > .alert-danger').append('</div>');
//clear all fields
$('#contactForm').trigger("reset");
},
complete: function() {
setTimeout(function() {
$this.prop("disabled", false); // Re-enable submit button when AJAX call is complete
}, 1000);
}
});
},
filter: function() {
return $(this).is(":visible");
},
});
$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});
/*When clicking on Full hide fail/success boxes */
$('#name').focus(function() {
$('#success').html('');
});
Code for Form:-
<form name="sentMessage" id="contactForm" novalidate="">
<div class="control-group form-group">
<div class="controls">
<input type="text" placeholder="Full Name" class="form-control" id="name" required="" data-validation-required-message="Please enter your name.">
<p class="help-block"></p>
</div>
</div>
<div class="control-group form-group">
<div class="controls">
<input type="tel" placeholder="Phone Number" class="form-control" id="phone" required="" data-validation-required-message="Please enter your phone number.">
<div class="help-block"></div></div>
</div>
<div class="control-group form-group">
<div class="controls">
<input type="email" placeholder="Email Address" class="form-control" id="email" required="" data-validation-required-message="Please enter your email address.">
<div class="help-block"></div></div>
</div>
<div class="control-group form-group">
<div class="controls">
<textarea rows="5" cols="100" placeholder="Message" class="form-control" id="message" required="" data-validation-required-message="Please enter your message" maxlength="999" style="resize:none"></textarea>
<div class="help-block"></div></div>
</div>
<div id="success"></div>
<!-- For success/fail messages -->
<button type="submit" class="btn btn-primary" id="sendMessageButton">Send Message</button>
</form>

Related

Sending data gives [object HTMLInputElement] as query response

I am trying to send user form data to partner endpoint like this:
$('#registrationFrm').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "https://pixel.plexop.com/?country="+countryid+"&_v=6&name="+firstName+"&lastname="+lastName+"&phone="+phone
+"&email="+emailid+"&ud=&e=2&adv=1&a=4&f=221161&FormId=1807&SerialId=1210053",
data: $("#registrationFrm").serialize(),
success: function() {
alert('success');
}
});
});
I get 200 "OK" back, but as of data I get this sent when I inspect it on "network":
Query string: country "[object HTMLSelectElement]
Query string: name "[object HTMLInputElement]
Query string: lastname "[object HTMLInputElement]"
My form looks like this:
<form id="registrationFrm" >
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="First Name" name="firstName" id="firstName" required />
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="text" class="form-control" placeholder="Last Name" name="lastName" id="lastName" required />
<span class="glyphicon glyphicon-user form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<input type="tel" class="form-control" placeholder="Phone No" name="phone" id="phone" required />
<span class="glyphicon glyphicon-earphone form-control-feedback"></span>
What am I doing wrong here?
Probably, you define your variables like:
const firstName = document.getElementById('firstName');
/*and so*/
But you should do this like:
const firstName = document.getElementById('firstName').value;
UPD:
$('#registrationFrm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url:
'https://pixel.plexop.com/?country=' +
countryid.value +
'&_v=6&name=' +
firstName.value +
'&lastname=' +
lastName.value +
'&phone=' +
phone.value +
'&email=' +
emailid.value +
'&ud=&e=2&adv=1&a=4&f=221161&FormId=1807&SerialId=1210053',
data: $('#registrationFrm').serialize(),
success: function () {
alert('success');
}
});
});

How to send data to HTML page and how to use AJAX for Single Page Application in NodeJS Server using express.js framework?

How can I display the form submitted data in another HTML Page
From 1st page (page1.html)collecting the data from users and after appending this data in the database I want to show the submitted values in another page i.e.(page4.html)
Below is my code
I have tried using res.sendFile or res.send
server.post('/addname', (req, res) => {
const user = {
timestamp: new Date,
FName: req.body.FName,
LName: req.body.LName,
Phone: req.body.Phone,
Email: req.body.email,
Contact: req.body.business,
Business: req.body.contact,
OTP: req.body.otp_field
}
res.sendFile(__dirname + '/page4.html');
//along with file rediraction, how can i send or show the "User" vaules in respactivte filed
});
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
nAs I can see in your code
<body>
<div>
<div align="center">
<form action="/addname" method="GET">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="submit" value="Submit" /></form>
</div>
</div>
</body>
Your form method is "GET", it should be "POST" as your API is "POST".
server.post('/addname', (req, res) => {
<form action="/addname" method="GET">
//Just change to
<form action="/addname" method="POST">
While sending and HTML file you need to send your submitted data too.
res.sendFile(__dirname + '/page4.html');
In order to save your hurdle switch to Single Page Application and use some JavaScript frame work like AngularJs, ReactJs or if not then also stick to single page and use Ajax calls for submit calls.
Else see "ejs" in place of "HTML" and use scriptlet to send and show data over HTML.
To send data to "ejs" via expressJs
res.render('show.ejs', {message});
With Ajax you can do this:
HTML
<body>
<div>
<div align="center">
<form id="form1">
<label>Please enter below details</label><br><br>
<label>First Name *: </label><input id="FName" type="text" name="FName"/><br><br>
<label>Last Name *: </label><input id="LName" type="text" name="LName"/><br><br>
<label>Email Address *: </label><input type="email" name="email"><br><br>
<br><br>
<input type="button" value="Submit" onClick:"submitForm()"/>
</form>
<div id="showValue"></div>
</div>
</div>
</body>
JavaScript
function submitForm() {
$.ajax({
url: '/addName',
type: 'POST',
headers: headers,
data: {
"Fname": $("#FName").val(),
"Lname": $("#LName").val(),
"email": $("#email").val()
},
success: function(result) {
//append result to your html
//Dynamic view
$("#form1").hide();
var html = '<div><span>First Name: ' + result.fName + '</span><span>Last Name: ' + result.lName + '</span></div>';
$("#showValue").html(html);
},
error: function (error) {
alert('error ',error);
}
});
}
Server side code I'm assuming you are using express.js and body-parser
app.post('/addName', (req, res) => {
//Insert into db
var body = req.body;
res.send({
fName: body.FName,
lName: body.LName
});
});

Bootstrap + JS Validation - ErrorText and Red border not showing up on fields and on Submit

I'm having the strangest issue, I have written the js validation code without any known issues, but for some reason it's not working on my site or on my fiddle. Can anyone tell me:
How can I change the order of the links or code to make the JS
Validation work in bootstrap?
I've been stuck on this issue for weeks, and I need a point in the right direction. Thanks in advanced.
https://jsfiddle.net/Lts7rwya/3/
JS:
$(document).ready(function(){
$.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]*$/i.test(value);
}, "Please enter only letters");
$.validator.addMethod("numbersonly", function(value, element) {
return this.optional(element) || /^[0-9\s]*$/i.test(value);
}, "Please enter only numbers");
$(".form-contact").validate({
errorClass: "error-class",
validClass: "valid-class",
rules: {
fullname: {
required: true,
lettersonly: true,
minlength: 5
},
youremail: {
required: true,
email: true
},
phone: {
required: true,
maxlength: 13,
numbersonly: true
},
yourmessage: {
required: true,
minlength: 10,
maxlength: 3000
}
},
messages: {
youremail: {
required: "Please enter your full email address."
},
fullname: {
required: "Please enter your first and last name.",
minlength: "Your full name must be at least 4 letters."
},
phone: {
required: "Please enter your full phone number",
minlength: "Your phone number is too short.",
maxlength: "Your phone number is too long."
},
yourmessage: {
required: "Don't forget to enter your message.",
minlength: "Please, add more detail to your message.",
maxlength: "Please keep the message under 3,000 words/characters."
}
},
highlight: function(element, errorClass) {
$(element).removeClass(errorClass);
}
});
});
HTML:
<div id="message" class="col-md-6 col-sm-12 bordercon">
<form name="sentMessage" id="contactForm" class="form-contact" action="message.php#contact" method="post">
<h2 style="margin-top:0px;"><i class="fa fa-1x fa-envelope"></i> Message Us</h2>
<div class="form-group">
<input type="text" class="form-control emailaddress" name="fullname" placeholder="Your Full Name *" id="fullname">
</div>
<div class="form-group">
<input type="email" class="form-control emailaddress" name="youremail" placeholder="Your Email Address *" id="youremail">
</div>
<div class="form-group">
<input type="tel" class="form-control emailaddress" name="phone" placeholder="Your Phone Number *" id="phone">
</div>
<div class="form-group">
<textarea type="text" class="form-control" name="yourmessage" placeholder="Your message, question, or quote request *" id="yourmessage"></textarea>
</div>
<div class="col-lg-12 text-center">
<div class="buttonwrapper">
<input class="sendmessage" title="Send Message" type="submit" name="send" value="Send Message">
</div>
</div>
<br />
</form>
</div>
<script>
window.jQuery || document.write('<script src="https://code.jquery.com/jquery-1.11.2.min.js"><\/script>')
</script>

How to validate ZK Textbox by using HTML5+CSS3 validation?

I'm using ZK7, HTML5, CSS3 and I'm trying to validate below zk textbox element if it is a valid email:
<form id="validation-form">
<fieldset>
<div class="form-group">
<label class="block clearfix" for="email">
<span class="block input-icon input-icon-right">
<z:textbox id="emailInput" type="email" class="form-control" placeholder="${labels.login.email}"/>
<i class="icon-envelope"></i>
</span>
</label>
</div>
<div class="clearfix">
<button id="forgotPassword" type="button" class="width-35 pull-right btn btn-sm btn-danger">
<i class="icon-lightbulb"></i>
${labels.send}
</button>
</div>
</fieldset>
</form>
Here is the script:
<script type="text/javascript">
jQuery(function($) {
$('[data-rel=tooltip]').tooltip();
$(".select2").css('width','200px').select2({allowClear:true})
.on('change', function(){
$(this).closest('form').validate().element($(this));
});
var $validation = false;
//documentation : http://docs.jquery.com/Plugins/Validation/validate
$('#validation-form').validate({
errorElement: 'div',
errorClass: 'help-block',
focusInvalid: false,
rules: {
email: {
required: true,
email:true
}
},
messages: {
email: {
required: "Please provide a valid email.",
email: "Please provide a valid email."
}
},
invalidHandler: function (event, validator) { //display error alert on form submit
$('.alert-danger', $('.login-form')).show();
},
highlight: function (e) {
$(e).closest('.form-group').removeClass('has-info').addClass('has-error');
},
success: function (e) {
$(e).closest('.form-group').removeClass('has-error').addClass('has-info');
$(e).remove();
},
errorPlacement: function (error, element) {
if(element.is(':checkbox') || element.is(':radio')) {
var controls = element.closest('div[class*="col-"]');
if(controls.find(':checkbox,:radio').length > 1) controls.append(error);
else error.insertAfter(element.nextAll('.lbl:eq(0)').eq(0));
}
else if(element.is('.select2')) {
error.insertAfter(element.siblings('[class*="select2-container"]:eq(0)'));
}
else if(element.is('.chosen-select')) {
error.insertAfter(element.siblings('[class*="chosen-container"]:eq(0)'));
}
else error.insertAfter(element.parent());
},
submitHandler: function (form) {
},
invalidHandler: function (form) {
}
});
$('#modal-wizard .modal-header').ace_wizard();
$('#modal-wizard .wizard-actions .btn[data-dismiss=modal]').removeAttr('disabled');
})
</script>
It is working when I change z:textbox to html input as:
<input id="emailInput" type="email" class="form-control" placeholder="${labels.login.email}"/>
How should I do the same by using zk textbox?
I'm not 100% sure if this is what you wanted, cause your question has a lot of javascript, jquery and the first code doesn't really looks like zk(only your internationalization is familiar).
If you use zk you can do the following :
<textbox value="#bind(vm.email)" id="email"
constraint="/.+#(.+\.[a-z]+|)/: Please enter a valid e-mail address"
type="email" placeholder="enter email" />
I did put a simpel email constraint there, but you can change the constraint to what you want.
Hope this helps you.
There is this nice example of integrating jquery masks with zk.
For client side validation this should be fine.
In addition, ZK offers form validation as well as constraints for InputElements

Send JSON from HTML form with NODEJS backend

I haven't done front end HTML since I was 10 and that was drag and drop frontpage stuff. with static pages. As a result I'm really rusty.
What I need to do is put together a web client for a rest API that I wrote in NodeJS. My question is how, do you send a request from a form (say a log in form) to the server where the body of the POST request is a JSON of the email/password?
HTML form:
<form id="loginForm" action="" method="" class="form-horizontal">
<fieldset>
<legend>Log in</legend>
<div class="control-group">
<label class="control-label" for="email">Email</label>
<div class="controls">
<input type="text" class="input-xlarge" id="email">
</div>
</div>
<div class="control-group">
<label class="control-label" for="password">Password</label>
<div class="controls">
<input type="password" class="input-xlarge" id="password">
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">Save changes</button>
<button class="btn">Cancel</button>
</div>
</fieldset>
</form>
I suggest a lot of reading. To get you started with a very basic example, though, you will find a page with a sample form below that does what you need. You just need to replace the string your URL here with the actual URL you expect will be doing the handling.
The serializeObject() function was taken from here: Convert form data to JavaScript object with jQuery
<html>
<body>
<form id="loginForm" action="" method="">
Username: <input type="text" name="username" id="username" /> <br />
Password: <input type="password" name="password" id="password" /> <br />
<input type="submit" />
</form>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(function () {
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("#loginForm").bind("submit", function(evt) {
console.log(JSON.stringify($("#loginForm").serializeObject()));
$.ajax({
url: "your URL here",
type: "POST",
contentType: "application/json",
data: JSON.stringify($("#loginForm").serializeObject()),
success: function (data, textStatus, jqXHR) {
// do something with your data here.
},
error: function (jqXHR, textStatus, errorThrown) {
// likewise do something with your error here.
}
});
return false;
});
});
</script>
</body>
</html>
The problem with your form is that input elements don't have name attributes. The name attribute is essential in many ways, so I would fix your html by setting each element's name attribute to the same value as its id attribute. The serializeObject function relies on form elements having names.
Here's an example using jQuery:
<form name="myform" action="#" method="POST">
Username: <input type="text" id="user" name="username"/><br/>
Password: <input type="password" id="pass" name="password"/>
<input type="submit" id="login" value="Login"/>
</form>
<script type="text/javascript">
var user=$('#user').val(), pass=$('#pass').val();
$('login').bind('click', function() {
$.ajax('/my/url', {
type: 'POST',
contentType: 'text/json',
data: JSON.stringify({username:user, password:pass}),
complete: function() { /* Do something with the response. */ }
});
return false; // Prevent form submit.
});
</script>
This might help you. Here is the form below: If you notice there is action and method if you don't know what these are, just go on and search for it. Action is the target server file that handles the information you send and method is get which is retrieving not updating.
Existing Users Username: Password:
Keep Me
Logged In
Here is the jquery part to handle the ajax call:
$.ajax({
type: "GET",
url: action,
data: form_data,
success: function(response)
{
if($.trim(response) == 'success')
window.location.replace("profile.php");
else
$("#result").html(response);
}
});
return false; });
});