How can I include a div with Javascript? Using MANDRILL & Full Calendar - javascript

We're trying to have the modal-body div below included in the email sent by Mandrill. Or set it up as a variable. Does anyone know how we could do this in a simple manner using the same setup we have now for the other included variables in the email? Thanks so much!
eventClick: function(event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
var start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
}
});
});
});//]]>
jQuery(function($)
{
$("#contact_form").submit(function()
{
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
$.ajax(
{
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'API',
'message': {
'from_email': "email#email.com",
'from_name': "name",
'headers': {
'Reply-To': "email#email.com"
},
'subject': 'Confirmation - Sign Up',
RIGHT HERE--->'text': ,
'to': [
{
'email': email,
'name': name,
'type': 'to'
}]
}
}
})
.done(function(response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
HTML:

Related

Display message from Lambda via Javascript after successful form submit

I'm using this code to add a contact form to my Serverless website (hosted on S3). When an email is successfully sent, the Lambda instance returns the message "Thank you! You can download the sample here: <a href='https://someurl.com'>Download</a>". I want to display that message to the user who submitted the form but I can't figure out how to do so. Currently, my javascript displays a hard-coded message based on the response code from the AWS API Gateway. But I don't want to include the download url in the javascript because I don't want users to be able to see the download without first signing up via the form.
Is there a way to grab the string returned by the Lambda instance and pass it back in the response body and then display that message to the user via javascript?
My current jQuery javascript for the form:
! function($) {
"use strict";
$("form", ".contact-form ").submit(function(t) {
t.preventDefault();
var r = !0,
s = this,
e = $(s).siblings(".contact-form-result"),
o;
// Escape if the honeypot has been filled
if (!!$("#whatname").val()) return;
if ($(s).find(":required").each(function() {
$(this).css("border-color", ""), $.trim($(this).val()) || ($(this).css("border-color", "red"), r = !1);
var t = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
"email" != $(this).attr("type") || t.test($.trim($(this).val())) || ($(this).css("border-color", "red"), r = !1)
}).keyup(function() {
$(this).css("border-color", "")
}).change(function() {
$(this).css("border-color", "")
}), r) {
//var c = $(this).serialize();
var firstname = $("#name-input").val();
var lastname = $("#lastname-input").val();
var mobile = $("#mobile-input").val();
var email = $("#email-input").val();
var message = $("#message-input").val();
var data = {
firstname : firstname,
lastname : lastname,
mobile : mobile,
email : email,
message : message }
$.ajax({
url: "PATH-TO-AMAZON-API",
type: "post",
dataType: "json",
crossDomain: "true",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(data),
beforeSend: function(data) {
$('#submit-mail').attr('disabled', true);
//$('#status').html('<i class="fa fa-refresh fa-spin"></i> Sending Mail...').show();
o = '<p class="form-message form-success">Sending...</p>';
e.removeClass("hidden").html(o)
},
success: function (data) {
// clear form and show a success message
//alert("Successfull");
o = '<p class="form-message form-success">Thank you for your message!</p>';
e.removeClass("hidden").html(o)
$(s)[0].reset();
setTimeout(function() {
e.addClass("hidden").html("")
}, 5e3);
$('#submit-mail').removeProp('disabled');
},
error: function (jqXHR, textStatus, errorThrown) {
// show an error message
//alert("UnSuccessfull");
o = '<p class="form-message form-error">Sorry, there was an error. Please try again later.</p>';
e.removeClass("hidden").html(o)
setTimeout(function() {
e.addClass("hidden").html("")
}, 5e3);
$('#submit-mail').removeProp('disabled');
}
});
}
})
}(jQuery);
And my Python Lambda function (using an API, SES and Dynamo [not currently using Dynamo]):
import boto3
from botocore.exceptions import ClientError
import json
import os
import time
import uuid
import decimal
client = boto3.client('ses')
sender = os.environ['SENDER_EMAIL']
subject = os.environ['EMAIL_SUBJECT']
configset = os.environ['CONFIG_SET']
charset = 'UTF-8'
dynamodb = boto3.resource('dynamodb')
recipient = 'example#email.com'
def sendMail(event, context):
print(event)
#Send mail for contact form
try:
data = event['body']
content = 'Message from ' + data['firstname'] + ' ' + data['lastname'] + ',<br>Phone: ' + data['mobile'] + ',<br>Message Contents: ' + data['message']
#saveToDynamoDB(data)
response = sendMailToUser(data, content)
except ClientError as e:
print(e.response['Error']['Message'])
else:
print("Email sent! Message Id:"),
print(response['MessageId'])
return "Thank you! You can download the sample here: <a href='https://someurl.com'>Download</a>"
def list(event, context):
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
# fetch all records from database
result = table.scan()
#return response
return {
"statusCode": 200,
"body": result['Items']
}
def saveToDynamoDB(data):
timestamp = int(time.time() * 1000)
# Insert details into DynamoDB Table
table = dynamodb.Table(os.environ['DYNAMODB_TABLE'])
item = {
'id': str(uuid.uuid1()),
'firstname': data['firstname'],
'lastname': data['lastname'],
'email': data['email'],
'message': data['message'],
'createdAt': timestamp,
'updatedAt': timestamp
}
table.put_item(Item=item)
return
def sendMailToUser(data, content):
# Send Email using SES
return client.send_email(
Source=sender,
ReplyToAddresses=[ data['email'] ],
Destination={
'ToAddresses': [
recipient,
],
},
Message={
'Subject': {
'Charset': charset,
'Data': subject
},
'Body': {
'Html': {
'Charset': charset,
'Data': content
},
'Text': {
'Charset': charset,
'Data': content
}
}
}
)
Thanks for your help!
Well, that was easy...after all the searching online for days trying to figure this out. Turns out the message is right there in success: function (data) so I all I have to do is return the data variable in my javascript. So it would look like this:
success: function (data) {
// clear form and show a success message
//alert("Successfull");
o = '<p class="form-message form-success">' + data + '</p>';
e.removeClass("hidden").html(o)
$(s)[0].reset();
setTimeout(function() {
e.addClass("hidden").html("")
}, 5e3);
$('#submit-mail').removeProp('disabled');
},

How do I prevent writing url's inside my input field using jQuery validation?

We are using https://jqueryvalidation.org/ library to validate the contact form on our website.
The details will be sent to a 3rd party web service
jQuery("#contactform").validate({ // initialize the plugin
rules: {
name: {required:true},
email: {required:true},
phonenumber: {required:true}
},
submitHandler: function(form, evt) {
evt.preventDefault();
var name = jQuery('#name').val();
var email = jQuery('#email').val();
var phonenumber = jQuery('#phonenumber').val();
var contactform_url = jQuery("#contactform").attr('action');
jQuery.ajax({
type: "POST",
url: contactform_url,
cache: false,
data: {
name: name,
email: email,
phonenumber: phonenumber
},
beforeSend: function() {
}
}).done(function(data, textStatus, jqXHR) {
}).fail(function(jqXHR, textStatus, errorThrown) {
});
}
});
Problem: The current validation cannot prevent a user to input a url to the name input field
so var name = jQuery('#name').val(); can have a value of https://www.google.com/
Do you know how can I avoid users to input a link or url to our name input field or at least convert the url into a string?
Any help is greatly appreciated. Thanks
Try with following code hope it will work for you
$('#name').on('input', function() {
var input=$(this);
if (input.val().substring(0,4)=='www.'){input.val('http://www.'+input.val().substring(4));}
var re = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,#?^=%&:\/~+#-]*[\w#?^=%&\/~+#-])?/;
var is_name=re.test(input.val());
if(is_name){
alert('valid');
}
}
else{
alert('invalid');
}
});
Your second condition ful fill here
var url = "google.com";
var lastCom = url.slice(-3);
alert(lastCom); // "com"

How to load alert plugin when form is submited

I am using an alert plugin and I want it to load the alert-success when the form is submitted under the .done function in my script. Plugin page here.
The plugin works with a button like this:
<button id="alert-success" class="bordered" >Try out!</button>
then when the user clicks the button it calls the jquery $(document).ready and executes the plugin. All I want to accomplish is to be loaded without the button when the form is submitted.
My form script:
var form = $('#contact');
form.submit(function (event) {
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
var $form = $(this);
var name= $('#fname').val();
var email= $('#email').val();
var Message = $('#msg').val();
var selectedOption = document.getElementById("country").value;
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country : selectedOption,
},
beforeSend: function () {
form.append(form_status.html(sending. . .
<i class="material-icons w3-spin w3-text-indigo" style="font-size:30px">mail_outline</i>').fadeIn()); }
}).done(function (data) {
form_status.html('<i id="alert-success" class="bordered material-icons w3-text-green" style="font-size:30px">done</i> message sent!').hide(10000);
});
document.getElementById("fname").value = "";
document.getElementById("email").value = "";
document.getElementById("country").value = "";
document.getElementById("msg").value = "";
});//end contact form
Script that executes when the button is clicked:
$(document).ready(function() {
var variants = {
'alert-success': {
args: [
{
content: 'Success! Message sent!',
icon: $.sweetModal.ICON_SUCCESS
}
]
},
};
for (var key in variants) {
if (variants.hasOwnProperty(key)) {
var variant = variants[key];
$('#' + key).on('click', { variant: variant }, function(e) {
var variant = e.data.variant;
variant.fn = variant.fn || $.sweetModal;
variant.fn.apply(this, variant.args);
});
} }
});
try adding this inside done method
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Email: email,
message: Message,
Country : selectedOption,
},
success:function()
{
// after success show modal
$.sweetModal({
title: "Title here",
message: "",
content: "Alert Success",
classes: ["success"],
showCloseButton: !0,
blocking: !0,
timeout: null,
theme: $.sweetModal.THEME_LIGHT,
type: $.sweetModal.TYPE_MODAL,
});
}
});
Customize as per your need. Customization options are on the plugin page

Issue with Javascript, it won't allow the Full Calendar to load

Could someone please tell me what's wrong with the following code. I'm guessing it has something to do with missing brackets for the Javascript, but I can't put my finger on it. How can we use the var modal = $("#modal"); where it says, var content = "Hello " + name + ", You have signed " + modal + " up to XYZ";
When we implement this code, the Full Calendar HTML dissapears of the site. Thanks a lot!
$(window).load(function() {
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'prev,next today'
},
defaultDate: '2016-03-15',
events: [
{
title: 'Event',
start: '2016-03-26T11:00:00',
end: '2016-03-26T12:00:00',
},
],
eventClick: function(event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
}
)}
jQuery(function($) {
$("#contact_form").submit(function() {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello "+name+ ", You have signed "+modal+ " up to XYZ";
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'api',
'message': {
'from_email': "email",
'text': "Hello ",
'from_name': "name",
'headers': {
'Reply-To': "email"
},
'subject': 'Confirmation - Sign Up',
'text': content,
'to': [{
'email': email,
'name': name,
'type': 'to'
}]
}
}
})
.done(function(response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
});
return false; // prevent page refresh
});
});
});
change this:
modal.modal();
}
)} //<-----this
to this:
modal.modal();
}
}) //<----this
full code simplified:
$(document).ready(function() {
$('#calendar').fullCalendar({
header: {
left: '',
center: 'title',
right: 'prev,next today'
},
defaultDate: '2016-03-15',
events: [
{
title: 'Event',
start: '2016-03-26T11:00:00',
end: '2016-03-26T12:00:00',
},
],
eventClick: function(event) {
console.log(event)
// alert(event.start.format('MMMM Do YYYY'))
start = event.start.format('MMMM Do YYYY'),
end = event.end.format('MMMM Do YYYY'),
html = '<p>Starts: ' + start + '<p>';
html += '<p>Ends: ' + end + '<p>';
var modal = $("#modal");
modal.find(".modal-title").html(event.title);
modal.find('.modal-body').html(html)
modal.modal();
}
}) //<-----this one
$("#contact_form").submit(function() {
var email = $("#email").val(); // get email field value
var name = $("#name").val(); // get name field value
var msg = $("#msg").val(); // get message field value
var content = "Hello " + name + ", You have signed " + modal + " up to XYZ";
$.ajax({
type: "POST",
url: "https://mandrillapp.com/api/1.0/messages/send.json",
data: {
'key': 'api',
'message': {
'from_email': "email",
'text': "Hello ",
'from_name': "name",
'headers': {
'Reply-To': "email"
},
'subject': 'Confirmation - Sign Up',
'text': content,
'to': [{
'email': email,
'name': name,
'type': 'to'
}]
}
}
})
.done(function(response) {
alert('You have been signed up. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
});
return false; // prevent page refresh
});
});

Unable to send email array in mandrill JSON response

Hi I have a form which the user inputs a message and sends it to multiple recipients. I am using Mandrill as my email client and the script is as follows
function sendMail() {
var email = $("#email").val();
var array = email.split(',');
var name = $("#name").val();
var msg = $("#msg").val();
$.ajax({
type: 'POST',
url: 'https://mandrillapp.com/api/1.0/messages/send.json',
data: {
'key': 'xxxxxxx',
'message': {
'from_email': 'xxx#xxx.com',
'to': [
{
'email': email,
'type': 'to'
}
],
'autotext': 'true',
'subject': 'Hello world ' + name,
'html': msg + '<br> <br> <img src="http://res.cloudinary.com/dzmi0gssmwn/image/upload/v1434831725/wpeqmuld5gzdplf7kzcw.jpg" width:320px;height:auto/>'
}
}
}).done(function(response) {
alert('Your message has been sent. Thank you!'); // show success message
$("#name").val(''); // reset field after successful submission
$("#email").val(''); // reset field after successful submission
$("#msg").val(''); // reset field after successful submission
})
.fail(function(response) {
alert('Error sending message.');
});
}
</script>
When I input one email address the message gets successfully sent and received in the inbox. But when I submit with multiple addresses, I get a response that the message has been sent, but when I looked at the logs it states
[{"email":"xxxx#xxx.xxx, xxxx#xxx.xxx","status":"invalid","_id":"c045cbffbd0c4c5ab5581f5edaff2007","reject_reason":null}]
Does anybody know how to solve this issue or understand whats going wrong ? Thanks for taking the time to read this.
First just use mandrill API through js SDK
<script type="text/javascript" src="mandrill.min.js"></script>
It can be found here.
var m = new mandrill.Mandrill('api key');
function sendTheMail(){
m.messages.send({
"message": {
"from_email": "xx#xx.com",
"from_name": "test",
"to":[{"email": "xx#x.com", "name": "someone's_name"}],
"subject": "subj",
"text": "msg"
}
});
}
Shouldn't you be doing this on server, however, since this will basically show your API to public, and once it's public even for millisecond a bot will have it saved forever.

Categories