phonegap submit form, how to send to my email - forms

I am building simple phonegap android app.
i make simple html form with few input fields (Name, Last name, Question).
I want that when user fill input fields (Name, Last name, Question) and click Submit to send to my email address. Just that.
Do you have any idea how to do that with phonegap?
Thank you

You could do it easily by using php or .net (as your selection) with AJAX Call
Just Create One HTML page which display form to User for filling up data and send it.
Here I saw you how I done with PHP (Use phpmailer. for more, visit : http://phpmailer.worxware.com/index.php?pg=examplebmail)
HTML Form
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<form action="#!" method="post">
<input type = "text" name="cname" />
<input type = "number" name="cnumber" />
<input type = "email" name="cemail" />
<input type = "submit" value="Submit" onclick="UpdateRecord()" />
</form>
<script>
function UpdateRecord()
{
// Social Links
GolbalURL = "http://www.yourserverpathtophpfile.com";
var cname = $("[name='cname']").val();
var cnumber = $("[name='cnumber']").val();
var cemail = $("[name='cemail']").val();
jQuery.ajax({
type: "POST",
url: GolbalURL+"sendemail.php",
data: "cname="+ cname+"& cnumber="+ cnumber+"& cemail="+ cemail,
dataType: "html",
cache: false,
success: function(response)
{
alert("Email Sent");
}
});
}
</script>
</body>
</html>
Sendmail.php
<?php
$cname = $_REQUEST['cname'];
$cnumber = $_REQUEST['cnumber'];
$cemail = $_REQUEST['cemail'];
require_once('class.phpmailer.php');
$mail = new PHPMailer(); // defaults to using php "mail()"
$body = "Name : ".$cname."Number : ".$cnumber."Email : ".$cemail;
$mail->SetFrom($cemail, $cname);
$address = "youremail#id.com";
$mail->AddAddress($address, "Your Name");
$mail->Subject = "Your Subject";
$mail->AltBody = "To view the message, please use an HTML compatible email viewer!"; // optional, comment out and test
$mail->MsgHTML($body);
if(!$mail->Send()) {
echo "Mailer Error: " . $mail->ErrorInfo;
} else {
echo "Message sent!";
}
?>
Do not forgot to upload your dynamic files to server and give it permissions. Or You can also call device's default mail application from code, check PHONEGAP EMAIL COMPOSER
GIT Link Of Email Compo.
https://github.com/katzer/cordova-plugin-email-composer/blob/172605ee12e58d5e5809e4e031b3b96cead143ac/README.md

You can do using Cordova EmailComposer Plugin for Android . Add this function on your submit button click. For installation follow these steps .
https://github.com/katzer/cordova-plugin-email-composer
function emailComposer(){
window.plugin.email.isServiceAvailable(
function (isAvailable) {
if(isAvailable){
window.plugin.email.open({
to: [''],
cc: [''],
bcc: [''],
subject: '',
body: ''
});
}else{
alert('Service is not available');
}
}
);
}
**JQUERY - CALL PHP SCRIPT TO POST DATA**
var ajax_call = serviceURL;
var form_data = $('#form').serialize();
$.ajax({
type: "POST",
url: ajax_call,
data: form_data,
dataType: "json",
success: function(response) {
//called when successful
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
Examples

There are plugins to compose emails, but it won't send it automatically. You really need to use a back end service to handle this for you. You can setup your own using any app language (PHP, ColdFusion, etc), or consider a service like WuFoo perhaps.

Related

Sending images with AngularJS and NodeJS

Hi I am making a service to send images with users' information. For example, name, phone number, and their images to upload.
I am planning to use ng-file-upload, one of AngularJS custom dependency. And then, I am going to use Nodemailer to send all the information and images to somewhere else.
But my question is can I send other text data along with ng-file-upload? And second is can I send images with other text data through nodemailer?
Although OP has found a solution in the end, since I had the same problem I figured I'd post the whole code here for others who might struggle with that.
So here is how I combined ng-file-upload and nodemailer to upload and send attachments by e-mail using Gmail:
HTML form:
<form name="postForm" ng-submit="postArt()">
...
<input type="file" ngf-select ng-model="picFile" name="file" ngf-max-size="20MB">
...
</form>
Controller:
app.controller('ArtCtrl', ['$scope', 'Upload', function ($scope, Upload) {
$scope.postArt = function() {
var file = $scope.picFile;
console.log(file);
file.upload = Upload.upload({
url: '/api/newart/',
data: {
username: $scope.username,
email: $scope.email,
comment: $scope.comment,
file: file
}
});
}
}]);
Server:
var nodemailer = require('nodemailer');
var multipartyMiddleware = require('connect-multiparty')();
// multiparty is required to be able to access req.body.files !
app.mailTransporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: ...
pass: ...
},
tls: { rejectUnauthorized: false } // needed or Gmail might block your mails
});
app.post('/api/newart', multipartyMiddleware,function(req,res){
console.log(req.files);
mailOptions = {
from: req.body.email,
to: ...,
subject: ...
text: ...,
attachments: [{
filename: req.files.file.name,
path: req.files.file.path // 'path' will stream from the corresponding path
}]
};
app.mailTransporter.sendMail(mailOptions, function(err) {
if (err) {
console.log(err);
res.status(500).end();
}
console.log('Mail sent successfully');
res.status(200).end()
});
});
The nodemailer examples helped me figure this out!
This works for any file type. The key aspect that some people might miss out is that you need multiparty to access the uploaded file (in req.body.files). Then the most convenient way to attach it is using the path key in the attachment object.
Definitely you can send images as attachment using nodemailer.
Try this for sending image as an attachment :
var mailOptions = {
...
html: 'Embedded image: <img src="cid:unique#kreata.ee"/>',
attachments: [{
filename: 'image.png',
path: '/path/to/file',
cid: 'unique#kreata.ee' //same cid value as in the html img src
}]
}
For more reference on sending image as attachment go through nodemailer's "using Embedded documentation".
For the first part of the question:
Yes! you can send other text data along with image using ng-file-upload. It depends how you want to do it and what you want to achieve.
For example, see the code below:
HTML Template
<form name="form">
<input type="text" ng-model="name" ng-required="true">
<input type="text" ng-model="phoneNo" ng-required="true">
<div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" ngf-resize="{width: 100, height: 100}">Select</div>
<button type="submit" ng-click="submit()">submit</button>
</form>
Controller
$scope.submit = function() {
if ($scope.form.file.$valid && $scope.file) {
$scope.upload($scope.file);
}
};
// upload on file select or drop
$scope.upload = function (file) {
Upload.upload({
url: 'upload/url',
data: {file: file, 'name': $scope.name, 'phoneNo' : $scope.phoneNo}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
Read ng-file-upload documentation completely to see understand all the things you can do along with file upload. It has many examples to make you understand everything.
I hope it helps, and answer your question.

How can i prevent User from directly accessing the HTML page

I have got a set 3 HTML Pages
I am using Apache Tomcat 7 server . I have got the following HTML pages (All are HTML pages only)
login.html
sales.html
index.html
The code for the login.html is when clicked on submit is
<input type="email" name="email" id="email" >
<input type="pin" name="email" id="pin" >
<button class="primary login-btn">Submit</button>
Once clicked on Submit button , i am calling a Jersey REST Webservce this way and will response either true OR false based on the values present in our Database
function submitLoginForm() {
var email_input = $.trim($("#email").val());
var pin_input = $.trim($("#pin").val());
var logininfo = {
'email': email_input,
'pin': pin_input
};
var login_information = JSON.stringify(logininfo);
$.ajax({
type: 'POST',
dataType: 'json',
data: login_information,
url: url + '/HEGS/orn/webchecklogin',
success: function(response) {
// if true , redirect to sales.html page
window.location = "index.html"
},
});
}
All this is working fine , my issue is , how can i stop the prevent the user from accessing the page directly
For example if he types the follwing URL
http:localhost:8080/HEGS/dealer/sales.html
You would want to redirect the url to one file, which would then load the correct file based on the criteria you set. I don't know much about Tomcat, but this article seems to explain it well under the "URL Rewriting" section.

Auto complete with multiple keywords

I want . Auto complete text box with multiple keyword. it's from database. if I use jQuery and do operation in client side mean. If the database size is huge, it leads to some issues. I need to know how this is done on the server side and get proper result.
I have already seen this topic but the operation is done on the client side. I need it from the database directly.
<html>
<head>
<title>Testing</title>
<link href="css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<style type="text/css">
.srchHilite { background: yellow; }
</style>
<script src="scripts/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
NewAuto();
});
function NewAuto() {
var availableTags = ["win the day", "win the heart of", "win the heart of someone"];
alert(availableTags); // alert = win the day,win the heart of,win the heart of someone
$("#tags").autocomplete({
source: function(requestObj, responseFunc) {
var matchArry = availableTags.slice(); // Copy the array
var srchTerms = $.trim(requestObj.term).split(/\s+/);
// For each search term, remove non-matches.
$.each(srchTerms, function(J, term) {
var regX = new RegExp(term, "i");
matchArry = $.map(matchArry, function(item) {
return regX.test(item) ? item : null;
});
});
// Return the match results.
responseFunc(matchArry);
},
open: function(event, ui) {
// This function provides no hooks to the results list, so we have to trust the selector, for now.
var resultsList = $("ul.ui-autocomplete > li.ui-menu-item > a");
var srchTerm = $.trim($("#tags").val()).split(/\s+/).join('|');
// Loop through the results list and highlight the terms.
resultsList.each(function() {
var jThis = $(this);
var regX = new RegExp('(' + srchTerm + ')', "ig");
var oldTxt = jThis.text();
jThis.html(oldTxt.replace(regX, '<span class="srchHilite">$1</span>'));
});
}
});
}
</script>
</head>
<body>
<div>
<label for="tags">
Multi-word search:
</label>
<input type="text" id="tags" />
</div>
</body>
</html>
take a look to Select2 it may help you.
Select2 is a jQuery based replacement for select boxes. It supports
searching, remote data sets, and infinite scrolling of results.
link
In your code, you have provided source as array. As you mentioned in comments, problem is how to get the data to source in jquery.
To make this work,
You need to do following
load jquery in header, which is you have already done.
Provid array,string or function for the source tag. [See api for
the source tag][1]
[1]: http://api.jqueryui.com/autocomplete/#option-source
In your serverside script, provid Jason encoded string.
If you check the API, you can see they have clear mentioned this.
Here is the jquery code
$(function() {
$( "#option_val" ).autocomplete({
dataType: "json",
source: 'search.php',
minLength: 1,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.value + " aka " + ui.item.id :
"Nothing selected, input was " + this.value );
}
});
});
</script>
Here is the php code, Sorry if you use differnt serverside script language.
<?php
// Create connection
$con=mysqli_connect("localhost","wordpress","password","wordpress");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result=mysqli_query($con,"select * from wp_users");
while($row = mysqli_fetch_array($result))
{
$results[] = array('label' => $row['user_login']);
}
echo json_encode($results);
mysqli_close($con);
?>

Two near-identical forms functioning differently

I have two nearly identical forms on two different pages which take in a user's name and email address. When I press the submit button, both of them call a validator, which works correctly, and then both are supposed to make an Ajax call and display the results. At this point, one of them makes the call successfully, and the other simply refreshes the page. I'm not sure what the difference is that causes one to work successfully and the other to fail. With the one that works, I already had this problem once with the form that works, which was caused by me generating the form through javascript. I have no idea what is causing it now. Here is the inline code for the functioning one:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<div class="response"></div>
<form id="inviteForm" >
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
var invites = <?php echo $user->getInvitesLeft(); ?>;
</script>
</form>
</div>
Response is where it displays the response from the Ajax call. I have to generate the content later on using Javascript because I take different actions depending on the value of invites. I was originally generating the whole thing, but I found that I had to have the form tags in place to prevent the refreshing problem the first time. Here is the code that generates the form the user sees:
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteForm").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
$("#inviteModal").css('display', "block");
$("#overlay").css("display", "block");
And here is the validator function:
$("#inviteForm").validate({
//Rules for invite validation
rules: {
first: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
first: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
if(data.indexOf("Thank you") >= 0 ){
$("#inviteModal .response").text(data);
invites -=1;
}
else{
$("#inviteModal .response").text(data);
}
}
}); //End ajax
} //End submitHandler
}); //End validator
As I said, this one works perfectly fine. The only difference between this one and the one that refreshes is that the non-functioning one is on a page that you don't have to be logged in to see, and takes different actions depending on whether or not a user is logged in. Here is the inline code:
<!--// MODAL: INVITE //-->
<div id="inviteModal" class="modal" style="display: none">
<div class="response"></div>
<form id="inviteForm" >
<script type="text/javascript" src="/includes/js/jquery-1.7.2.min.js"></script>
<?php
if(!$user || $user == null){ //No user logged in, display invite request form instead
$loggedin = false;
}
else{ //Allow user to invite friends
$loggedin = true;
}
?>
</form>
Here is the generation code, almost identical except for one extra if layer:
if(!loggedin){
$("#inviteForm").html("<h2>Please enter the specified information to request an invitation. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
else{
invites = <?php echo $user->getInvitesLeft(); ?>;
if(invites < 1){
$("#inviteModal").html("You have no invites left. You can get more by increasing your score.");
}
else{
$("#inviteForm").html("<h2>Please enter the specified information for the friend you wish to invite. </h2>"+
"<p>First: <input type=\"text\" name=\"first\"></p>"+
"<p>Last: <input type=\"text\" name=\"last\"></p>"+
"<p>Email: <input type=\"text\" name=\"email\"></p>"+
"<p><input type=\"submit\" name=\"submit\" value=\"Invite\"></p>");
}
}
$("#inviteModal").css('display', "block");
$("#overlay").css("display", "block");
And here is the validator:
$("#inviteForm").validate({
//Rules for invite validation
rules: {
first: "required",
email: {
required: true,
email: true
}
},
//Messages to print if validation fails
messages: {
first: "Please provide your friend's name.",
email: "We cannot contact your friend without a valid email address.",
},
//What to do when validation succeeds
submitHandler: function(form) {
//Form is valid, make Ajax call
if(loggedIn){ //They are inviting a friend
$.ajax({
type: "POST",
url: '/invite/process',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
if(data.indexOf("Thank you") >= 0 ){
$("#inviteModal .response").text(data);
invites -=1;
//$("#overlay").css("display", "none");
//$("#inviteModal").fadeOut(5000);
}
else{
$("#inviteModal .response").text(data);
}
return false;
}
}); //End Ajax
}
else{ //They are requesting an invite for theirself
$.ajax({
type: "POST",
url: '/invite/request',
data: $("#inviteForm").serialize(),
datatype: "html",
success: function(data, textStatus ,XHR) {
//alert(data);
$("#inviteModal .response").text(data);
return false;
}
}); //End ajax
}
return false;
} //End submitHandler
}); //End validate
Again almost identical except for one extra layer of if. So why would the bottom one refresh the page instead of making the Ajax call while the first one works perfectly fine?
how about commenting out those return false statement in the ajax success callback functions for the second one?

JSON object parsing error using jQuery Form Plugin

Environment: JQuery Form Plugin, jQuery 1.7.1, Zend Framework 1.11.11.
Cannot figure out why jQuery won't parse my json object if I specify an url other than a php file.
The form is as follows:
<form id="imageform" enctype="multipart/form-data">
Upload your image <input type="file" name="photoimg" id="photoimg" />
<input type="submit" id ="button" value="Send" />
</form>
The javascript triggering the ajax request is:
<script type="text/javascript" >
$(document).ready(function() {
var options = {
type: "POST",
url: "<?php $this->baseURL();?>/contact/upload",
dataType: 'json',
success: function(result) {
console.log(result);
},
error: function(ob,errStr) {
console.log(ob);
alert('There was an error processing your request. Please try again. '+errStr);
}
};
$("#imageform").ajaxForm(options);
});
</script>
The code in my zend controller is:
class ContactController extends BaseController {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
}
public function uploadAction() {
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = $_FILES['photoimg']['tmp_name'];
$im = new imagick($image);
$im->pingImage($image);
$im->readImage($image);
$im->thumbnailImage(75, null);
$im->writeImage('userImages/test/test_thumb.jpg');
$im->destroy();
echo json_encode(array("status" => "success", "message" => "posted successfully"));
}
else
echo json_encode(array("status" => "fail", "message" => "not posted successfully"));
}
}
When I create an upload.php file with the above code, and modify the url from the ajax request to
url: "upload.php",
i don't run into that parsing error, and the json object is properly returned. Any help to figure out what I'm doing wrong would be greatly appreciated! Thanks.
You need either to disable layouts, or using an action helper such as ContextSwitch or AjaxContext (even better).
First option:
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
And for the second option, using AjaxContext, you should add in your _init() method:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
->initContext();
This will disable automatically disable layouts and send a json header response.
So, instead of your two json_encode lines, you should write:
$this->status = "success";
$this->message = "posted successfully";
and
$this->status = "fail";
$this->message = "not posted successfully";
In order to set what to send back to the client, you simply have to assign whatever content you want into view variables, and these variables will be automatically convert to json (through Zend_Json).
Also, in order to tell your controller which action should be triggered, you need to add /format/json at the end of your URL in your jQuery script as follow:
url: "<?php $this->baseURL();?>/contact/upload/format/json",
More information about AjaxContext in the manual.
Is the Content-type header being properly set as "application/json" when returning your JSON?