How to Send an Email from client side JS using my backend - javascript

I have class method for sending Email
public static bool SendEmail(string msg)
{
var sent = false;
try
{
var fromEmail = ConfigurationManager.AppSettings["FromEmail"];
var toEmail = ConfigurationManager.AppSettings["ToEmail"];
var emailsubject=ConfigurationManager.AppSettings["ErrorTitle"];
var emailService = new EmailServiceClient();
sent = emailService.SendEmail(fromEmail, toEmail, emailsubject, msg);
}
catch (Exception ex)
{
LogException(ex);
}
return sent;
}
Here is my Javascript function on on button Click() event
function sendMail() {
var e= "Hi";
$.ajax({
url: '/Home/SendEmail',
method: "POST",
success:function (result) {
alert('Email Sent');
},
error: function (result) {
alert('Email Does Not Sent');
}
});
}
This JS code is opening an outlook email of my system (open my mail client).
I want to send the email on button click from my webpage directly via EmailService (not by SMTP because I have WCF created for EmailService), I am not understanding flow that how can I achieve it.
Need to know changes in JS code and Any documentation or example for reference would be helpful.
Thank You

It worked with this:
public ActionResult SendEmail(string msg)
{
var sent = false;
try
{
var emailClient = new EmailServiceReference.EmailServiceClient();
sent = emailClient.SendEmail(fromEmail, toEmail, emailsubject, msg); /// All parameters of SendEmail method defined
}
catch (Exception ex)
{
Console.WriteLine("Exception occured while sending Email " + ex.Message);
}
return Json(sent, JsonRequestBehavior.AllowGet);
}

I recommend you to read about jquery and how to use the jquery ajax , the code below is a good point to start, you did not mention if you are using MVC or API or WebForms, so code below is a bit generic. (this is a complete guide that you can follow)
function SendMail(){
var msg = 'your msg';
$.ajax({
url: 'YOURURLHERE/SendEmail?msg=' + msg,
method: "GET",
}).done(function (result) {
alert('Email Sent');
});
});
}

Related

Error part in jQuery is missing

I build following JavaScript part and everything works fine. But I'm not sure if the code is completely right. Because in my script I only use success: function() but I don't use error. Is it a MUST to have error in a jQuery AJAX call?
Currently I'm catching the errors in my php controller function and echo them in the success part.
$(document)
.ready(function() {
var groupName = '';
var groupid = '';
$(".grp")
.click(function() {
$('.text-danger')
.html('');
groupName = $(this)
.data('groupname');
groupid = $(this)
.attr('id');
$('.text')
.html(groupName);
$('#dataModal')
.modal({
show: true
});
});
jQuery(".grpval")
.click(function(e) {
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
, });
jQuery.ajax({
url: "{{ route('request_group') }}"
, method: 'post'
, data: {
'Gruppe': groupid
}
, success: function(data) {
if (typeof data.successsuccess != 'undefined') {
jQuery('.alert-success')
.show();
jQuery('.alert-success')
.html('<p>' + data.successsuccess + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else if (typeof data.successdberror != 'undefined') {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + data.successdberror + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else {
jQuery.each(data.errors, function(key, value) {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + value + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
});
}
}
});
});
});
EDIT: Here is the function from my Controller:
public function setGroupRequest(Request $request){
$validator = \Validator::make($request->all(), [
'Gruppe' => [new ValidRequest]
]);
$groupid = $request->input('Gruppe');
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
try{
$groups_request = new GroupRequest();
$groups_request->idgroups = $groupid;
$groups_request->iduser = Auth::id();
$groups_request->request_active = 1;
$groups_request->save();
$db_status = 'success';
}catch(\Exception $e){
$db_status = 'error';
}
if($db_status == 'success'){
return response()->json(['successsuccess'=>'Record is successfully added']);
}else{
return response()->json(['successdberror'=>'DB Error! Values could not be saved.']);
}
}
Error handling is required as you never know different things on the internet might result in failure of request for example,
Network failure.
Lost database connection
Unauthorised access/access denied
Any variable being not defined
There is nothing wrong in your way of writing PHP error in success, but writing it in $ajax error callback function is preferred as it helps in separating error & success logic.
In fact you can add a jquery error callback function as well to your $ajax which will handle all the errors originating from above mentioned internet failures.
You can add error function, which will receive any type of error coming from backend.
jQuery.ajax({
url: "{{ route('request_group') }}",
method: 'data: {
'Gruppe': groupid
},
success: function(data) {
//code here
},
error: function (jqXHR, exception) {
//error handling
}
})
In your PHP file,
if ($query) {
echo "success"; //whatever you want to show on success.
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}
This way you can catch PHP error as well as any internet Network errors in your jquery ajax.

Access the session variables from controller inside ajax call

I have certain fields getting filled in my controller.
public string AjaxLogin()
{
//some code to check admin or not
Session["UserName"] = "Smith";
if(type="Admin")
{
Session["UserRole"] = 1;
}
Session["EmployeeID"] = 101;
}
I have an ajax call to this controller like below and if it is success, I need to access these session variables inside success to check the user role.
$.ajax(
{
url: GLOBAL.GetAppPath() + 'Home/AjaxLogin',
data: data,
type: 'POST',
error: function (xhr, status, error) {
console.log(error);
},
success: function (result, status, xhr) {
if (result == 'OK')
{
var UserVal = '#Session["UserRole"]';
alert(UserVal);
if(UserVal ==1)
{
var baseUrl ="#Url.Action("Admin","AdminPage")";
window.location.href = baseUrl;
}
else
{
var baseUrl ="#Url.Action("Admin","RegularPage")";
window.location.href = baseUrl;
}
}
else {
$('#msgError').html('Error: ' + result);
$('#msgError').css('display', 'block');
}
},
});
But I cannot access this variable in this call. I want to check the user role variable and give url actions accordingly.
If you want to redirect to a controller in your project you can use the Url helper for you
Sample:
return JavaScript( "window.location = '" + Url.Action("Edit","Dispatch") + "'" );
P.S: I couldn't comment since it asks for 50 reputation that's why I'm commenting it over here.

Link not opening after streaming data of the document down

I think I am missing some code on the JavaScript side. I am downloading the documents for each request. When the user clicks on the link, I go get the document data and stream it down. I see on Fiddler that the data is coming down, but the .txt document link is not opening.
[HttpGet]
public HttpResponseMessage GetDataFiles(Int64 Id)
{
var results = context.PT_MVC_RequestFile.Where(x => x.RowId == Id).FirstOrDefault();
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
try
{
if (results != null)
{
response.Headers.AcceptRanges.Add("bytes");
response.StatusCode = HttpStatusCode.OK;
response.Content = new ByteArrayContent(results.Data);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = results.FileName;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
response.Content.Headers.ContentLength = results.Data.Length;
}
}
catch (EntityException ex)
{
throw new EntityException("GetFiles Failed" + ex.Message);
}
return response;
}
Firstly, I downloaded all the documents for that request, and if the user clicks on the file, I call the download stream action.
$.ajax({
url: url,
type: 'GET',
// data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
if (data != "") {
$("#fileLength").val(data.length);
// alert(data.length);
$.each(data, function (i, item) {
var newDiv = $(document.createElement('div')).attr("id", 'file' + i);
newDiv.html("<input id=\"cb" + i + "\" type=\"checkbox\"> <a href=\"#\" onclick=\"GetData('" + item.RowId + "','" + item.mineType + "')\" >" + item.FileName + "</a>");
newDiv.appendTo("#fileRows");
});
} else {
}
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
I think I am missing something after success though. Somehow it downloads the data, but the link does not open. Could it be the content type is not set, or that it thinks it is JSON data? Help with some ideas please.
Here is the link:
function GetData(rowId,mineType) {
// alert(mineType);
var url = "api/MyItemsApi/GetDataFiles/" + rowId;
$.ajax({
url: url,
type: 'GET',
//data: JSON.stringify(model, null),
contentType: "application/json",
success: function (data) {
},
error: function (xhr, ajaxOptions, thrownError) {
}
});
}
You can't easily download a file through an Ajax request. I recommend to post the data to a blank page from a form, instead of the Ajax (you can populate that form and post it via jQuery if you need to). If you're interested, I could guide you through it, just let me know.
If you still want to download from Ajax, I suggest you refer to this post.

Ajax request not posting ID to controller

I have wrote an AJAX post request to my deletewidget controller, it is posting the request token fine, however it does not seem to pass the widgetID to the controller. I have stepped through the javascript code and it assigns the ID to the variable widgetID fine, and have also put a breakpoint in my controller but it says null.
$(document).ready(function () {
$('#columns').on('click', '.glyphicon.glyphicon-trash', function (event) {
var panel = this;
//get id here
//toggle the modal
$('#deleteWidgetModal').modal('show');
var widgetID = $(this).closest('.panel.panel-default').attr('data-widgetid');
document.getElementById('delete-widget').onclick = function (event) {
event.stopPropagation();
//anti forgery token
//get the form
var form = $('#__AjaxAntiForgeryForm');
//from the form get the antiforgerytoken
var token = $('input[name="__RequestVerificationToken"]', form).val();
var URL = '/Dashboard/DeleteWidgetConfirmed';
//we make an ajax call to the controller on click
//because the controller has a AntiForgeryToken attribute
//we need to get the token from the form and pass it with the ajax call.
$.ajax({
url: URL,
data: {
__RequestVerificationToken: token,
id: widgetID
},
type: 'POST',
success: function(result){
var parentElement = $(panel).closest(".col-md-4.column");
var targetElement = $(panel).closest(".panel.panel-default");
targetElement.remove();
//parentElement.addClass("expand-panel");
checkEmptyPanelContainers();
$('#deleteWidgetModal').modal('hide');
},
error: function (jqXHR, textStatus, errorThrown) {
alert("An error has occurred please contact admin");
}
})
}
return false;
})
});
and here is my controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteWidgetConfirmed(int? id)
{
if(id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
WidgetModel widgetModel = db.widgets.Find(id);
db.widgets.Remove(widgetModel);
db.SaveChanges();
return new EmptyResult();
}
It seemed to be executing the ajax code twice, I moved my return false up one level and it solved the problem

Redirect from javascript in asp razer view

I have following Jquery code the code is sending data to controller fine and now I want to redirect from here after success how can I achieve this
$('#reply_admin').click(function () {
var recipName = $('.input_eply').val();
var id =#Model.id
$.post('/Admincontact/Replt/' + id,
{ reply: recipName },
function (data) {
$('#reply').append(data);
window.location.href = '#Url.Action("Index", "Admincontact")';
});
});
and my controller is
[HttpPost]
public ActionResult Replt(string reply,string id)
{
EmailManager.admin_reply(db.contactUs.Find(Convert.ToInt32(id)).Email, reply);
return new EmptyResult();
}
Whats the meaning of
$('#reply').append(data);
If you are returning EmptyResult()
Try only
function (data) {
window.location.href = '#Url.Action("Index", "Admincontact")';
}

Categories

Resources