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.
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.
I have produced a site at "http://missdcall.co.uk" and have included a contact form at the bottom using Pulse CMS.
The contact form continues to return an error stating: "Sorry it seems that our mail server is not responding, Sorry for the inconvenience!"
As far as I can see, all is set-up correctly. I cannot see any errors in the code.
If anyone has any suggestions, they would be greatly appreciated!
Please find relevant files below...
home.txt
<div class="col-sm-6">
<form id="form_1" novalidate>
<div class="form-group">
<label>
Name
</label>
<input id="name" class="form-control" required />
</div>
<div class="form-group">
<label>
Email
</label>
<input id="email" class="form-control" type="email" required />
</div>
<div class="form-group">
<label>
Message
</label><textarea id="message" class="form-control" rows="4" cols="50" required></textarea>
</div>
<button class="bloc-button btn btn-d btn-lg btn-block" type="submit">
Send
</button>
</form>
</div>
form_1.php
<?php
if(empty($_POST['name']) && strlen($_POST['name']) == 0 || empty($_POST['email']) && strlen($_POST['email']) == 0 || empty($_POST['message']) && strlen($_POST['message']) == 0)
{
return false;
}
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'hello#missdcall.co.uk'; // Email submissions are sent to this email
// Create email
$email_subject = "Message from miss'd call.";
$email_body = "You have received a new message. \n\n".
"Name: $name \nEmail: $email \nMessage: $message \n";
$headers = "MIME-Version: 1.0\r\nContent-type: text/plain; charset=UTF-8\r\n";
$headers .= "From: joe#j-col.com\n";
$headers .= "Reply-To: $email";
mail($to,$email_subject,$email_body,$headers); // Post message
return true;
?>
formHandler.js
$(function()
{var successMsg = "Your message has been sent."; // Message shown on success.
var failMsg = "Sorry it seems that our mail server is not responding, Sorry for the inconvenience!"; // Message shown on fail.
$("input,textarea").jqBootstrapValidation(
{
preventSubmit: true,
submitSuccess: function($form, event)
{
if(!$form.attr('action')) // Check form doesnt have action attribute
{
event.preventDefault(); // prevent default submit behaviour
var processorFile = "./includes/"+$form.attr('id')+".php";
var formData = {};
$form.find("input, textarea, option:selected").each(function(e) // Loop over form objects build data object
{
var fieldData = $(this).val();
var fieldID = $(this).attr('id');
if($(this).is(':checkbox')) // Handle Checkboxes
{
fieldData = $(this).is(":checked");
}
else if($(this).is(':radio')) // Handle Radios
{
fieldData = $(this).val()+' = '+$(this).is(":checked");
}
else if($(this).is('option:selected')) // Handle Option Selects
{
fieldID = $(this).parent().attr('id');
}
formData[fieldID] = fieldData;
});
$.ajax({
url: processorFile,
type: "POST",
data: formData,
cache: false,
success: function() // Success
{
$form.append("<div id='form-alert'><div class='alert alert-success'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button><strong>"+successMsg+"</strong></div></div>");
},
error: function() // Fail
{
$form.append("<div id='form-alert'><div class='alert alert-danger'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button><strong>"+failMsg+"</strong></div></div>");
},
complete: function() // Clear
{
$form.trigger("reset");
},
});
}
},
filter: function() // Handle hidden form elements
{
return $(this).is(":visible");
},
});
});
I found a tutorial for a simple contact form using fancyBox. I was able to apply the form into my website, and then modify the code of the form to meet my needs. But my form is not working.
Once I put in all of the information into the form and I press the Send Email button, the button then disappears and I get a "sending..." which is what it supposed to do if all of the fields are "true". But it does not want to do the last step which is to run the php file.
The form also came with the php file necessary for this to work, but it doesn't send it.
Does the php file have to be in an specific place in the website? I have tried to place it from several different locations but to no avail.
<div id="inline">
<form id="contact" name="contact" action="#" method="post">
<label for="name">Your Name </label>
<input type="text" id="name" name="name" class="txt">
<br>
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
<script type="text/javascript">
function validateEmail(email) {
var reg = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)|(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return reg.test(email);
}
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var nameval = $("#name").val();
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
var namelen = nameval.length;
if(namelen < 2) {
$("#name").addClass("error");
}
else if(namelen >= 2) {
$("#name").removeClass("error");
}
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4 && namelen >= 2) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
$(this).before("<p><strong>Success! We will respond to your request as soon as possible.</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
sendmessage.php
<?php
$sendto = "antiques47#aol.com";
$username = $_POST['name'];
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$subject = "More information request";
$headers = "From: " . strip_tags($usermail) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New User Feedback</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$username."</p>\r\n";
$msg .= "<p><strong>Email:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "</body></html>";
if(#mail($sendto, $subject, $msg, $headers)) {
echo "true";
} else {
echo "false";
}
?>
I tried changing the ACTION on the form to the specific file, but it didn't work either.
I noticed that the ajax part also has the URL to send message.php, I tried to change that so it has a specific directory to the file but that did not work.
Updated:
You are changing the From: attribute in your mail headers. Some ISPs will block outgoing emails that do that. This could be your problem. Comment out the line:
$headers = "From: " . strip_tags($usermail) . "\r\n";
and try again.
If that fails, check each step of the AJAX:
.1. In sendmessage.php, change the very top of the file to read:
<?php
die('Got to here');
.2. Then, back in your ajax code block, amend it (temporarily) to read:
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
alert(data);
}
});
This will at least tell you if it is communicating.
.3. Then, echo back the POST items that you received, to ensure there isn't a problem there:
PHP:
$username = $_POST['name'];
$usermail = $_POST['email'];
$content = nl2br($_POST['msg']);
$out = 'username [' .$username. ']';
$out .= 'usermail [' .$usermail. ']';
$out .= 'content [' .$content. ']';
echo $out;
Again, see what is echo'd out by the ajax success function.
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 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.