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
});
});
Related
so I am at a bit of a bind here. So I have 2 jQuery scripts that handle a simple database row update (per the user ID, session), this lets the user send a "Gift" that adds value to the users database row column "bonus".
I got this working practically perfect, but the problem is: It will only get the first ID of the results when gifting, not any other user ID. I suspect this is a fault in the looping logic.
RequestBin tells me I have my correct ID for myself, and the user ID is stuck with the first iterated userid (we cant send to any other user ID). We need to be able to gift any result (user ID).
We use a dialog to trigger the AJAX call with Yes / No. Yes firing the AJAX event, no closing model.
The AJAX JS - Sends value to database
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: 'Gift this user new Gift?',
zIndex: 10000,
autoOpen: true,
width: '600',
height: '200',
resizable: false,
buttons: {
Yes: function () {
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
var sender = $('input[name=sender]').val();
var receiver = $('input[name=receiver]').val();
$.ajax({
url: 'https://xxxxx.m.pipedream.net',
type: 'POST',
data: {
sender: sender,
receiver: receiver
},
beforeSend: function () {
$('#gift-bonus-status').text('Sending...').delay(100).fadeIn().delay(100).fadeOut();
},
success: function (response) {
$('#gift-bonus-status').text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
}
});
},
No: function () {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
};
function fetchTopTransfers() {
$(function () {});
$.ajax({
url: '/ajax/ajax_user_list.php',
method: 'GET',
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
$('input[name=receiver]').val(item.user_id);
html_to_append +=
'<div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' +
item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' +
item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' +
formatBytesProduct(item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\')" id="gift-bonus-status">Give Gift</a></div></div><div style="padding-bottom:5px">' +
item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' +
item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' +
item.progress + '%</div></div></div><div style="clear:both"></div><input type="hidden" name="sender" value="<?=$account->getId()?>" /><input type="hidden" name="receiver" value="' +
item.user_id + '" />';
});
$("#top-transfers").html(html_to_append);
}
});
}
fetchTopTransfers();
setInterval(function () {
fetchTopTransfers()
}, 5000);
AJAX responce:
What is happening here???
Any help is much appreciated
As there many inputs with name receiver that's why you are not able to pass correct values. So, inside your ConfirmDialog function pass this as well it will refer to current element which is clicked. Then , inside your function to get required values you can use $(this).closest(".outer").find(..)...
Demo Code :
//just for demo..
var data = [{
"user_id": 1,
"product_id": 12,
"username": "acc",
"name": "swi",
"progress": "20",
"speed": 15
}, {
"user_id": 2,
"product_id": 12,
"username": "acc",
"name": "swi22",
"progress": "10",
"speed": 12
}]
var html_to_append = "";
$.each(data, function(i, item) {
//give outer div.. also pass `this` inside your function
html_to_append +=
'<div class="outer"><div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' +
item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' +
item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' +
(item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\',this)" >Give Gift</a></div></div><div style="padding-bottom:5px">' +
item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' +
item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' +
item.progress + '%</div></div><div style="clear:both"></div><input type="hidden" name="sender" value="23" /><input type="text" name="receiver" value="' +
item.user_id + '" /></div>';
});
$("#top-transfers").html(html_to_append);
//add el it refer to `this`
function ConfirmDialog(message, el) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: 'Gift this user new Gift?',
zIndex: 10000,
autoOpen: true,
width: '600',
height: '200',
resizable: false,
buttons: {
Yes: function() {
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
//get closest div(outer) then find required inputs values
var sender = $(el).closest(".outer").find('input[name=sender]').val();
var receiver = $(el).closest(".outer").find('input[name=receiver]').val();
console.log("Reciver --" + receiver + " Sender ---" + sender)
$.ajax({
url: 'https://xxxxx.m.pipedream.net',
type: 'POST',
data: {
sender: sender,
receiver: receiver
},
beforeSend: function() {
//use el here as well..
$(el).text('Sending...').delay(100).fadeIn().delay(100).fadeOut();
},
success: function(response) {
//use el here as well
$(el).text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
}
});
},
No: function() {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<div id="top-transfers">
</div>
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');
},
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
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:
I have this chunk of code:
$.ajax({
type: "POST",
async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {
}
}]
});
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [{
caption: 'Ok',
callback: function () {}
}]
});
}
});
When the ajax return success it displays the dialog box for a whole 2 seconds or so (not long enough for a user to read the message that it contains) then closes it. Using chrome's debugger, I've determined that it runs out of scope without waiting for a confirmation on the dialog box inside the success function. Does anyone know how I would go about halting the code until the user clicks ok?
Here is the full chunk of code for that ajax call..
var leZDB = null;
function zipSelectedAttachments() {
var ids = getSelectedTaskIDs();
if (ids.length > 0) {
leZDB = $.Zebra_Dialog('Do you want to zip the attachment(s)?', {
'type': 'question',
'title': 'Confirmation',
'buttons': ['Yes', 'No'],
'onClose':function (caption) {
if(caption = 'Yes') {
LinkAndPass(ids);
}
}
});
} else {
$.Zebra_Dialog('No attachments are selected.', {
'type': 'error',
'title': 'Error',
'buttons': [
{ caption: 'Ok', callback: function () { } }
]
});
}
}
function LinkAndPass(ids) {
leZDB.close();
if (true)
{
SendIDSForZipping(ids);
}
}
function SendIDSForZipping(ids) {
var csList = '';
var userID = $('#hiduserID').val();
for (var i = 0; i < ids.length; ++i) {
csList += ids[i] + ',';
}
var $this = $(this);
$this.die('click');
$.ajax({
type: "POST",
//async: true,
url: "Notes/ViewAttachments.aspx/CompressFiles",
data: "{ 'hidBinaryFileIDs': '" + csList + "', 'userID' : '" + userID+ "'}",
contentType: "application/json; charset=utf-8",
context:this,
dataType: "json",
success: function (data) {
var hasClickedOK = false;
var hasDisplayed = false;
if (!hasDisplayed) {
hasDisplayed = true;
$.Zebra_Dialog(data.d, {
'type': 'information',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
hasClickedOK = true;
}
}
]
});
}
},
error: function (xhr, ajaxOptions, thrownError) {
$.Zebra_Dialog('Error : ' + xhr.status + ' - ' + xhr.statusText + ' : ' + thrownError, {
'type': 'error',
'title': 'Confirmation',
'buttons': [
{
caption: 'Ok',
callback: function () {
}
}
]
});
}
});
}
The getSelectedIDs() returns an array of numbers.
The Code behind returns a string.
try asyn:false in $.ajax({
type: "POST",
async: true
});
The problem consisted of the web method being called from the code behind. A faulty piece of logic caused it to refresh the page, instantly closing the box.