D
D
del9937882015-09-24 22:14:37
PHP
del993788, 2015-09-24 22:14:37

How to screw ajax?

Hello. After a two-week search for a form with sending several files to the mail without reloading, I still found it. But one problem remains, how to add ajax here? Please look at the code:

<form enctype="multipart/form-data" method="post" id="feedback-form">
<label for="nameFF">Имя:</label>
<input type="text" name="nameFF" id="nameFF" required placeholder="например, Иван Иванович Иванов" x-autocompletetype="name" class="w100 border">
<label for="contactFF">Email:</label>
<input type="email" name="contactFF" id="contactFF" required placeholder="например, [email protected]" x-autocompletetype="email" class="w100 border">
<label for="fileFF">Прикрепить файл:</label>
<input type="file" name="fileFF[]" multiple id="fileFF" class="w100">
<label for="messageFF">Сообщение:</label>
<textarea name="messageFF" id="messageFF" required rows="5" placeholder="Детали заявки…" class="w100 border"></textarea>
<br>
<input value="Отправить" type="submit" id="submitFF">
</form>

document.getElementById('feedback-form').addEventListener('submit', function(evt){
  var http = new XMLHttpRequest(), f = this;
  evt.preventDefault();
  http.open("POST", "contacts.php", true);
  http.onreadystatechange = function() {
    if (http.readyState == 4 && http.status == 200) {
      alert(httfp.responseText);
      if (http.responseText.indexOf(f.nameFF.value) == 0) { // очистить поле сообщения, если в ответе первым словом будет имя отправителя
        f.messageFF.removeAttribute('value');
        f.messageFF.value='';
      }
    }
  }
  http.onerror = function() {
    alert('Извините, данные не были переданы');
  }
  http.send(new FormData(f));
}, false);


<?php
if (isset ($_POST['contactFF'])) {
  $to = "@gmail.com"; // поменять на свой электронный адрес
  $from = $_POST['contactFF'];
  $subject = "Заполнена контактная форма с ".$_SERVER['HTTP_REFERER'];
  $message = "Имя: ".$_POST['nameFF']."\nEmail: ".$from."\nIP: ".$_SERVER['REMOTE_ADDR']."\nСообщение: ".$_POST['messageFF'];
  $boundary = md5(date('r', time()));
  $filesize = '';
  $headers = "MIME-Version: 1.0\r\n";
  $headers .= "From: " . $from . "\r\n";
  $headers .= "Reply-To: " . $from . "\r\n";
  $headers .= "Content-Type: multipart/mixed; boundary=\"$boundary\"\r\n";
  $message="
Content-Type: multipart/mixed; boundary=\"$boundary\"

--$boundary
Content-Type: text/plain; charset=\"utf-8\"
Content-Transfer-Encoding: 7bit

$message";
  for($i=0;$i<count($_FILES['fileFF']['name']);$i++) {
     if(is_uploaded_file($_FILES['fileFF']['tmp_name'][$i])) {
         $attachment = chunk_split(base64_encode(file_get_contents($_FILES['fileFF']['tmp_name'][$i])));
         $filename = $_FILES['fileFF']['name'][$i];
         $filetype = $_FILES['fileFF']['type'][$i];
         $filesize += $_FILES['fileFF']['size'][$i];
         $message.="

--$boundary
Content-Type: \"$filetype\"; name=\"$filename\"
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename=\"$filename\"

$attachment";
     }
   }
   $message.="
--$boundary--";

  if ($filesize < 10000000) { // проверка на общий размер всех файлов. Многие почтовые сервисы не принимают вложения больше 10 МБ
    mail($to, $subject, $message, $headers);
    echo $_POST['nameFF'].', Ваше сообщение получено, спасибо!';
  } else {
    echo 'Извините, письмо не отправлено. Размер всех файлов превышает 10 МБ.';
  }
}
?>


I know that using ajax you can do what I want, but alas, I don’t have enough knowledge ... At the end, I want to get this view: a person clicks on the "send" button and a loading animation appears and then the result is displayed. either positive or negative.

So far, there is such a code.
$("#feedback-form").submit(function() {
var str = $(this).serialize();
$.ajax({
type: "POST",
url: "contacts.php",
data: str,
success: function(msg) {
if(msg == 'ok') {
 $(".result").toggleClass("dis"); return false;
}
else {
 $(".notresult").toggleClass("dis"); return false;
}
}
});
return false;
});


But he, as you understand, does not receive msg == 'ok' . And how to convey it - I do not know. Letters leave, but for some reason without files... Tell me, how can I send him msg == 'ok' and not lose the function of sending files?

PS Still the question remains, how to add a loading animation? What line should I put it in?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
IceJOKER, 2015-09-24
@IceJOKER

The answer to all your questions - Freelance Services, cook $$
This is a site where you ask a specific question, not asking you to do something for you! To do this, order the services of a programmer for $$ or contact the form, or teach yourself!

A
Alexander Taratin, 2015-09-25
@Taraflex

Use https://github.com/PHPMailer/PHPMailer to submit.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question