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');
},
Related
I want to send some data from chrome extension to Spreadsheet via GAS, but only "last" is dropped, although "Title" and "URL" is sent successfully.
Hence, could you kindly check the code?
const gasUrl = "here is my spreadsheet GAS url";
chrome.tabs.query({active: true, currentWindow: true}, tabs => {
title = tabs[0].title;
url = tabs[0].url;
last = url.slice(-8); // I want to send url's last 8 letters.
console.log(`Title: ${title}`);
console.log(`URL: ${url}`);
console.log(`Last: ${last}`); // I can see "last" is worked as intend here.
});
$(function() {
$('#doit').on('click', function() {
post2GAS(title, url, last);
});
});
function post2GAS(title, url, last){
const data = {
title: title,
url: url,
last: last
}
$.ajax({
type: 'POST',
url: gasUrl,
data: JSON.stringify(data)
})
.done(function (data) {
console.log("success"); // I can see success on console.
})
.fail(function (jqXHR, textStatus, errorThrown) {
console.log("failed");
console.log("XMLHttpRequest : " + jqXHR.status);
console.log("textStatus : " + textStatus);
console.log("errorThrown : " + errorThrown);
})
.always((data) => {
console.log("finished"); // I can see finished on console.
});
}
Seems GAS cannot catch "last" param correctly, but I cannot find specific reason.
Here is GAS code.
function doPost(e) {
var params = JSON.parse(e.postData.getDataAsString());
var title = params.title;
var url = params.url;
var last = params.last;
var sheet = SpreadsheetApp.openById('Sheet ID').getSheetByName("Sheet Name");
sheet.appendRow([title, url, last]);
var output = ContentService.createTextOutput();
output.setMimeType(ContentService.MimeType.JSON);
output.setContent(JSON.stringify( { sucsess: true }));
return output;
}
Thanks,
I'm so sorry, I have not deploy new GAS.
And when I deployed, it's solved.
Hence, I'm close this ticket here.
I am getting these errors when trying to use Facebook Login for the Web with the JavaScript SDK to store the user data into the database.
Undefined property: stdClass::$gender in /home/domain/public_html/loguser/facebook.php on line 30
Undefined property: stdClass::$locale in /home/domain/public_html/loguser/facebook.php on line 31
Undefined property: stdClass::$link in /home/domain/public_html/loguser/facebook.php on line 33
Apparently on Browser I am getting Gender : undefined message for one test login so in case like this thata a user may not specified his/her Gender, Locale or link how can I prevent this error on PHP side?
function verify_user() {
FB.api('/me', {locale: 'en_US', fields: 'id, name, first_name, last_name,email, link, gender,locale, picture'},
function (response) {
$.ajax({
url: "facebook.php",
data: {userinfo : JSON.stringify(response)},
type: "POST",
success: function(resp) {
//Your cutom code after successful login
}
});
});
}
and on facebook.php I have
$qry_body = " `oauth_provider` = 'facebook',
`oauth_id` = '".$userInfo->id."',
`name` = '".$userInfo->name."',
`first_name` = '".$userInfo->first_name."',
`last_name` = '".$userInfo->last_name."',
`email` = '".$userInfo->email."',
`gender` = '".$userInfo->gender."',
`locale` = '".$userInfo->locale."',
`picture` = '".$userInfo->picture->data->url."',
`link` = '".$userInfo->link."',
`modified` = '".date("Y-m-d H:i:s")."' ";
I am trying to send a JSON to my restapi, builded using Django Rest Framework and all I got an error message whenever I send this request, because the other ajax call have the same structure. No matter what view I am acessing, I got the same error.
I am pretty sure that the problem is on the ajax configuration or on the javascript that creates the json data, because when I send a json through 'Advanced REST client' or even through an app build using Xamarin Forms, the response is 200.
function createJson( email, pass){
tmpObj = {"Email": email, "Pass": pass};
json_result = JSON.stringify(tmpObj);
return json_result;
}
function sendLogin(){
var jsonData = createJson(State.email, State.pass);
console.log(jsonData)
$.ajax({
type: 'POST',
dataType: 'json',
contentType: 'application/json',
url: '/restapi/usuarios/login/',
data: jsonData,
processData: false ,
success: function(json) {
console.log(json);
State = json;
first_name = getFirstName(State.Nome)
title = "Login";
msg_html = "Bemvindo, <b>" + first_name + "</b>.";
modal = createModal(title, msg_html);
},
// handle a non-successful response
error : function(xhr,errmsg,err) {
var msg = "Oops! We have encountered an error: "+errmsg;
console.log(msg);
console.log(xhr.status + ": " + xhr.responseText);
setState({sent: 'error', result: err, email: ''});
}
});
}
On the Server-Side:
#api_view(['POST'])
def UsuarioLogin(request):
data = JSONParser().parse(request)
if all(credencial in data for credencial in ('Email', 'Pass')):
q = User.objects.filter(email=data['Email'])
if q.count() == 1:
username = q.get().username
password = data['Pass']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
usuario = q.get()
payload = UserSerializer(usuario, many=False)
return JsonResponse(payload.data, status=status.HTTP_200_OK, safe=False)
else:
return JsonResponse({"Mensagem": "Senha ou email incorretos"}, status=status.HTTP_401_UNAUTHORIZED, safe=False)
else:
return JsonResponse({"Mensagem": "Usuário não cadastrado"}, status=status.HTTP_404_NOT_FOUND, safe=False)
else:
return JsonResponse({"Mensagem": "Nem todos os campos foram informados"}, status=status.HTTP_400_BAD_REQUEST,
safe=False)
The error message, on the browser is:
400: {"detail":"JSON parse error - Expecting value: line 1 column 1 (char 0)"}
You should be able to access data simply by accessing request.data.
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'm looking for a solution where I can provide URL to specific image and then with Javascript I retrieve data of that image. I alread found that I can't just pull file through, so maybe byte array or base64 will do?
To be specific before someone downvote that question: I want to parse URL and get image to my server in any form. There is a lot similar questions, but none of them answers this one.
What I need that for? I have access to API where I also am provided with image url's, but I want them to be uploaded to my server via Background Job in Parse.com service (something like CRON job). I know how to link file with ParseObject, but can't find solution how to download image directly to ParseCloud and link it.
var Image = require("parse-image");
Parse.Cloud.job("getImagesJob", function(request, status) {
Parse.Cloud.useMasterKey();
var beerObj = Parse.Object.extend("My_class");
var query = new Parse.Query(beerObj);
query.first().then(function(objs) {
var brew = objs.get("brewery");
var bname = objs.get("beer_name");
//var fullName = brew + " " + bname;
var fullName = "Browar Name";
console.log(fullName);
return Parse.Cloud.httpRequest({
method: 'GET',
url: 'api server address',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
params: {
q : fullName,
client_id : '...',
client_secret : '...'
}
}).then(function(httpResponse) {
var json = JSON.parse(httpResponse.text);
if(json.meta.code === 200){
if(json.response.beers.count > 0){
if(json.response.beers.items[0].beer.beer_label === "/default.png"){
console.log("brak etykiety dla " + fullName);
} else {
console.log("znaleziono etykietę dla " + fullName);
Parse.Cloud.httpRequest({ //NOT REACHING
url: json.response.beers.items[0].beer.beer_label,
success: function(response) {
// The file contents are in response.buffer.
var image = new Image();
return image.setData(response.buffer, {
success: function() {
objs.set("logo", image.data());
console.log("udalo sie dolaczyc");
},
error: function(error) {
// The image data was invalid.
console.error(error);
}
})
},
error: function(error) {
// The networking request failed.
}
});
}
} else {
// daj cokolwiek żeby się nie zacięło na jednym
console.log("Brak danych dla piwa: " + fullName);
}
}
}, function(httpResponse) {
console.error('Request failed with response code ' + httpResponse.status + httpResponse.text);
});
}).then(function(obj) {
status.success("Zrobione");
}, function(error) {
status.error(error);
});
});
You can use parse-image module in Cloud Code as in their documentation
var Image = require("parse-image");
Parse.Cloud.httpRequest({
url: YOUR_URL,
success: function(response) {
// The file contents are in response.buffer.
var image = new Image();
return image.setData(response.buffer, {
success: function() {
console.log("Image is " + image.width() + "x" + image.height() + ".");
},
error: function(error) {
// The image data was invalid.
}
})
},
error: function(error) {
// The networking request failed.
}
});
With above code, you can get image data in Buffer using image.data(). To get base64 data, use image.data().toString("base64")