I have problem with the ajax file. The ajax file does not work with the php form.
when I run the code it displays an error file_get_content error, file name empty.
The php code is working properly. but the ajax file cannot transfer the file field value.
So the file cannot attach with mail.
it shows the error: file name empty
plz help me to pass the file field value through the ajax file.
<div>
<form method="post" enctype="multipart/form-data" name="form1" id="form1" action="contactus.php" onsubmit="xmlhttpPost('contactus.php', 'form1', 'Myresult', ''); return false;">
Name:<input name="name1" type="text" value="" />
Address:<input name="address1" type="text" value="" />
Phone:<input name="phone1" type="text" value=""/>
Email: <input name="email1" type="text" value="" />
File:<input name="file" type="file" size="35" id="file" />
Links:<input name="links1" type="text" value="" />
Subject:<input name="subject1" type="text" value="" />
Location:<select name="location">
<option value="" selected="selected">--Select--</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option>
<option>5</option>
</select>
Comments:<textarea name="comment1" ></textarea>
<input name="submit" id="submit" type="submit"/>
<div id="Myresult"></div>
</form>
</div>
php form(contactus.php)
<?php
if(isset($_POST['submit']))
{
$name=$_POST['name1'];
$address=$_POST['address1'];
$phone=$_POST['phone1'];
$email=$_POST['email1'];
$subject=$_POST['subject1'];
$location=$_POST['location'];
$comment=$_POST['comment1'];
$links=$_POST['links1'];
$to='mail#mail.com';
$message .= "\nName: ".$name."\n\n";
$message .= "Address: ".$address."\n\n";
$message .= "Phone: ".$phone."\n\n";
$message .= "Email: ".$email."\n\n";
$message .= "Links: ".$links."\n\n";
$message .= "Location: ".$location."\n\n";
$message .= "Comments:\n\n ".$comment."\n";
$attachment = chunk_split(base64_encode(file_get_contents($_FILES['file']['tmp_name'])));
$filename = $_FILES['file']['name'];
$filetype = $_FILES['file']['type'];
$boundary =md5(date('r', time()));
$headers = "From: $name <$email>\r\nReply-To: $name <$email>";
$headers .= "\r\nMIME-Version: 1.0\r\nContent-Type: multipart/mixed; boundary=\"_1_$boundary\"";
$message="This is a multi-part message in MIME format.
--_1_$boundary
Content-Type: multipart/alternative; boundary=\"_2_$boundary\"
--_2_$boundary
Content-Type: text/plain; charset=\"iso-8859-1\"
Content-Transfer-Encoding: 7bit
$message
--_2_$boundary--
--_1_$boundary
Content-Type: $filetype; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment
$attachment
--_1_$boundary--";
mail($to,$subject,$message,$headers);
print 'Thanks, your message sent!';
}
?>
ajax.js
function xmlhttpPost(strURL,formname,responsediv,responsemsg) {
var xmlHttpReq = false;
var self = this;
// Xhr per Mozilla/Safari/Ie7
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// per tutte le altre versioni di IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
// Quando pronta, visualizzo la risposta del form
updatepage(self.xmlHttpReq.responseText,responsediv);
}
else{
// In attesa della risposta del form visualizzo il msg di attesa
updatepage(responsemsg,responsediv);
}
}
self.xmlHttpReq.send(getquerystring(formname));
}
function getquerystring(formname) {
var form = document.forms[formname];
var qstr = "";
function GetElemValue(name, value) {
qstr += (qstr.length > 0 ? "&" : "")
+ escape(name).replace(/\+/g, "%2B") + "="
+ escape(value ? value : "").replace(/\+/g, "%2B");
//+ escape(value ? value : "").replace(/\n/g, "%0D");
}
var elemArray = form.elements;
for (var i = 0; i < elemArray.length; i++) {
var element = elemArray[i];
var elemType = element.type.toUpperCase();
var elemName = element.name;
if (elemName) {
if (elemType == "TEXT"
|| elemType == "TEXTAREA"
|| elemType == "PASSWORD"
|| elemType == "BUTTON"
|| elemType == "RESET"
|| elemType == "SUBMIT"
|| elemType == "FILE"
|| elemType == "IMAGE"
|| elemType == "HIDDEN")
GetElemValue(elemName, element.value);
else if (elemType == "CHECKBOX" && element.checked)
GetElemValue(elemName,
element.value ? element.value : "On");
else if (elemType == "RADIO" && element.checked)
GetElemValue(elemName, element.value);
else if (elemType.indexOf("SELECT") != -1)
for (var j = 0; j < element.options.length; j++) {
var option = element.options[j];
if (option.selected)
GetElemValue(elemName,
option.value ? option.value : option.text);
}
}
}
return qstr;
}
function updatepage(str,responsediv){
document.getElementById(responsediv).innerHTML = str;
}
problems:
1) Standard AJAX cannot upload files. The usual workaround is to build a form in a hidden <iframe> and perform a standard POST upload there.
2) Your code simply ASSUMES an upload has been performed AND succeeded. This is, frankly, stupid. NEVER assume success when dealing with users. Always prepare for the worst. Your code, at minimum, should have something like this:
if ($_FILES['fieldname']['error'] !== UPLOAD_ERR_OK) {
die("File upload failed with error code " . $_FILES['fieldname']['error']);
}
if you'd had something like that, you'd have gotten (probably) error code #4 - no file uploaded, because uploads cannot be done via AJAX. The error codes are defined here: http://www.php.net/manual/en/features.file-upload.errors.php
3) You are building your own mime emails, which is not the easiest thing to get right. Why don't you try using Swiftmailer or PHPMailer? Both make sending a MIME email, with html, embedded attachments, etc... almost trivial. Virtually all of your MIME-building code would be reduced to a SINGLE line in either library.
Related
Project structure is as follows
C:\xampp\htdocs\myProject\Documentation
C:\xampp\htdocs\myProject\HTML\css
C:\xampp\htdocs\myProject\HTML\images
C:\xampp\htdocs\myProject\HTML\js
C:\xampp\htdocs\myProject\HTML\videos
C:\xampp\htdocs\myProject\HTML\404.html
C:\xampp\htdocs\myProject\HTML\contact.php
C:\xampp\htdocs\myProject\HTML\index.html
C:\xampp\htdocs\myProject\PSD
I have a contact form in index.html that is controlled by a javascript file. This code stops default form submit, performs error checks and then uses ajax to make a post request to contact.php. The javascript code runs, it detects the php (see the alert in the code below just after the axjax funtion call. The value of d is the php script in the alert, but none of the debug lines in the php code get called and it never returns 'success'.
Here is the form
<form class="form-horizontal" id="phpcontactform">
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Full Name" name="name" id="name">
</div>
<div class="control-group">
<input class="input-block-level" type="email" placeholder="Email ID" name="email" id="email">
</div>
<div class="control-group">
<input class="input-block-level" type="text" placeholder="Mobile Number" name="mobile" id="mobile">
</div>
<div class="control-group">
<textarea class="input-block-level" rows="10" name="message" placeholder="Your Message" id="message"></textarea>
</div>
<div class="control-group">
<p>
<input class="btn btn-danger btn-large" type="submit" value="Send Message">
</p>
<span class="loading"></span> </div>
</form>
here is the javascript
// JavaScript Document
$(document).ready(function() {
$("#phpcontactform").submit(function(e) {
e.preventDefault();
var name = $("#name");
var email = $("#email");
var mobile = $("#mobile");
var msg = $("#message");
var flag = false;
if (name.val() == "") {
name.closest(".control-group").addClass("error");
name.focus();
flag = false;
return false;
} else {
name.closest(".control-group").removeClass("error").addClass("success");
} if (email.val() == "") {
email.closest(".control-group").addClass("error");
email.focus();
flag = false;
return false;
} else {
email.closest(".control-group").removeClass("error").addClass("success");
} if (msg.val() == "") {
msg.closest(".control-group").addClass("error");
msg.focus();
flag = false;
return false;
} else {
msg.closest(".control-group").removeClass("error").addClass("success");
flag = true;
}
var dataString = "name=" + name.val() + "&email=" + email.val() + "&mobile=" + mobile.val() + "&msg=" + msg.val();
$(".loading").fadeIn("slow").html("Loading...");
$.ajax({
type: "POST",
data: dataString,
url: "http://localhost/myProject/HTML/contact.php",
cache: false,
success: function (d) {
alert("d: "+d);
$(".control-group").removeClass("success");
if(d == 'success') // Message Sent? Show the 'Thank You' message and hide the form
$('.loading').fadeIn('slow').html('<font color="green">Mail sent Successfully.</font>').delay(3000).fadeOut('slow');
else
$('.loading').fadeIn('slow').html('<font color="red">Mail not sent.</font>').delay(3000).fadeOut('slow');
}
});
return false;
});
$("#reset").click(function () {
$(".control-group").removeClass("success").removeClass("error");
});
})
And finally here is the php
<?php
echo "<script>console.log('Debug Objects:' );</script>";
$name = $_REQUEST["name"];
$email = $_REQUEST["email"];
$mobile = $_REQUEST["mobile"];
$msg = $_REQUEST["msg"];
echo "<script>";
echo "alert('this also works');";
echo "</script>";
$to = "myemail#gmail.com";
if (isset($email) && isset($name) && isset($msg)) {
$subject = $name."sent you a message via Raaga";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: ".$name." <".$email.">\r\n"."Reply-To: ".$email."\r\n" ;
$msg = "From: ".$name."<br/> Email: ".$email ."<br/> Mobile: ".$mobile." <br/>Message: ".$msg;
echo "<script>alert('this maybe works');</script>";
$mail = mail($to, $subject, $msg, $headers);
if($mail)
{
echo 'success';
}
else
{
echo "<script>alert('name:'+$name);</script>";
echo 'failed';
}
}
echo "<script>alert('this finally works');</script>";
?>
I tried moving contact.php to the htdocs root but that didnt work. Have turned off all antivirus and firewalls but that didnt work either. Am at a loss. Thought php was supposed to work out of the box with xampp?
Okay so thanks to ADyson for the help. The issue was not that php isn't running, its that the mail server was not properly configured.
Hello I would like to attach a file and send it using jQuery AJAX and PHP, right now it just send the text, can some body help me about what it follows to attach the file and send the email with it,
Then i will proceed with validations,
I will show the complete solution after achieve it
This is the form
<form class="parte-form" enctype="multipart/form-data">
<input type="text" class="txt-field txt-full pName" name="pName" placeholder="* Nombre" required="required">
<div class="half-input-cont">
<input type="text" class="txt-field txt-half" name="pPhone" placeholder="Telefono">
<input type="text" class="txt-field txt-half" name="pEmail" placeholder="* Correo" required="required">
</div>
<textarea class="txt-field txt-full txt-area" placeholder="Mensaje" name="pMsg"></textarea>
<div class="input-cont">
<label class="txt-file" for="cv">Adjuntar C.V.<p>Seleccionar archivo</p> <span>No se ha elegido archivo</span></label>
<input type="file" class="txt-file-btn" id="cv" name="pFile">
</div>
<div class="more-btn-cont form-btn-cont">
<input type="hidden" name="frm-action" value="par-form">
<input type="submit" class="btn btn-blue-l btn-par" name="pPar" value="Enviar solicitud">
</div>
</form>
this is the data preparation to be send - jQuery Ajax
$(data);
function data(){
$('.btn-par').click(parte);
}
function parte(e){
e.preventDefault();
var data = $('.parte-form').serializeArray();
$.ajax({
type: "POST",
url: "data/comp-actions.php",
data: data,
beforeSend: function(){
},
success: function (response) {
if (response == 1) {
var name = $('.pName').val();
$('.popup-name').html(name)
$('.popup-send').removeClass('hidden');
$('.popup-close').click(function(){
$('.popup-send').addClass('hidden');
});
} else {
console.log('Error al enviar');
}
}
});
}
This is the data recollection and sender - PHP
//Cotizar values
$pName = $_POST['pName'];
$pPhone = $_POST['pPhone'];
$pEmail = $_POST['pEmail'];
$pMsg = $_POST['pMsg'];
$pPar = $_POST['pPar'];
//File name
$fileName = $_FILES['pFile']['name'];
$fileTmp = $_FILES['pFile']['tmp_name'];
$filePath = "files/".$fileName;
//File metadata
$fileType = $_FILES['pFile']['type'];
$fileSize = $_FILES['pFile']['size'];
// $fileError = $_FILES['pFile']['error'];
//Send mail
if($pName != "" && $pEmail != ""){
$to = "my#email.com";
$subject = "$pName Desea unirse al equipo";
$headers = "From: $pEmail";
$info = "$pName, se comunica con nosotros para unirse al equipo\n"
. "\n"
. "\n"
. "Datos del solicitante\n"
. "Nombre: $pName\n"
. "Telefono: $pPhone\n"
. "Email: $pEmail\n"
. "mensaje: $pMsg\n"
. "\n"
. "\n"
. "Datos del archivo\n"
. "Archivo: $fileName\n"
. "Tipo de archivo: $fileType\n"
. "Tamaño del archivo: $fileSize\n"
. "Ruta del archivo: $filePath\n"
. "\n"
. "\n"
. "\n";
if (mail($to, $subject, $info, $headers)) {
echo 1;
}else{
echo 0;
}
}
Use FormData to grab file contents as well
var form = $(".parte-form")[0];
var data = new FormData(form);
In your ajax call, set
processData: false
Here is my solution for this feature
This solution could be improved I'm working on it if you have a better solution, please pot it or post the link to the solution
File with the form, the call to your css and js files, in case of not need it you can remove the recaptcha div
<form class="parte-form" id="contact_body" method="POST" action="send-unete.php" enctype="multipart/form-data">
<input type="text" class="txt-field txt-full pName txt-text" name="pName" placeholder="* Nombre" required="required">
<div class="half-input-cont">
<input type="tel" class="txt-field txt-half txt-phone" name="pPhone" placeholder="Teléfono">
<input type="email" class="txt-field txt-half" name="pEmail" placeholder="* Correo" required="required">
</div>
<textarea class="txt-field txt-full txt-area" placeholder="Mensaje" name="pMsg"></textarea>
<div class="input-cont">
<!-- it changes the style of the input type file -->
<label class="txt-file" for="cv">Adjuntar C.V.<p>Seleccionar archivo</p> <span>No se ha elegido archivo</span></label>
<input type="file" class="txt-file-btn" id="cv" name="pFile[]">
</div>
<div class="g-recaptcha" data-sitekey="your key"></div>
<div class="more-btn-cont form-btn-cont">
<!-- Set of email where the email will be send -->
<input type="hidden" name="pEmailSet" value="<?php the_field( 'email_set_unete', 216) ?>">
<!-- Identifies the form in case of have more forms or actions like save, delete, load etc -->
<input type="hidden" name="frm-action" value="par-form">
<input type="submit" class="btn btn-blue-l btn-par" name="pPar" value="Enviar solicitud">
</div>
</form>
<!-- Success popup -->
<div class="popup-send layer hidden">
<div class="wrapper">
<div class="popup-info">
<div class="popup-title">
<p>Mensaje enviado</p>
<button class="popup-close">X</button>
</div>
<p class="popup-msg"><b class="popup-bold popup-name"></b>, Tus datos han sido enviados al área correspondiente en la brevedad nos comunicaremos contigo, para darle seguimiento a tu petición, <b class="popup-bold">Gracias</b></p>
</div>
</div>
</div>
<!-- Error popup -->
<div class="popup-error layer hidden">
<div class="wrapper">
<div class="popup-info">
<div class="popup-title">
<p>Mensaje no enviado</p>
<button class="popup-close">X</button>
</div>
<p class="popup-msg"></p>
</div>
</div>
</div>
<!-- it gets the mail path of the site used for references -->
<p class="dir hidden"><?php bloginfo('template_directory'); ?></p>
JS file with ajax call it recolects the data and prepar it for be reciebed by the php file
function data(){
// Action function
// $('.btn-cot').click(cotizar);
$('.btn-par').click(parte);
}
function parte(e){
$("#contact_body").submit(function(e){
e.preventDefault(); //prevent default action
proceed = true;
//if everything's ok, continue with Ajax form submit
if(proceed){
var post_url = $(this).attr("action"); //get form action url
var request_method = $(this).attr("method"); //get form GET/POST method
var form_data = new FormData(this); //Creates new FormData object
$.ajax({ //ajax form submit
url : "data/comp-actions.php",
type: request_method,
data : form_data,
dataType : "json",
contentType: false,
cache: false,
processData:false
}).done(function(res){ //fetch server "json" messages when done
if(res == 1){
var name = $('.pName').val();
$('.popup-name').html(name)
$('.popup-send').removeClass('hidden');
$('.popup-close').click(function(){
$('.popup-send').addClass('hidden');
});
}else{
$(".popup-error").removeClass("hidden"),
$(".popup-error .popup-msg").html('Tu mensaje no pudo ser enviado, te pedimos revises que hayas completado los <b class="popup-bold">campos requeridos (*)</b>, revisado que el archivo adjunto sea en <b class="popup-bold">formato pdf</b>, asi como marcado la <b class="popup-bold">casilla de verificación</b> y vuelvas a intentarlo, <b class="popup-bold">Gracias</b>'),
$(".popup-close").click(function() {
$(".popup-error").addClass("hidden");
})
}
});
}
});
}
This is the comp-actions.php file, it checks the submited action and loads the needed file, the recaptchalib.php must be added in order to get the recaptcha response
include('recaptchalib.php');
//Action selector
$action = $_POST['frm-action'];
$captchaResponse = $_POST['g-recaptcha-response'];
if ($captchaResponse != "") {
$captcha = 1;
if($action == "cot-form" && $captcha == 1){
include('send-cotizar.php');
} elseif($action == "par-form" && $captcha == 1){
include('send-unete.php'); //**
}elseif($captcha != 1){
echo 0;
}
} else {
echo 0;
}
This is the send-unete.php file wich is loaded after the action check and prepare the data and attachment to be send it
$pEmailSet = $_POST['pEmailSet'];
$recipient_email = $pEmailSet; //recepient
$fromUser = $_POST['pEmail'];
$from_email = $fromUser; //from email using site domain.
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
die('Sorry Request must be Ajax POST'); //exit script
}
if($_POST){
$sender_name = filter_var($_POST["pName"], FILTER_SANITIZE_STRING); //capture sender name
$sender_email = filter_var($_POST["pEmail"], FILTER_SANITIZE_STRING); //capture sender email
$phone_number = filter_var($_POST["pPhone"], FILTER_SANITIZE_NUMBER_INT);
$subject = "$sender_name desea unirse a nuestro equipo";
$message = filter_var($_POST["pMsg"], FILTER_SANITIZE_STRING); //capture message
$attachments = $_FILES['pFile'];
$file_count = count($attachments['name']); //count total files attached
$boundary = md5("sanwebe.com");
//construct a message body to be sent to recipient
$message_body = "$sender_name, se comunica con nosotros para unirse a nuestro equipo\n";
$message_body .= "\n";
$message_body .= "Datos del solicitante\n";
$message_body .= "Nombre: $sender_name\n";
$message_body .= "Email: $sender_email\n";
$message_body .= "Tel: $phone_number\n";
$message_body .= "Mensaje: $message\n";
if($file_count > 0){ //if attachment exists
//header
$headers = "MIME-Version: 1.0\r\n";
$headers .= "From:".$from_email."\r\n";
$headers .= "Reply-To: ".$sender_email."" . "\r\n";
$headers .= "Content-Type: multipart/mixed; boundary = $boundary\r\n\r\n";
//message text
$body = "--$boundary\r\n";
$body .= "Content-Type: text/plain; charset=ISO-8859-1\r\n";
$body .= "Content-Transfer-Encoding: base64\r\n\r\n";
$body .= chunk_split(base64_encode($message_body));
//attachments
for ($x = 0; $x < $file_count; $x++){
if(!empty($attachments['name'][$x])){
if($attachments['error'][$x]>0) //exit script and output error if we encounter any
{
$mymsg = array(
1=>"The uploaded file exceeds the upload_max_filesize directive in php.ini",
2=>"The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form",
3=>"The uploaded file was only partially uploaded",
4=>"No file was uploaded",
6=>"Missing a temporary folder" );
print json_encode( array('type'=>'error',$mymsg[$attachments['error'][$x]]) );
exit;
}
//get file info
$file_name = $attachments['name'][$x];
$file_size = $attachments['size'][$x];
$file_type = $attachments['type'][$x];
//read file
$handle = fopen($attachments['tmp_name'][$x], "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content)); //split into smaller chunks (RFC 2045)
$body .= "--$boundary\r\n";
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
$body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
}
}
}else{ //send plain email otherwise
$headers = "From:".$from_email."\r\n".
"Reply-To: ".$sender_email. "\n" .
"X-Mailer: PHP/" . phpversion();
$body = $message_body;
}
$sentMail = mail($recipient_email, $subject, $body, $headers);
if($sentMail) //output success or failure messages
{
echo 1;
// print json_encode(array('type'=>'done', 'text' => 'Thank you for your email'));
// exit;
}else{
echo 0;
// print json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
// exit;
}
}
This is really making me crazy.
This is the issue, I have X form with some text inputs and one input file. In my script I do a previous validation and after, send it to x.php file who sent the mail and returns a response, after that the page changes depending that response. The issue is the x.php file is no receiving the file by this way.
HTML
<form action="/" method="post" enctype="multipart/form-data" id="hv_form" name="hv_form">
<input type="text" name="name" placeholder="Nombre completo" />
<input type="email" name="email" placeholder="E-mail" />
<input type="text" name="phone" placeholder="Teléfono" />
<input type="file" name="hv_file" id="hv_file" />
<label for="hv_file">
<img src="images/addFile.svg" />
Elige un archivo...
</label>
<button class="submit submit_file trans35" type="submit">Enviar archivo</button>
</form>
JQUERY
function send_file(trigger, dataOrigin) {
// trigger > the button inside form to submit data
// dataOrifin > the form
$(trigger).on( 'click', function(e) {
e.preventDefault();
var error = false,
$name = $(dataOrigin +" [class*='name']").val(),
$email = $(dataOrigin +" [class*='email']").val(),
$phone = $(dataOrigin +" [class*='phone']").val(),
$file = $(dataOrigin +" [id='hv_file']").val();
//Check empty inputs or errors
if($name.length == 0){
var error = true;
$(dataOrigin +" [class*='name']").queue(function(){$(this).addClass('cont_error').dequeue();}).delay(err_wt).queue(function(){$(this).removeClass('cont_error').dequeue();});
} else {
$(dataOrigin +" [class*='name']").removeClass('cont_error');
}
//. . . etc
//Send message and file
if (error == true) {
//do something if previous error
} else if (error == false) {
$.post("send_file.php", $(dataOrigin).serialize(),function(result){
var r = JSON.parse(result);
console.log( r );
if (r[0] == 1) {
// if php file responses "1" means sent
// do something...
console.log( "[HV] "+dataOrigin +": Mensaje enviado");
} else if (r[0] == 0) {
// if php file responses "0" means NOT sent
// do something...
console.log( "[HV] "+ dataOrigin +": Mensaje NO enviado");
}
});
}
PHP CODE
<?php
$email_to = 'xxxx#xxxxxx.com'; //email de la empresa
$business = 'xxxxxx'; //nombre de la empresa
$name = $_POST['name'];
$email_from = $_POST['email'];
$phone = $_POST['phone'];
$file = $_FILES['hv_file'];
//Correo
$headers = "From: Postulacion web <$email_from>" . "\r\n";
$headers .= "Reply-To: $name <$email_from>\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=UTF-8 " . "\r\n";
$headers .= "X-Mailer: PHP/" . phpversion(). "\r\n";
$subject = "$name ha enviado su curriculum"; //Asunto del mensaje
$message_full = "Hello world";
$r;
if(mail($email_to, $subject, $message_full, $headers)){
$r = '1';
} else {
$r = '0';
}
$toSend = [$r, $file ];
echo json_encode($toSend);
?>
But by this way $_FILES (in php file) is always empty, what i'm doing wrong?
And if I remove 'preventDefault' and submit the form naturally by clicking the button, the php file does receive the file!
Pleaaasee help me! I'm full desperate!
I changed up your ajax a bit, but I have a solution that works. In your code, I could not see how you were calling your send_file() function. So I got rid of it and used the button to fire the jquery.
Make sure you have jQuery installed.
You will see some changes in your html as well. Everything gets id's and I changed the button to type="button".
Your going to have to rewrite some of your form validation.
But none the less this work and it should give you a good example to work from. This will work every time you hit the button.
HTML
<form action="/" method="post" enctype="multipart/form-data" id="hv_form" name="hv_form">
<input id="name" type="text" name="name" placeholder="Nombre completo" />
<input id="email" type="email" name="email" placeholder="E-mail" />
<input id="phone" type="text" name="phone" placeholder="Teléfono" />
<input id="hv_file" type="file" name="hv_file" />
<label for="hv_file">
Elige un archivo...
</label>
<button id="sendFile" class="submit submit_file trans35" type="button">Enviar archivo</button>
</form>
jQuery
<script>
$(document).ready(function(){
$('#sendFile').on( 'click', function(e) {
e.preventDefault();
var myForm = new FormData();
myForm.append('name', $('#name').val());
myForm.append('email', $('#email').val());
myForm.append('phone', $('#phone').val());
myForm.append('hv_file', $('#hv_file')[0].files[0]);
$.ajax({
url: 'send_file.php',
type: 'POST',
data: myForm,
success: function (result) {
var r = JSON.parse(result);
console.log( r );
if (r[0] == 1) {
// if php file responses "1" means sent
// do something...
//console.log( "[HV] "+dataOrigin +": Mensaje enviado");
} else if (r[0] == 0) {
// if php file responses "0" means NOT sent
// do something...
//console.log( "[HV] "+ dataOrigin +": Mensaje NO enviado");
}
},
cache: false,
contentType: false,
processData: false
});
});
});
</script>
Your PHP looked ok to me. But you do need to make sure you are validating your post & file in your PHP script to make sure nothing unwanted makes it through.
I have this problem with my contact form. When I submit the form I receive 2 identical emails in my box.
Im using JS to check the form for errors and then simple PHP mail() function to send the email.
Here is the PHP code:
<?php
$from = Trim(stripslashes($_POST['email']));
$to = "myemail#gmail.com";
$subject = "Contact Form";
$name = Trim(stripslashes($_POST['name']));
$email = Trim(stripslashes($_POST['email']));
$number = Trim(stripslashes($_POST['number']));
$message = Trim(stripslashes($_POST['message']));
$body = "";
$body .= "Name: ";
$body .= $name;
$body .= "\n\n";
$body .= "E-mail: ";
$body .= $email;
$body .= "\n\n";
$body .= "Telephone Number: ";
$body .= $number;
$body .= "\n\n";
$body .= "Message: ";
$body .= $message;
$body .= "\n\n";
$success = mail($to, $subject, $body, "From: <$from>" . "\r\n" . "Reply-to: <$from>" . "\r\n" . "Content-type: text; charset=utf-8");
?>
And here is the JS:
$(".submit").click(function() {
var name = $("input[name=name]").val();
var email = $("input[name=email]").val();
var number = $("input[name=number]").val();
var message = $("textarea[name=message]").val();
if (defaults['name'] == name || name == "") {
$(".error").text("Please enter your name!");
return false;
} else if (defaults['email'] == email || email == "") {
$(".error").text("Please enter your email!");
return false;
} else if (defaults['number'] == number || number == "") {
$(".error").text("Please enter your number!");
return false;
} else if (defaults['message'] == message || message == "") {
$(".error").text("Plese enter your message!");
return false;
}
var dataString = 'name=' + name + '&email=' + email + '&number=' + number + '&message=' + message;
$(".error").text("Please wait...").hide().fadeIn("fast");
$.ajax({
type: "POST",
url: "contact.php",
data: dataString,
success: function() {
$('#form form').html("");
$('#form form').append("<div id='success'>Your message has been sent! Thank you</div>");
}
});
return false;
});
And here is the HTML form:
<form id="contact" method="post" action="#">
<label for="name">Name:</label>
<input type="text" name="name" required tabindex="1">
<label for="email">Email adress:</label>
<input type="text" name="email" required tabindex="2">
<label for="number">Tel. number:</label>
<input type="text" name="number" tabindex="3">
<label for="message">Your message:</label>
<textarea name="message" rows="10" cols="70" required tabindex="4"></textarea>
<input type="checkbox" id="terms" name="terms" value="terms">I agree to the terms
<input type="submit" name="submit" class="submit more-info" tabindex="5" value="Send">
<span class="error"></span>
</form>
I have been using the same code for all of my contact forms and it worked all right. Could it be hosting/server related issue?
replace your click event
$(".submit").click(function() {
with
$('.submit').unbind('click').click(function() {
code.
What I can assume your click event is binding two times may be due to a lot of the mess in the code
also use this line in the end of the click event function
$('.submit').unbind('click').click(function() {
// your stuff
event.stopImmediatePropagation(); // as long as not bubbling up the DOM is ok?
});
for reference have a look at the link: https://forum.jquery.com/topic/jquery-executes-twice-after-ajax
$(".submit").click(function(e) { ... }) POSTS to your server for the first time.
Because this is a <submit> button, the form will still submit. The form POSTS to your server for the second time.
The solution would be adding a e.preventDefault() at the bottom inside the $(".submit").click function...
$(".submit").click(function(e) {
// ^ add this e
var name = ...;
$.ajax({
...
});
e.preventDefault();
return false;
});
Try removing the jQuery animations:
$(".error").text("Please wait...").hide().fadeIn("fast");
They can sometimes cause problems.
I've got a contact form with 3 fields and a textarea...
I use jQuery to validate it and then php to send emails.
This contact form works fine but, when I receive an email, From field isn't correct. I'd like to want that From field shows text typed in the Name field of the contact form. Now I get a From field like this: <nameOfMyServerAdmin#serverUrl.com>
For example, if an user types "Matthew" in the name field, I'd like to want that this word "Matthew" appears in the From field.
This is my code (XHTML, jQuery, PHP):
<div id="contact">
<h3 id="formHeader">Send Us a Message!</h3>
<form id="contactForm" method="post" action="">
<div id="risposta"></div> <!-- End Risposta Div -->
<span>Name:</span>
<input type="text" id="formName" value="" /><br />
<span>E-mail:</span>
<input type="text" id="formEmail" value="" /><br />
<span>Subject:</span>
<input type="text" id="formSubject" value="" /><br />
<span>Message:</span>
<textarea id="formMessage" rows="9" cols="20"></textarea><br />
<input type="submit" id="formSend" value="Send" />
</form>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#formSend").click(function(){
var valid = '';
var nome = $("#formName").val();
var mail = $("#formEmail").val();
var oggetto = $("#formSubject").val();
var messaggio = $("#formMessage").val();
if (nome.length<1) {
valid += '<span>Name field empty.</span><br />';
}
if (!mail.match(/^([a-z0-9._-]+#[a-z0-9._-]+\.[a-z]{2,4}$)/i)) {
valid += '<span>Email not valid or empty field.</span><br />';
}
if (oggetto.length<1) {
valid += '<span>Subject field empty.</span><br />';
}
if (valid!='') {
$("#risposta").fadeIn("slow");
$("#risposta").html("<span><b>Error:</b></span><br />"+valid);
$("#risposta").css("background-color","#ffc0c0");
}
else {
var datastr ='nome=' + nome + '&mail=' + mail + '&oggetto=' + oggetto + '&messaggio=' + encodeURIComponent(messaggio);
$("#risposta").css("display", "block");
$("#risposta").css("background-color","#FFFFA0");
$("#risposta").html("<span>Sending message...</span>");
$("#risposta").fadeIn("slow");
setTimeout("send('"+datastr+"')",2000);
}
return false;
});
});
function send(datastr){
$.ajax({
type: "POST",
url: "contactForm.php",
data: datastr,
cache: false,
success: function(html) {
$("#risposta").fadeIn("slow");
$("#risposta").html('<span>Message successfully sent.</span>');
$("#risposta").css("background-color","#e1ffc0");
setTimeout('$("#risposta").fadeOut("slow")',2000);
}
});
}
</script>
<?php
$mail = $_POST['mail'];
$nome = $_POST['nome'];
$oggetto = $_POST['oggetto'];
$text = $_POST['messaggio'];
$ip = $_SERVER['REMOTE_ADDR'];
$to = "support#matthewlabs.com";
$message = $text."<br /><br />IP: ".$ip."<br />";
$headers = "From: $nome \n";
$headers .= "Reply-To: $mail \n";
$headers .= "MIME-Version: 1.0 \n";
$headers .= "Content-Type: text/html; charset=UTF-8 \n";
mail($to, $oggetto, $message, $headers);
?>
You should be using an email address in the "From:" header. Try this:
$headers = "From: $nome <$mail>\r\n";
$headers .= "Reply-To: $mail\r\n";