Sending a file from form to email - javascript

I am trying to figure out how to send a file that containts things like images to text files, etx from a form submission through ajax to my php file to send into an email. I am trying to format it the way I have my other data in ajax and php email, but I can tell the form stops right away in my ajax. It doesn't even send through to my php, but I am not sure if I have the email part right either.
This is what I tried so far. I tried to delete as much obsolete code as possible, but still include enough to give a good feeling for what I am trying to do.
How can I make this file attach/send into an email from a form through AJAX to my php email
<form action="" autocomplete="on" method="POST" id="project-information-form" enctype="multipart/form-data">
<input type="text" class="input-borderless" id="project-name" name="name" placeholder="Your Name">
<input type="email" class="input-borderless" id="project-email" name="email" placeholder="Email Address">
<input type="number" class="input-borderless" id="project-number" name="phone" placeholder="Phone Number">
<input type="file" name="file" id="file" class="inputfile" data-multiple-caption="{count} files selected" multiple>
<label for="file"><span id="file-upload-image"><img src="/icons/white-upload.png" height="25px" width="25px"></span>File Upload</label>
<input type="submit" id="submit-project" class="submit-project-button" value="Send Project Inquiry">
</form>
AJAX
$("#submit-project").on("click", function(event) {
// event.preventDefault();
var project_name = $("#project-name").val();
var project_email = $("#project-email").val();
var project_number = $("#project-number").val();
var uploaded_file = $("#file").val();
submitHandler: function(form) {
console.log(form);
$.ajax({
url: "email-project.php",
type: "POST",
data: {
"project_name": project_name,
"project_email": project_email,
"project_number": project_number,
"file": project_file
},
success: function(data) {
//console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to send email!");
alert(data);
} else {
}
},
PHP Page for email
ini_set('display_errors', 1);
error_reporting(E_ALL);
$project_name = $_POST['project_name'];
$project_email = $_POST['project_email'];
$project_number = $_POST['project_number'];
$project_file = $_POST['file'];
$to = '';
$subject = '';
$message = '
<html>
<head>
<title>Project Inquiry Form Sent</title>
</head>
<body>
<p>There has been a Project submitted. Here are the details:</p><br>
<p>Name: '. $project_name .'</p>
<p>Email: '. $project_email .'</p>
<p>Phone Number: '. $project_number .'</p>
<p>The client uploaded a file ' .$project_file.'.</p>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From:' .$project_email . "\r\n";
if (!empty($project_email)) {
if (filter_var($project_email, FILTER_VALIDATE_EMAIL)) {
//Should also do a check on the mail function
if (mail($to, $subject, $message, $headers)) {
echo "Your email was sent!"; // success message
} else {
echo "Mail could not be sent!"; // failed message
}
} else {
//Invalid email
echo "Invalid Email, please provide a valid email address.";
}
} else {
echo "Email Address was not filled out.";
}

You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method sends the form data to the server, then a script on the server handles the upload.
Here's an example using PHP. Take a look at this example.
Credit goes here -> jQuery AJAX file upload PHP
$('#submit-project').on('click', function() {
var file_data = $('#file').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'email-project.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // display response from the PHP script, if any
}
});
});

Related

unable to retrieve $_POST variable in php

After searching a lot and working endlessly on this problem I decided to post here.
I am passing a formdata with a filename variable to php using ajax. I then try to access the variable name so I can pass it to a second php that loads the name into the database. I am unable to pass or echo the data in php though. Can anyone help?
My javascript
function uploadFile() {
var input = document.getElementById("picture");
file = input.files[0];
newFileName = elementHandle[9].val() + elementHandle[10].val() + elementHandle[11].val();
console.log(newFileName);
if (file != undefined) {
formData = new FormData();
if (!!file.type.match(/image.*/)) {
formData.append("newFileName1", newFileName);
$.ajax({
url: "upload_file.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data) {}
});
} else {
alert('Not a valid image!');
}
} else {
alert('Input something!');
}
}
My php
<?php
$dir = "im_ges/";
$file_name = $dir. $_REQUEST["newFileName1"].".jpg";
echo $file_name;
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_POST ['newFileName1'].".jpg");
?>
Try this sample code
form.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function (responce) {
alert(responce);
}
});
});
});
</script>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<input name="name" value="First Name"><br>
<input name="file" type ="file" ><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
create post.php
echo "Name Value : ".$_POST["name"]."\n\n";
echo "\n File Details\n";
print_r($_FILES);
This will alert the values from form
If you get the file name in your custom php controller the you can use
$target_dir = "uploads/";
$filename = "phonenumber.png";//Set here the new file name which you passed through ajax
$target_file = $target_dir .$filename;
// test here the file is moved or not,
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
then update db with the $filename
}
or i changed the some code in above mentioed and add a text filed to enter a phone number and the selected file moved to the taget with the value enterd in the
text field with name phone can you check is it usefull for you .
form.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'post.php',
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function (responce) {
alert(responce);
}
});
});
});
</script>
</head>
<body>
<form action="" method="post" enctype="multipart/form-data"><form id="uploadimage" action="" method="post" enctype="multipart/form-data">
<input name="name" value="First Name"><br>
<input name="phone" value=""><br> <!-- new field -->
<input name="file" type ="file" ><br>
<input name="submit" type="submit" value="Submit">
</form>
</body>
</html>
post.php
<?php
echo "Name Value : ".$_POST["name"]."\n\n";
echo "\n File Details\n";
print_r($_FILES);
$target_dir = "uploads/";
$uploadOk = 1;
$filename = $_FILES['image']['name'];
$ext = pathinfo($filename, PATHINFO_EXTENSION);
$target_file = $target_dir . $_POST["phone"].$ext; // here we change the file name before uploads
// test here the file is moved or not,
if (move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
// if moved the file then update db with the $filename write code here
}
?>
create a folder in the root with name "uploads" and give full permison

Google invisible recaptcha using jquery and php

I'm trying to add Google's invisible recaptcha in my website. It is basically for a contact us form where the user submits his name, email and message and on clicking submit will trigger a mail to us.
I planned to take care of the mail part using php. However, I am not able to get past submitting the form in jquery.
This is my html :
<div class="row">
<script src="mail.js"></script>
<form id="main-contact-form" name="contact-form">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Name" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email" required>
</div>
<div class="form-group">
<textarea name="message" class="form-control" rows="2" placeholder="Message" required></textarea>
</div>
<button class="g-recaptcha btn btn-primary" data-sitekey="6LdGAiQUAAAAAHeNXI3yDSsZhLAJs7U1HX_zXm8o" data-callback="onSubmit" type="submit">Submit</button>
</form>
</div>
The onSubmit callback:
function onSubmit(response) {
var request;
console.log('here');
document.getElementById('main-contact-form').submit();
}
The jQuery code for passing the submitted form to the php where verification of the captcha is done mail is sent:
$("#main-contact-form").submit(function(event) {
// Prevent default posting of form - put here to work in case of errors
event.preventDefault();
console.log('in here');
// Abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// Let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// Serialize the data in the form
var serializedData = $form.serialize();
// Let's disable the inputs for the duration of the Ajax request.
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function(response, textStatus, jqXHR) {
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function(jqXHR, textStatus, errorThrown) {
// Log the error to the console
console.error(
"The following error occurred: " +
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function() {
// Reenable the inputs
$inputs.prop("disabled", false);
});
});
Php code for mailing:
<?php
$name;$email;$message;$captcha;
if(isset($_POST['name'])){
$name=$_POST['name'];
}if(isset($_POST['email'])){
$email=$_POST['email'];
}if(isset($_POST['message'])){
$message=$_POST['message'];
}if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
exit;
}
$secretKey = "secret key";
$ip = $_SERVER['REMOTE_ADDR'];
$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha.);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo '<h2>Message could not be sent</h2>';
} else {
$name = #trim(stripslashes($name));
$from = #trim(stripslashes($email));
$subject = #trim(stripslashes('contact'));
$message = #trim(stripslashes($message));
$to = 'email#email.com';//replace with your email
$headers = array();
$headers[] = "MIME-Version: 1.0";
$headers[] = "Content-type: text/plain; charset=iso-8859-1";
$headers[] = "From: {$name} <{$from}>";
$headers[] = "Reply-To: <{$from}>";
$headers[] = "Subject: {$subject}";
$headers[] = "X-Mailer: PHP/".phpversion();
mail($to, $subject, $message, $headers);
echo '<h2>Thanks for posting comment.</h2>';
}
?>
?>
The PHP code might not be correct and I am yet to work on that (I haven't used PHP before.).
Now, when I try to submit the form, the page reloads with the form as query params in the address bar. Even, when event.preventDefault() is given for when the form is submitted in the onSubmit callback of Recaptcha, it reloads the page.
Please help me with getting this working. Also I do not want to refresh the page when the form is submitted as I plan to use ajax for sending the form input to the php script.

jquery.ajax, success and done function is not returning anything

I am a wordpress user and try to update the database using jquery.ajax. My code updates the database but the success function doesn't return anything to html div tag. Here are some portions of my code:
PHP Code:
$connect = mysqli_connect(HOST, USER, PASS, NAME);
if(mysqli_connect_errno()){
$msg = "Connection With Database is not Successful. Error: ".mysqli_error();
echo $msg;
die();
}
$nam = $_POST['name'];
$eml = $_POST['email'];
$entry = "INSERT INTO `table` (name, email,) VALUES ('$nam', '$eml')";
if(!mysqli_query($connect, $entry)){
$msg = "Error while submitting Your Data. Error: ".mysqli_error();
echo $msg;
die();
}
$msg = "Your data submitted successfully";
echo $msg;
mysqli_close($connect);
?>
HTML Code:
<form method="POST" id="data_form">
<input type="text" name="name" id="name" placeholder="Full Name" />
<br>
<input type="email" name="email" id="email" placeholder="Email Address" required />
<br>
<button type="submit" id="submit">Submit</button>
</form>
<div id="output"></div>
jQuery Code:
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false,
success: function(result){
$("#output").html(result);
}
});
});
});
I also used 'done' instead of 'success' but didn't work.
jQuery(document).ready(function (){
$("#data_form").submit(function (e){
e.preventDefault();
var formdata = $("#data_form").serialize();
$.ajax({
type: "POST",
url: "udata.php",
data: formdata,
cache: false
}).done(function(result){
$("#output").html(result);
});
});
});
Actually I am trying to print the $msg variable from the php file to the 'output' div tag.
Any help would be greatly appreciated.

Sending e-mail form using PHP and AJAX

I have contact form on my site. It sends message to email. I try to do it without page reload using AJAX, but it seems that AJAX doesn't work: messages are sent but the page still redirecting to call-form.php. What is incorrect in my code? (jQuery is included)
HTML
<form name="freeCall" action="<?php bloginfo(template_url); ?>/mail/call-form.php" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
</form>
PHP - call-form.php
<?
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
}
?>
JS
$(function () {
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
});
Ok, first when you make an AJAX call, you must have a way to know if your PHP returns you something (useful for debugging).
Then, when submitting a form with AJAX, the tag action="" is not needed.
Finally, to prevent a form from being sent when making an AJAX call, add e.preventDefault() with the event called e here, like in my example.
I have improved your code to be more realistic about the latest standards.
HTML :
<form name="freeCall" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
JS :
$(function () {
$("#free-call-form").submit(function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
dataType: "json", // Add datatype
data: form_data
}).done(function (data) {
console.log(data);
alert("It's OK!");
}).fail(function (data) {
console.log(data);
});
});
});
And PHP :
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
echo json_encode(array('status' => 'success'));
} else {
echo json_encode(array('status' => 'error'));
}
With echo json_encode, you know what is the return of your AJAX call. It is better
You're not preventing the default submit action -
$("#free-call-form").submit(function (event) { // capture the event
event.preventDefault(); // prevent the event's default action
Returning false or preventing the default behavior of the event should work for you.
Example with old .submit(), that now is an alias of .on('eventName'); and using return false to avoid form submission.;
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
return false;
});
Example using .on('eventName') and using e.preventDefault() to avoid form submission.
$("#free-call-form").on('submit', function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
From Jquery .submit() Documentation: This method is a shortcut for
.on( "submit", handler ) in the first variation, > and .trigger(
"submit" ) in the third.
Also, you would consider not using EVER the user input directly, it would not cause problems in this exact context (or maybe yes) but with your actual approach they can change the mail markup or adding some weirds things there, even scripts, you would consider escape, validate or limit it.
Also as zLen pointed out in the comments:
the action in the form markup is not necessary because you are not using it, you can remove it:
action="<?php bloginfo(template_url); ?>/mail/call-form.php"
What is happening is your form is being submitted, it's not actually the AJAX call which is doing it. To fix it, add
return false;
at the end of the submit function so that the browser doesn't submit the form and the AJAX call happens properly.

showing text in div without reloading the page

In the following code, I have a contact form and in that form there is an email validation script. As a result of validation, I want the error message to be shown in a div called confirmation without reloading the page. Also, if the email is valid, the mail will be sent and I want the Thank you message to be shown in the same div confirmation. The problem is what can I do to prevent reloading the page and let the error message or the thanks message shows in the confirmation div?
<html>
<body>
<?php
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return TRUE;
} else {
return FALSE;
}
}
?>
<?php
if (!isset($_POST["submit"])) {
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
From: <input type="text" name="from"><br>
Subject: <input type="text" name="subject"><br>
Message: <textarea rows="10" cols="40" name="message"></textarea><br>
<input type="submit" name="submit" value="Submit Feedback"><br>
<div id="confirmation" style="display:none" align="center"></div>
</form>
<?php
} else { // the user has submitted the form
// Check if the "from" input field is filled out
if (isset($_POST["from"])) {
// Check if "from" email address is valid
$mailcheck = spamcheck($_POST["from"]);
if ($mailcheck==FALSE) {
echo"
<script>
document.getElementById('confirmation').text ='invalid email';
</script>";
} else {
$from = $_POST["from"]; // sender
$subject = $_POST["subject"];
$message = $_POST["message"];
// message lines should not exceed 70 characters (PHP rule), so wrap it
$message = wordwrap($message, 70);
// send mail
mail("nawe11#gmail.com",$subject,$message,"From: $from\n");
echo"
<script>
document.getElementById('confirmation').text ='Thank you';
</script>";
}
}
}
?>
</body>
</html>
Thanks
<input type="text" name="from" id ="from">
Call example:
var request = $.ajax({
url: "file.php",
type: "POST",
data: { email : $('#from').val() }
});
request.done(function( msg ) {
//handle HTML
});
request.fail(function( jqXHR, textStatus ) {
//Handle problem at server side
});
PHP Side
<?php
$email = $_POST["email"]
function spamcheck($field) {
// Sanitize e-mail address
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
// Validate e-mail address
if(filter_var($field, FILTER_VALIDATE_EMAIL)) {
return 'valid';
} else {
return 'no_valid';
}
}
echo spamcheck($email);
There's no way you could do that with just PHP.
What you're looking at is commonly known as AJAX, and uses client-side language (Javascript)
It's very common, and widely used on the internet. You can find many examples and production-ready scripts by searching ajax on google.
More informations here : http://www.w3schools.com/ajax/

Categories

Resources