Calling Web Service .asmx from JavaScript using AJAX - javascript

I have implemented a pop-up in an asp.net web app which allows the user to select something and an email template is generated. After completing all the required fields, the user sends the email by the click of a button.
This button calls a JavaScript function where I gather all the user input data like from, to, subject, body and want to send this data to a web service I have created which will send the mail.
I didn't want to use mailto, so I went with web service.
The problem is that I can't send the data:
$.ajax({
type: 'POST',
url: "Services/MailService.asmx/SendMail",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: { 'loginName': "'" + loginName + "'", 'fromAddress': "'" + fromAddress + "'", 'toAddress': "'" + toAddress + "'", 'mailSubject': "'" + mailSubject + "'", 'mailBody': "'" + mailBody + "'"},
success: function ()
{
alert("The email was sent successfully!");
},
error: function(data)
{
alert("An error occurred while trying to send the email. " + data.responseText);
}
});
I know that what I inserted in the data property is wrong. I have tried the following, (one at a time):
data: JSON.stringify({ 'loginName': loginName, 'fromAddress': fromAddress, 'toAddress': toAddress, 'mailSubject': mailSubject, 'mailBody': mailBody }),
data: { 'loginName': loginName, 'fromAddress': fromAddress, 'toAddress': toAddress, 'mailSubject': mailSubject, 'mailBody': mailBody },
data: { loginName: loginName, fromAddress: fromAddress, toAddress: toAddress, mailSubject: mailSubject, mailBody: mailBody },
data: "{ 'loginName': '" + loginName + "', 'fromAddress': '" + fromAddress + "', 'toAddress': '" + toAddress + "', 'maliSubject': '" + mailSubject + "', 'mailBody': '" + mailBody + "' }",
All these options give me the following errors:
An error occurred while trying to send the email. {"Message":"Invalid web service call, missing value for parameter: \u0027mailBbody\u0027.","StackTrace":" at System.Web.Script.Services.WebServiceMethodData.CallMethod(Object target, IDictionary`2 parameters)\r\n at System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext context, WebServiceMethodData methodData, IDictionary`2 rawParams)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.InvalidOperationException"}
or
An error occurred while trying to send the email. {"Message":"Invalid JSON primitive: loginName.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
I don't understand what I'm doing wrong.
The web service looks like this:
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public void SendMail(string loginName, string fromAddress, string toAddress, string mailSubject, string mailBody)
{
MailMessage mailMsg = new MailMessage(fromAddress, toAddress);
mailMsg.Subject = mailSubject;
mailMsg.Body = mailBody;
string pathToCreate = "~/Upload/" + loginName + "/";
if (Directory.Exists(Server.MapPath(pathToCreate)))
{
if (Directory.GetFiles(Server.MapPath(pathToCreate)).Length > 0)
{
string[] attachedFiles = Directory.GetFiles(Server.MapPath(pathToCreate));
foreach (string a in attachedFiles)
{
Attachment data = new Attachment(a);
mailMsg.Attachments.Add(data);
}
}
}
SmtpClient smtp = new SmtpClient();
smtp.Send(mailMsg);
}
}
What could I do to solve this issue?

I was able to successfully send the data by using:
data: '{loginName:' + JSON.stringify(loginName) + ', fromAddress:' + JSON.stringify(fromAddress) + ', toAddress:' + JSON.stringify(toAddress) + ', mailSubject:' + JSON.stringify(mailSubject) + ', mailBody:' + JSON.stringify(mailBody) + '}',
I don't know if this is the right way but it's working.

Related

Sending Large data from View to Controller in MVC

I am getting table records, I need to send it to Controller so that I can send email. When I tried with following code, it's throwing error
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "GET",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
data: "{'emailList': '" + JSON.stringify(emailList) + "', body' : '" + body + "' }",
success: function (json) {
alert(json);
}
});
Error as : HTTP Error 404.15 - Not Found The request filtering module
is configured to deny a request where the query string is too long.
Most likely causes: Request filtering is configured on the Web server
to deny the request because the query string is too long.
I have tried to add following code, still same error
var formData = new FormData();
var objArr = [];
objArr.push({ "emIl": emailList, });
//JSON obj
formData.append('objArr', JSON.stringify(objArr))
body = 'Hi Team'
console.log('emIl ' + emailList);
var baseUrl = ".";
$.ajax({
type: "POST",
url: baseUrl + "/Dashboard/GetFinanceSendMail",
processData: false,
contentType: false,
data: formData,
Here is Controller Code
[HttpGet]
public JsonResult GetFinanceSendMail(string emailList, string body)
{
List<string> emails = emailList.Split(',').ToList();
// Send Email add optiona arg to the method
_openPobl.TriggerFinanceEmail(body, emails);
return Json(emails, JsonRequestBehavior.AllowGet);
}
fix the action, remove [get]
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(string emailList, string body)
and ajax
var emailList = '';
$('.checkBoxClass').each(function () {
if ($(this).is(':checked')) {
emailList += $(this).val() + ',';
}
});
var body = 'Hi Team';
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: {emailList: emailList, body : body },
success: function (json) {
alert(json);
}
});
but if you want to use post much more reliable to create a viewmodel class
public class ViewModel
{
public string EmailList {get;set;}
public string Body {get;set;}
}
action
Route[("~/Dashboard/GetFinanceSendMail")]
public JsonResult GetFinanceSendMail(ViewModel model)
.....
and ajax
$.ajax({
type: "POST",
url: "/Dashboard/GetFinanceSendMail",
data: { model: {emailList: emailList, body : body } },
success: function (json) {
alert(json);
}
});

C# Leaflet how do i properly post data from view to controller using ajax?

currently i keep getting the alert request failed whenever i try to pass back data from view to controller.
leafletLats and leafletLngs are an array, but im not sure of the datatype. They are derived from coord which is of type LatLng[].
may i know what is causing the Post method to not pass through? is it the problems in the controller?
in View
routeControl.on('routeselected', function (e) {
var coord = e.route.coordinates;
var name = e.route.name;
var leafletLats = coord.map(function(point) {
return [point.lat];
});
var leafletLngs = coord.map(function(point) {
return [point.lng];
});
alert('Array size = ' + coord.length + '\nCoordinates: \n' + leafletLats);
alert('Array size = ' + coord.length + '\nCoordinates: \n' + leafletLngs);
//alert('Array size = ' + coord.length + '\nCoordinates: \n' + coord.join('\n'));
$.ajax({
type: 'Post',
url: '/Map/GetRouteCoordinates',
data: JSON.stringify(leafletLats),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(`Request passed!`);
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert(`Request failed!`);
}
});
in controller
[HttpPost]
public ActionResult GetRouteCoordinates(MyModel test)
{
//do something with the result
Debug.WriteLine("data passed back");
return View();
}
public class MyModel
{
public List<MyModel_Value> latList { get; set; }
}
public class MyModel_Value
{
public double lat { get; set; }
}
did some modification and changing the data to data: JSON.stringify({ arr: stringifiedArr }) works for me

i can't pass javascript variable to servlet without submitting a form

function gameLogin() {
var usernameToPass;
console.log('Fetching information from facebool.... ');
FB.api('/me', function (response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
//pass user name to Servlet
usernameToPass = response.name;
pass(usernameToPass);
});
}
function pass(name) {
$.ajax({
url: 'GameManagerServlet',
data: {
username: name
},
type: 'GET',
success: function (name) {
console.log(name);
}
});
}
so basically i have this script in my jsp using Facebook login api got username then stored in a variable, and trying to pass to my servlet by another function, because my servlet needs to receive the username when the page is loaded, i've tried some ways like by ajax, but the server side when i use request.getParameter("username"); but always got null. Could you help me to fix this problem? Thanks a lot!
You should use callback function like below.
var usernameToPass;
function gameLogin() {
console.log('Fetching information from facebool.... ');
FB.api('/me', function (response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
//pass user name to Servlet
usernameToPass = response.name;
pass(callback){
callback(usernameToPass);
};
}
function pass(function(name) {
$.ajax({
url: 'GameManagerServlet',
data: {
username: name
},
type: 'GET',
success: function (successname) {
console.log(successname);
}
});
})

Send attachment via SendGrid using Parse Cloud Code Module

I am trying to send an attachment to my email using SendGrid, in this case the attachment is of type NSData. Is there a way to send an attachment using SendGrid without having an URL or that image saved in Parse? I want to go from phone straight to email w/ attachment.
Currently the email is sending successfully, just do not have an image/attachment. Thanks in advance!
Parse.Cloud.define("sendBookRequestEmail", function(request, response) {
var Buffer = require('buffer').Buffer;
var buffer1 = new Buffer(request.params.image);
var b3 = buffer1.toString('base64');
var SendGrid = require("sendgrid");
SendGrid.initialize("username", "password");
SendGrid.sendEmail({
to: "email",
from: request.params.email,
subject: "Requesting book",
text: "Title: " + request.params.title + "\r\n" + "Author: " + request.params.author + "\r\n" + "ISBN: " + request.params.isbn + "\r\n" + "I want to: " + request.params.bookrequest + "\r\n" + "Notes: " + request.params.notes,
attachments: [request.params.image]
}, {
success: function(httpResponse) {
response.success("success");
console.log(httpResponse);
},
error: function(httpResponse) {
console.error(httpResponse);
}
});
});
The object that you were passing to the sendMail call does not have the right structure. Try something like this:
sendEmail({
to: "email",
from: request.params.email,
subject: "subject",
text: "text",
attachments: [{
content: b3, // 'Some base 64 encoded attachment content'
filename: 'some-attachment.txt',
type: 'plain/text',
disposition: 'attachment',
contentId: 'mytext'
}
],
});

Facebook story posting issue

I am setting up for posting story on facebook but I am getting following alert:
You, or this app's Open Graph Test User, must have published this action at least once.
I am getting id in the response but when I am clicking on that I am redirecting to "Page not found".
Here is my code :
FB.api(
'me/objects/appnamespace:objecttype',
'post',
{
object :{
app_id: myappId,
objectype: myurl,
title: "Sample Organization",
image: mylogo,
description: ""
}
},
function(response) {
if (!response) {
alert('Error occurred.');
} else if (response.error) {
document.getElementById('result').innerHTML =
'Error: ' + response.error.message;
} else {
document.getElementById('result').innerHTML =
'<a href=\"https://www.facebook.com/me/activity/' +
response.id + '\">' +
'Story created. ID is ' +
response.id + '</a>';
}
}
);

Categories

Resources