I need send mails with nodemailer using ajax for show a message confirmation, with out reload my page.
other problem is if using the code ajax in the frontend send two mails
============================
app.js
app.post('/enviar', function(req,res){
var name = req.body.nombre;
var mail = req.body.correo;
var messege = req.body.mensaje;
var mail_from = "servicios#fractalservicios.com";
var subject_from = "Contact web fractal nodejs";
var transporter = nodemailer.createTransport(smtpTransport({
host: "*****",
port: ***,
auth: {
user: "****",
pass: "****"
}
}));
var mailOptions = {
from: name + ' ' + mail, // sender address
to: mail_from, // list of receivers
subject: subject_from , // Subject line
html: messege // html body
};
transporter.sendMail(mailOptions,function(error,result){
if(error){
console.log(error);
console.log("salio mal");
//res.end("error");
res.render('error',{titulo: 'error al enviar menmsaje'});
}else{
console.log("Message sent: " + res.message);
console.log("correcto");
res.redirect('/');
//res.render('enviado',{titulo: 'mensaje enviado'});
}
//res.redirect('/');
});
})
build.js => Front-end
var nombre = $('#nombre').val();
var correo = $('#correo').val();
var mensaje = $('#mensaje').val();
var enviar_info = {
"nombre": nombre,
"correo": correo,
"mensaje": mensaje
};
$('.send_mail').on('click',function(){
$.ajax({
type: "POST",
url: "/enviar",
data: JSON.stringify(enviar_info),
contentType:"application/json; charset=utf-8",
dataType: 'json',
success: function(e){
alert("genial se envio tu mensaje");
}
});
});
I recently ran into the same issue and I tried the following way. It worked like a magic for me, late answer but, I am sure someone else might need it...
$(function() {
$('#contact-form').on('submit', function(event) {
event.preventDefault();
let name = $('input[name="name"]').val(),
company = $('input[name="company"]').val(),
email = $('input[name="email"]').val(),
phone = $('input[name="phone"]').val(),
message = $('textarea[name="message"]').val();
$.ajax({
url: '/',
method: "POST",
contentType: 'application/json',
data: JSON.stringify({
name,
company,
email,
phone,
message
}),
success: function(response) {
console.log(response);
},
fail: function(error) {
console.log(error);
}
});
});
});
and in server.js
app.post('/', function(req, res) {
const output = `
<p>You have a new contact request</p>
<h3>contact details</h3>
<ul>
<li>Name: ${req.body.name}</li>
<li>Company: ${req.body.company}</li>
<li>Email: ${req.body.email}</li>
<li>Phone: ${req.body.phone}</li>
</ul>
<h3>Message</h3>
<p>${req.body.message}</p>
`;
let transporter = nodemailer.createTransport({
service: 'gmail',
host: 'mail.domain.com',
port: 465,
tls: {
rejectUnauthorized: false, //NOTE: you only need to set rejectUnauthorized to false if you are running on a local server, you can remove it after testing
}
});
let mailOptions = {
from: `nodemailer contact ${req.body.email}`,
to: 'info#domain.com',
subject: 'User Form Contact',
html: output
};
transporter.sendMail(mailOptions, function(error, info) {
if (error) {
return console.log(error);
}
console.log('Message sent: %s', info.messageId);
console.log('Preview URL: %s', nodemailer.getTestMessageUrl(info));
res.send({
msg: 'Email has been sent!'
});
});
});
Related
I tried to define the url which opens when user click on notification but it continue go to url('/')
only . I send the new url with payload.data but I did not know where I can define this route in the client side so it opens when user click notification .
I use laravel-notification-channels/fcm
/**
* #param Model $notifiable
* #return FcmMessage
*/
final public function toFcm(Model $notifiable): FcmMessage
{
return FcmMessage::create()
->setData(array_merge(['type' => $this->fcmNotification->type],$this->fcmNotification->data)
)->setNotification(\NotificationChannels\Fcm\Resources\Notification::create()
->setTitle($this->fcmNotification->title)
->setBody($this->fcmNotification->body)
->setImage($this->fcmNotification->image)
) ->setAndroid(
AndroidConfig::create()
->setFcmOptions(AndroidFcmOptions::create()->setAnalyticsLabel('analytics'))
->setNotification(AndroidNotification::create()->setColor('#0A0A0A'))
)->setApns(
ApnsConfig::create()->setFcmOptions(ApnsFcmOptions::create()->setAnalyticsLabel('analytics_ios')));
}
##################### firebase-messaging-sw.js
importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-app.js');
importScripts('https://www.gstatic.com/firebasejs/7.23.0/firebase-messaging.js');
/*
firebase.initializeApp({
apiKey: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
authDomain: "xxxxxxxxxxxxxxxxxxxxxxxxxxxx",
projectId: "xxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxxx",
appId: "x",xxxxxxxxxxxxxxxxxxxxxxxxx
measurementId: "xxxxxxxxxxxxxxxx"
});
const messaging = firebase.messaging();
messaging.setBackgroundMessageHandler(function(payload) {
console.log(
"[firebase-messaging-sw.js] Received background message ",
payload,
);
/* Customize notification here */
const notificationTitle = "Background Message Title";
const notificationOptions = {
body: "Background Message body.",
icon: "/itwonders-web-logo.png",
};
return self.registration.showNotification(
notificationTitle,
notificationOptions,
);
});
##################### main layout
$(document).ready(function () {
const firebaseConfig = {
apiKey: "xxxxxxxxxxxxx",
authDomain: "x",xxxxxxxxxxxxxxxxxxxx
projectId: "xxxxxxxxxxxxxxxxxxxx",
storageBucket: "xxxxxxxxxxxxxxxxxxxx",
messagingSenderId: "xxxxxxxxxxxxxxxxxxxx",
appId: "xxxxxxxxxxxxxxxxxxxx",
measurementId: "xxxxxxxxxxxxxxxxxxxx"
};
firebase.initializeApp(firebaseConfig);
const messaging = firebase.messaging();
function initFirebaseMessagingRegistration() {
messaging
.requestPermission()
.then(function () {
return messaging.getToken()
})
.then(function (token) {
// console.log(token);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '{{ theme_route('save.fcm.token')}}',
type: 'POST',
data: {
token: token
},
dataType: 'JSON',
success: function (response) {
console.log('Token saved successfully.');
},
error: function (err) {
console.log('User Token Error' + err);
},
});
}).catch(function (err) {
console.log('User Chat Token Error' + err);
});
} initFirebaseMessagingRegistration();
messaging.onMessage(function (payload) {
const noteTitle = payload.notification.title;
console.log(payload.data);
const noteOptions = {
body: payload.notification.body,
icon:"{{website()->logo}}" ,
image: payload.notification.image,
};
new Notification(noteTitle, noteOptions);
self.addEventListener('notificationclick', function(event) {
event.notification.close();
console.log('test click event');
event.waitUntil(self.clients.openWindow('#'));
});
});
});```
I figured that I should look for " PushEvent " : I used this two listeners to handle user clicks on FCM web push notifications, in your service worker firebase-messaging-sw.js place the following
two listeners (of course change them depending on your data) :
self.addEventListener("push", (event) => {
console.log(event);
let response = event.data && event.data.text();
let title = JSON.parse(response).notification.title;
let body = JSON.parse(response).notification.body;
let icon = JSON.parse(response).notification.image;
let image = JSON.parse(response).notification.image;
event.waitUntil(
self.registration.showNotification(title, { body, icon, image, data: { url: JSON.parse(response).data.url } })
)
});
self.addEventListener('notificationclick', function(event) {
event.notification.close();
event.waitUntil(
clients.openWindow(event.notification.data.url)
);
});
I need to pass values to Controller for making a PDF.
I create a Var Filter with many data, and other variable with respective necessesary.
When I call Controller, nothing happen.
I'm NOT an expert in MVC and AJAX.
Can someone help me?
View JavaScript:
function GeneratePdfUsuarios() {
var Filter = {
Nombre: $("#F_Nombre").val(),
Cargo: $("#F_Cargo").val(),
Iniciales: $("#F_Iniciales").val(),
UserName: $("#F_Usuario").val(),
Email: $("#F_Correo").val(),
Enabled: $("#EstadosList").val(),
BirthDay_Since: $("#F_Fecha_Desde").val(),
BirthDay_to: $("#F_Fecha_Hasta").val(),
RoleName: $("#RolesList").val(),
Sucursal: $("#SucursalesList").val()
};
var Title = "Usuarios";
var Description = "Listado de usuarios del sistema";
GeneratePdfList(1, Filter, Title, Description);
}
function GeneratePdfList(pDataCoType, pFilter, pTitle, pDescription) {
var token = $('[name=__RequestVerificationToken]').val();
var _data = {
DataCoType: pDataCoType //A number for Enumeration
, Filter: pFilter //An Object with Data
, Title : pTitle // Title for PDF
, Description: pDescription // Simple Description fpr Pdf
, __RequestVerificationToken: token
};
//ShowLoading();
$.ajax({
contentType: 'application/json; charset=utf-8'
,dataType: 'json',
url: "/Utility/GeneratePdfList",
type: 'POST',
data: _data,//JSON.stringify({ '_data': _data }),
success: function (data) {
if (data['success']) {
swal("Info","Entro","success");
//window.location.href = "#Url.Action("Usuarios", "Account")";
} else {
swal({
title: "Error!",
text: data['error'] + " !",
type: "warning",
timer: 100500,
allowOutsideClick: false,
allowEscapeKey: false,
showConfirmButton: true
});
swal("Peligro","Algo Fallo en el controlador "+e.Message,"warning");
//var message = document.createTextNode(data['error']);
//var p = $('#genericError')
//p.empty();
//p.append(message);
}
},
error: function () {
swal("Peligro", "Failed " + e.Message, "warning");
}
});
}
ActionResult in Controller:
I am trying to do the following from my HTML:
var vm = new Vue({
el: '#loginContent',
data: {
main_message: 'Login',
isLoggedIn: false,
loginError: '',
loginButton:'Login'
},
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
});
Basically user presses the login button, onLogin method is called that sends a post to my API. The post is working fine and I do get the response back in the .then() promise.
But, trying to do things like this.isLoggedIn = true; does not update my DOM with what I am expecting the HTML to do when the user logs in.
Could be that I am in some sort of background thread (sorry, mobile developer here) when I get the response in the promise and it can't find the "vm" instance?
Thanks
It is probably happening because your this is not pointing to correct scope, scope of this changes inside an $.ajax call, so you just have to do something like following:
methods: {
onLogin: function() {
//this.$set(loginSubmit, 'Logging In...');
var data = {
email: $('#email').val(),
password: $('#password').val(),
};
var that = this
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then(function (response) {
if(response.error) {
console.err("There was an error " + response.error);
that.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
that.isLoggedIn = true;
} else {
that.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
}
}
I would propose another method use ES6 Arrow Functions like '=>'. It is simple and do not need extra variable.Like following:
$.ajax({
url: '/api/login',
data: data,
method: 'POST'
}).then((response) => {
if(response.error) {
console.err("There was an error " + response.error);
this.loginError = 'Error';
} else {
//$('#loginBlock').attr("hidden",true);
console.log(response.user);
if(response.user) {
this.isLoggedIn = true;
} else {
this.loginError = 'User not found';
}
}
}).catch(function (err) {
console.error(err);
});
You might want to take a look at axios. I used $.ajax and got it working, but found axios and prefer axios over the ajax library.
Looking at the Flux Documentation I can't figure out how the code to a ajax update, and a ajax fetch would fit into the dispatcher, store, component architecture.
Can anyone provide a simple, dummy example, of how an entity of data would be fetched from the server AFTER page load, and how this entity would be pushed to the server at a later date. How would the "complete" or "error" status of request be translated and treated by the views/components? How would a store wait for the ajax request to wait? :-?
Is this what you are looking for?
http://facebook.github.io/react/tips/initial-ajax.html
you can also implement a fetch in the store in order to manage the information.
Here is an example (it is a concept, not actually working code):
'use strict';
var React = require('react');
var Constants = require('constants');
var merge = require('react/lib/merge'); //This must be replaced for assign
var EventEmitter = require('events').EventEmitter;
var Dispatcher = require('dispatcher');
var CHANGE_EVENT = "change";
var data = {};
var message = "";
function _fetch () {
message = "Fetching data";
$.ajax({
type: 'GET',
url: 'Url',
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = error;
MyStore.emitChange();
}
});
};
function _post (myData) {
//Make post
$.ajax({
type: 'POST',
url: 'Url',
// post payload:
data: JSON.stringify(myData),
contentType: 'application/json',
success: function(data){
message = "";
MyStore.emitChange();
},
error: function(error){
message = "update failed";
MyStore.emitChange();
}
});
};
var MyStore = merge(EventEmitter.prototype, {
emitChange: function () {
this.emit(CHANGE_EVENT);
},
addChangeListener: function (callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function (callback) {
this.removeListener(CHANGE_EVENT, callback);
},
getData: function (){
if(!data){
_fetch();
}
return data;
},
getMessage: function (){
return message;
},
dispatcherIndex: Dispatcher.register( function(payload) {
var action = payload.action; // this is our action from handleViewAction
switch(action.actionType){
case Constants.UPDATE:
message = "updating...";
_post(payload.action.data);
break;
}
MyStore.emitChange();
return true;
})
});
module.exports = MyStore;
Then you need to subscribe your component to the store change events
var React = require('react');
var MyStore = require('my-store');
function getComments (){
return {
message: null,
data: MyStore.getData()
}
};
var AlbumComments = module.exports = React.createClass({
getInitialState: function() {
return getData();
},
componentWillMount: function(){
MyStore.addChangeListener(this._onChange);
},
componentWillUnmount: function(){
MyStore.removeChangeListener(this._onChange);
},
_onChange: function(){
var msg = MyStore.getMessage();
if (!message){
this.setState(getData());
} else {
this.setState({
message: msg,
data: null
});
}
},
render: function() {
console.log('render');
return (
<div>
{ this.state.message }
{this.state.data.map(function(item){
return <div>{ item }</div>
})}
</div>
);
}
});
I hope it is clear enough.
I'm using Facebook JavaScript SDK to log in with Facebook,
the only problem is that the JavaScript code executed after the controller.
all i want is to check if the user logged in before going to the controller.
Any help?
This is the java script Code
<script type="text/javascript">
window.fbAsyncInit = function () {
FB.init({ appId: '#Facebook.FacebookApplication.Current.AppId', channelURL: '#Request.Url.Scheme://#Request.Url.Authority#Url.Content("~/fbchannel.ashx")', cookie: true, xfbml: true, oauth: true });
FB.Event.subscribe('auth.login', function (response) { window.location.reload(); });
FB.Event.subscribe('auth.logout', function (response) { window.location.reload(); });
FB.Event.subscribe('auth.authResponseChange', function (response) {
if (response.status === 'connected') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
$.ajax({
url: '/Home/SaveAccess',
type: 'POST',
data: { A: accessToken },
success: function (data) {
},
error: function() {}
});
var field = document.createElement("input");
field.setAttribute("type", "hidden");
field.setAttribute("name", 'accessToken');
field.setAttribute("value", accessToken);
form.appendChild(field);
document.body.appendChild(form);
form.submit();
} else if (response.status === 'not_authorized') {
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
$.ajax({
url: '/Home/SaveAccess',
type: 'POST',
data: { A: accessToken },
success: function () {
}
});
} else {
}
});
(function(d){
var js, id = 'facebook-jssdk'; if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
d.getElementsByTagName('head')[0].appendChild(js);
}(document));
i save the Access Token in a session, the problem is that this code executed after the controller code.
Didn't understand exactly what you wanted. Here's a solution for what I did.
You can call FB.getLoginStatus anytime to check if the user is connected or not.
FB.getLoginStatus(function (response) {
if (response.status === 'connected') {
// user logged in and connected
}
});
You can also add this in the fbAsyncInit to check user status every time the page loads.