SharePoint 2013 Send Email from Contact Us Form via REST/JS - javascript

and thanks in advance for your answers.
I am trying to send an email from a contact us form. It appears to work but I don't receive any emails. I don't have any experience with REST and would like someone who does to see if they can spot any problems.
This is on a SharePoint 2013 Enterprise Publishing Site.
I have changed some variables and IDs for privacy purposes.
The HTML is in a custom page layout, and the JS is being called successfully in the same page layout after jQuery.
JS:
$.noConflict();
jQuery( document ).ready(function( $ ) {
// Code that uses jQuery's $ can follow here.
function submitForm() {
var toAddress = "email#domain.com";
var fromAddress ="email#domain.com";
var emSubject = "Public Contact Us Form Entry";
var lblName = "Name: ";
var valName = document.getElementById('form-name').value;
var lblEmail = "Email: ";
var valEmail = document.getElementById('form-email').value;
var lblMessage = "Message: ";
var valMessage = document.getElementById('form-message').value;
var emBody = lblName.concat(valName,lblEmail,valEmail,lblMessage,valMessage);
var data = {
properties: {
__metadata: { 'type': 'SP.Utilities.EmailProperties' },
From: fromAddress,
To: toAddress,
Body: emBody,
Subject: emSubject
}
}
var urlTemplate = _spPageContextInfo.webAbsoluteUrl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify(data),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data) {
alert('User(s) notified')
},
error: function (err) {
alert("Unable to send email -- " + JSON.stringify(err));
}
});
}
});
HTML:
<div class="label">Name</div>
<input name="Name" type="text" id="form-name" size="40">
<div class="label">Email</div>
<input name="E-mail" type="text" id="form-email" size="40">
<div class="label">Message</div>
<textarea name="Message" cols="55" rows="5" id="form-message"></textarea>
<div class="form-button">
<button onclick='submitForm()'>Submit</button>
</div>

You code has one mistake:
I changed To: toAddress to To: { 'results': [toAddress] }.
Now every thing is working fine and I am also getting the emails.
var data = {
properties: {
__metadata: { 'type': 'SP.Utilities.EmailProperties' },
From: fromAddress,
To: { 'results': [toAddress] } ,
Body: emBody,
Subject: emSubject
}
}

Related

Passing Javascript variable to AJAX call does not work

When i am passing a variable to AJAX it works if i just create a variable with some string values e.g. var userid = "test" and var passwd = "test1" but not when the variable contains var userid = form.userid.value and var passwd = form.passwrd.value. Why does form.userid.value and form.passwrd.value not work?
Here is the HTML:
<html>
<head>
<title>
Login page
</title>
<script src="login.js"></script>
<!-- jQuery -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<!-- jQuery -->
<script src="./jquery.rest.min.js"></script>
<script src="./webtoolkit.base64.js"></script>
</head>
<body>
<h1 style="font-family:Comic Sans Ms;text-align="center";font-size:20pt;
color:#00FF00;>
Simple Login Page
</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="checkLogin(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
</body>
</html>
Here is the javascript which does not work (login.js):
function checkLogin(form) {
var auth_token = localStorage.getItem("token");
//the variables which do not correctly pass through to AJAX call
var userid = form.userid.value;
var passwd = form.pswrd.value;
if(auth_token == null) {
$.ajax({
type: 'POST',
data: {
username: userid,
password: passwd
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
var tok = res.token
localStorage.setItem("token", JSON.stringify(tok));
}});
} else {
$.ajax({
type: 'POST',
headers: {
'Authorization':'token ' + JSON.parse(auth_token)
},
data: {
quote_text: "Test Javascript with variable token pt 2",
tags: '["test", "javascript"]'
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
}
});
};
};
However this will work where i have hard coded the username and password (login.js):
function checkLogin(form) {
var auth_token = localStorage.getItem("token");
//hard coded variable content which works.
var userid = "test";
var passwd = "test1";
if(auth_token == null) {
$.ajax({
type: 'POST',
data: {
username: userid,
password: passwd
},
url: 'http://127.0.0.1:8000/api/v1/api-token-auth/',
success: function(res){
var tok = res.token
localStorage.setItem("token", JSON.stringify(tok));
}});
} else {
$.ajax({
type: 'POST',
headers: {
'Authorization':'token ' + JSON.parse(auth_token)
},
data: {
quote_text: "Test Javascript with variable token pt 2",
tags: '["test", "javascript"]'
},
url: 'http://127.0.0.1:8000/api/v1/test/',
success: function(res){
console.log(res) //answer of api call.
}
});
};
};
Closed and reopened browser. No idea why that was necessary.

SharePoint send email with javascript on add list item

I like to send an email to the administrator when a user adds a item to my List. I already changed the NewForm for the list and execute the add item with:
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', retrieveListItems);
Now in my SharePoint the email notification on Lists has been disabled by the company. So I'd like some code to send an email automatically after the user added an item.
I already have the username of the person who added the item.
var loginName = "";
var userid = _spPageContextInfo.userId;
GetCurrentUser();
function GetCurrentUser() {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
The email has to be send to an address of the companies outlook server. An SMTP can be used.
Marco
Here is a little code snippet to send email using javascript.
function getUserEmail(){
$.ajax({
url:spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid("+_spPageContextInfo.userId+")?$select=Email",
headers:{"Accept": "application/json;odata=verbose","content-type": "application/json;odata=verbose"},
success:function(result){
var email = result.d.Email;
sendEmail("xxxx#email.com", email, "body", "subject");
}
});
}
function sendEmail(from, to, body, subject) {
var siteurl = _spPageContextInfo.webServerRelativeUrl;
var urlTemplate = siteurl + "/_api/SP.Utilities.Utility.SendEmail";
$.ajax({
contentType: 'application/json',
url: urlTemplate,
type: "POST",
data: JSON.stringify({
'properties': {
'__metadata': {
'type': 'SP.Utilities.EmailProperties'
},
'From': from,
'To': {
'results': [to]
},
'Body': body,
'Subject': subject
}
}),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log(data);
},
error: function (err) {
console.error(err);
}
});
}
But it also depends on your scenario. Can you give us more details about:
I already changed the NewForm for the list and execute the add item with:
How did you proceed?
Are you working on on-premise or online instance?
It seems that it was still possible to set an alert on a list when an item was added. So that solved my problem.

How to call method from CS page using AJAX?

I want to call the method which is in CS page using AJAX.
Here is my design code:
<!-- Name -->
<input type="text" name="name" id="name" required="required" class="form" placeholder="Name" />
<!-- Email -->
<input type="email" name="mail" id="mail" required="required" class="form" placeholder="Email" />
<!-- Subject -->
<input type="text" name="subject" id="subject" required="required" class="form" placeholder="Subject" />
<!-- Message -->
<textarea name="message" id="message" class="form textarea" placeholder="Message"></textarea>
<!-- Send Button -->
<button type="button" id="submit" name="submit" class="form-btn semibold">Send Message</button>
Here is the ajax
$(document).on("click", "#submit", function (e) {
$.ajax({
type: "POST",
url: "OakscrollWebService.cs/SendMail",
dataType: "json",
data: JSON.stringify({ name: $('#name').val(), email: $('#mail').val(), subject: $('#subject').val(), message: $('#message').val() }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
failure: function (data) {
alert("something went wrong");
//console.log(msg);
}
});
});
Now, I add the asmx page (web service). In that I have given the reference call to the CS file which is in App_Code folder, here is the code.
<%# WebService Language="C#" CodeBehind="~/App_Code/OakscrollWebService.cs" Class="OakscrollWebService" %>
Here the cs file from where I want to call the SendMail method using ajax (which code I shown you previously) and here is the method code in cs file
[WebMethod]
public static void SendMail(string name, string email, string subject, string message)
{
//Thread.Sleep(10000);
// Gmail Address from where you send the mail
var fromAddress = "mextra03#gmail.com";
// any address where the email will be sending
var toAddress = email.Trim();
//Password of your gmail address
const string fromPassword = "*********";
// Passing the values and make a email formate to display
string sub = subject.Trim();
string body = "From: " + name.Trim() + "\n";
body += "Email: " + email.Trim() + "\n";
body += "Subject: " + subject.Trim() + "\n";
body += "Message: \n" + message.Trim() + "\n";
// smtp settings
var smtp = new System.Net.Mail.SmtpClient();
{
smtp.Host = "smtp.gmail.com";
smtp.Port = 587;
smtp.EnableSsl = true;
smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;
smtp.Credentials = new NetworkCredential(fromAddress, fromPassword);
smtp.Timeout = 20000;
}
// Passing values to smtp object
smtp.Send(fromAddress, toAddress, sub, body);
}
This is the content I used to call the sendmail method by ajax. But facing issues like "403 forbidden" and "500 server not found" and can't call the sendmail method using AJAX.
Hi I think you need to change your url to have the file extension .asmx instead of .cs (change the line url: "OakscrollWebService.cs/SendMail", to url: "OakscrollWebService.asmx/SendMail",) because when I tested it I was getting a 404 error meaning the page was not found. You could also create a variable to check that your JSON is correct using JSONLint.
$(document).on("click", "#submit", function (e) {
var data = '{"name":"' + $('#name').val() + '", "email":"' + $('#mail').val() + '", "subject":"' + $('#subject').val() + '", "message":"' + $('#message').val() + '"}'; //Optional to check your JSON
$.ajax({
type: "POST",
url: "OakscrollWebService.asmx/SendMail",
dataType: "json",
data: JSON.stringify({ name: $('#name').val(), email: $('#mail').val(), subject: $('#subject').val(), message: $('#message').val() }),
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
failure: function (data) {
alert("something went wrong");
//console.log(msg);
}
});
});
});
Good luck!

Uable to send POST data to JSON file via JQuery/AJAX, Why?

I am learning to process JQuery/Ajax from this video on YouTube, click here..
I'm not having any problem in receiving data from order.json file but when I am trying to POST data. I am always getting Error.
The code structure with screenshot and code is below, please help me.
Project folder screenshot:
HTML code:
<div class="wrapper">
<h1>Jquery Ajax Tutorial</h1>
<h3>Coffie Orders</h3>
<ul id="orders"></ul>
<h4>Add a Coffie Order</h4>
<p> Name: <input type="text" id="name"> </p>
<p> Drink: <input type="text" id="drink"> </p>
<button id="add-order">Add!</button>
JQuery/Ajax code:
$(document).ready(function () {
var $orders = $('#orders');
var $name = $('#name');
var $drink = $('#drink');
function addOrder(order){
$orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
}
$.ajax({
type: 'GET',
url: '/api/orders.json',
success: function (orders) {
$.each(orders, function(i, orders) {
addOrder(orders);
});
},
error: function(){
alert('Error Loading Page');
}
});
$('#add-order').click(function(){
var order = {
name: $name.val(),
drink: $drink.val(),
}
$.ajax({
type: 'POST',
url: '/api/orders.json',
data: order,
success: function(newOrder) {
addOrder(newOrder);
},
error: function(){
alert('Error Adding Orders');
}
});
});
});
JSON: order.json
[{
"id": 1,
"name": "James",
"drink": "Coffiee"
}, {
"id": 2,
"name": "John",
"drink": "Latte"
}]
Client side scripting languages are used to send and retrieve data which resides on server side. We can't use them to write/edit data on server side.
For doing so, we have to use server side scripting languages like PHP or ASP or any other which you prefer.
The video you referred was an API written in Core PHP used for retrieving / writing data from / to a json file which resides on server.
In my below code i have used PHP to write submitted data to a json file via jQuery/AJAX.
Check this out..
api/process.php
if (isset($_POST['params'])) {
$params = $_POST['params'];
$oldData = file_get_contents('orders.json');
$tmp = json_decode($oldData);
array_push($tmp, $params);
$newData = json_encode($tmp);
if (is_writable('orders.json')) {
file_put_contents('orders.json', $newData);
echo $newData;
} else {
echo "file is not writable, check permissions";
}
}
index.html
<h1>Jquery Ajax Tutorial</h1>
<h3>Coffie Orders</h3>
<ul id="orders"></ul>
<h4>Add a Coffie Order</h4>
<p> Name: <input type="text" id="name"> </p>
<p> Drink: <input type="text" id="drink"> </p>
<button id="add-order">Add!</button>
<script src='js/jquery.min.js'></script>
<script src='js/main.js'></script>
js/main.js
let $orders = $('#orders');
let $name = $('#name');
let $drink = $('#drink');
function addOrder(order) {
$orders.append('<li>Name: '+ order.name +', Drink: '+ order.drink +'</li>');
}
$('#add-order').click(function(){
let order = {
name: $name.val(),
drink: $drink.val()
};
$.ajax({
type: 'POST',
url: '/api/process.php',
data: { params: order },
success: function(resp) {
addOrder(resp);
},
error: function(){
alert('Error Adding Orders');
}
});
});
$.ajax({
type: 'GET',
url: '/api/orders.json',
success: function (orders) {
$.each(orders, function(i, orders) {
addOrder(orders);
});
},
error: function(){
alert('Error Loading Page');
}
});
api/orders.json
[
{
"id": 1,
"name": "James",
"drink": "Coffiee"
},
{
"id": 2,
"name": "John",
"drink": "Latte"
}
]
Note: Here, i am not writing id to json file for new orders.
Hope, this piece of code works fine for you. :) :)

Autocomplete not working when added space

In my project, I am trying to create a autocomplete effect using the following plugin:
Devbridge jQuery Autocomplete
This plugin is working fine until I don't add space into my textbox (after adding a word). and when I just delete the entered word using backspace then the autocomplete is showing the previous list which should have shown before.
PS: Every time I am passing the full text of the text field to server through ajax call which is necessary in my application.
Here is my code:
JS Fiddle (not working because of ajax url)
JS
$(function () {
var result = $('#result');
var contents = {
value: "",
data: ""
};
/* Ajax call */
result.keydown(function (event) {
if (!event.shiftKey) {
var sugData;
var text = result.val(); //.split(" ").pop();
//console.log(text);
/* Send the data using post and put the results in a div */
$.ajax({
url: "http://localhost:9999/projects/1/autocomplete/suggestions",
type: "POST",
data: "drqlFragment=" + text, // + " ",
//data: "drqlFragment=when node_database_property ",
async: false,
cache: false,
headers: {
accept: "application/json",
contentType: "application/x-www-form-urlencoded"
},
contentType: "application/x-www-form-urlencoded",
processData: true,
success: function (data, textStatus, jqXHR) {
var resData = data.suggestions;
//console.dir(resData);
for (var i = 0; i < resData.length; i++) {
resData[i].value = resData[i].keyword;
}
sugData = resData;
//console.dir(sugData);
},
error: function (response) {
//console.dir(response);
$("#result").val('there is error while submit');
}
});
console.dir(sugData);
$('#result').autocomplete({
lookup: sugData
});
}
});
});
HTML
<form id="foo">
<textarea id="result" rows="4" cols="50"></textarea>
<input type="submit" value="Send" />
</form>
Sorry, I can't provide you the json data because it is being modified by the server whenever I press a key. (So, actually it is an object variable returning by the server on ajax call).

Categories

Resources