Formularz kontaktowy php (ajax) z załącznikiem, nie dochodzi załącznik

0

Mam formularz po licznych poprawkach, ale nadal nie chodzi, znaczy załącznik nie dochodzi. I tu jest problem. Proszę o wskazówki.
index.html

<div class="container">
<div class="row">
<div class="col-xl-8 offset-xl-2 py-5">

<form id="contact-form" method="post" action="contact.php" role="form">

    <div class="messages"></div>

    <div class="controls">

        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_name">Imię</label>
                    <input id="form_name" type="text" name="name" class="form-control" placeholder="Proszę podać imię *" required="required" data-error="Firstname is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_lastname">Nazwisko</label>
                    <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Proszę podać nazwisko *" required="required" data-error="Lastname is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_email">Email *</label>
                    <input id="form_email" type="email" name="email" class="form-control" placeholder="Proszę podać email *" required="required" data-error="Valid email is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
                <div class="col-md-6">
                <div class="form-group">
                    <label for="form_message">Numer oferty</label>
                    <input id="form_message" type="text" name="message1" class="form-control" placeholder="Proszę podać numer oferty *" required="required" data-error="Valid email is required.">
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_phone">Telefon</label>
                    <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Proszę podać telefon">
                    <div class="help-block with-errors"></div>
                </div>
            </div>

            <div class="col-md-6">
                <div class="form-group">
                    <label for="form_file">File</label>
                    <input id="form_file" type="file" name="attachment" class="form-control" placeholder="File"/>
                    <div class="help-block with-errors"></div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <div class="form-group">
                    <label for="form_message">Wiadomość</label>
                    <textarea id="form_message" name="message" class="form-control" placeholder="Wpisz tekst wiadomości *" rows="4" required="required" data-error="Please,leave us a message."></textarea>
                    <div class="help-block with-errors"></div>
                </div>
            </div>
            <div class="col-md-12">
                <input type="submit" class="btn btn-success btn-send" value="Wyślij wiadomość">
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                <p class="text-muted"><strong>*</strong> Pola wymagane</p>
            </div>
        </div>
    </div>

</form>


</div>
 <!-- /.8 -->

</div>
 <!-- /.row-->
 
</div>
    <!-- /.container-->

contact.php

<?php
/*
 *  CONFIGURE EVERYTHING HERE
 */

// an email address that will be in the From field of the email.
$from = 'demo <[email protected]>';

// an email address that will receive the email with the output of the form
$sendTo = 'demo <[email protected]>';

// subject of the email
$subject = 'Zgloszenie kandydatury';

// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Imię', 'surname' => 'Nazwisko', 'phone' => 'Telefon', 'email' => 'Email', 'message' => 'Wiadomość', 'message1' => 'Numer oferty'); 

// message that will be displayed when everything is OK :)
$okMessage = 'Dziękujemy za zgłoszenie kandydatury';

// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later';

/*
 *  LET'S DO THE SENDING
 */

// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');

    $emailText = "Zgłoszono kandydaturę\n=============================\n";

    foreach ($_POST as $key => $value) {
        // If the field exists in the $fields array, include it in the email 
        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

    // All the neccessary headers for the email.


if(!isset($_FILES['attachment']) || !is_uploaded_file($_FILES['attachment']['tmp_name'])) {
  throw new \Exception('CV missing');
}

$content = file_get_contents($_FILES['attachment']['tmp_name']);
$content = chunk_split(base64_encode($content));

$separator =  sha1(time() . rand());

$headers = array("From: {$from}",
  "Reply-To: {$from}",
  "Return-Path: {$from}",
  "MIME-Version: 1.0",
  "Content-Type: multipart/mixed; boundary=\"{$separator}\"",
  "Content-Transfer-Encoding: 7bit",
  "This is a MIME encoded message."
);

$body = array("--{$separator}",
   "Content-Type: text/plain; charset=\"iso-8859-1\"",
   "Content-Transfer-Encoding: 8bit",
   $emailText,
  "--{$separator}",
  "Content-Type: application/octet-stream; name=\"cv.pdf\"",
  "Content-Transfer-Encoding: base64",
  "Content-Disposition: attachment",
  $content,
  "--{$separator}--"
);

mail($sendTo, $subject, implode("\r\n", $body), implode("\r\n", $headers));



    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}

// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
// else just display the message
else {
    echo $responseArray['message'];
}

contact.js

$(function () {

    // init the validator
    // validator files are included in the download package
    // otherwise download from http(tu:i // bo pierwszy post i linku nie mozna bylo wkleic a taki byl tu)1000hz.github.io/bootstrap-validator

    $('#contact-form').validator();


    // when the form is submitted
    $('#contact-form').on('submit', function (e) {

        // if the validator does not prevent form submit
        if (!e.isDefaultPrevented()) {
            var url = "contact.php";

            // POST values in the background the the script URL
            $.ajax({
                type: "POST",
                url: url,
                data: $(this).serialize(),
                success: function (data)
                {
                    // data = JSON object that contact.php returns

                    // we recieve the type of the message: success x danger and apply it to the 
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;

                    // let's compose Bootstrap alert box HTML
                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                    
                    // If we have messageAlert and messageText
                    if (messageAlert && messageText) {
                        // inject the alert to .messages div in our form
                        $('#contact-form').find('.messages').html(alertBox);
                        // empty the form
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
});
3

Coś Ci się udało zdebugować? Masz jakieś błędy, czy po prostu nie działa i już?

0

Wiadomość dochodzi, załącznik nie. Wysyłanie na stronie wygląda prawidłowo, ale załącznik nie dociera.
Nie działa.

2

Nie używaj phpowej funkcji mail(). To jest bardzo podstawowy sposób wysyłki maili, nie zaleca się go do używania. Zmień to na np. phpmailera.

0

Nikt tu nie może mi pomóc w przedstawionym temacie?
Gdzie mogę znaleźć kody do phpmailera z załącznikiem w takim razie?

3
Dariusz Zdz napisał(a):

Nikt tu nie może mi pomóc w przedstawionym temacie?

Gdzie mogę znaleźć kody do phpmailera z załącznikiem w takim razie?

Przecież właśnie pomagamy. To Ty nie jesteś pomocny, bo jedyne co napisałeś, to to, że nie działa.

A gdzie znaleźć? Np. na githubie: https://github.com/PHPMailer/PHPMailer. Wystarczy wpisać phpmailer w Google, serio, to nie boli...

0

Zwróć też uwagę na ograniczenia przysłania mailem plików np. z uwagi na typ pliku lub jego rozmiar.

0

PHP Mailer, ok jest na githubie, tak wiem i widzialem wczesniej tylko, ze z tego githuba cieżko mi cokolwiek wyczytac.

0
Dariusz Zdz napisał(a):

PHP Mailer, ok jest na githubie, tak wiem i widzialem wczesniej tylko, ze z tego githuba cieżko mi cokolwiek wyczytac.

Masz tam przecież czarno na białym co i jak, włącznie z dodawaniem załącznika...

0

ok, wiec troche dzis poczytam i sie poucze, postaram sie wyciagnac wnioski ze wskazowek, najwyzej jutro dam znać, poki co dzieki

0

Funkcja serializująca w js raczej nie dołączy załącznika, musisz użyć obiektu FormData

var formData = new FormData();
formData.append('attachment', $('#form_file')[0].files[0]);

//lub 

var form = $('#contact-form')[0]; 
var formData = new FormData(form);

$.ajax({
       type: "POST",
       url: url,
       data : formData,
      ...
})
0

OK, dzieki, zaraz, moze juz jutro zobacze i sie pobawie, bo te sprawy z phpmailerem i githubem cos mi nie wychodza. Wole te swoje zapiski i w tym sie bawic i czegos przy okazji sie nauczyc tez. Napisze oczywiscie, jak mi poszlo.

0

Nie wiem czy dobrze zrozumialem. Poprawilem moj contact.js, ale nic to nie dało w dalszym ciągu załącznik nie dochodzi z wyslana wiadomoscia. Teraz wygląda tak:

$(function () {

    // init the validator
    // validator files are included in the download package
    // otherwise download from http://1000hz.github.io/bootstrap-validator

    $('#contact-form').validator();


    // when the form is submitted
    $('#contact-form').on('submit', function (e) {

        // if the validator does not prevent form submit
        if (!e.isDefaultPrevented()) {
            var url = "contact.php";

            // POST values in the background the the script URL
            $.ajax({
                type: "POST",
                url: url,
                data : formData,
                success: function (data)
                {
                    // data = JSON object that contact.php returns

                    // we recieve the type of the message: success x danger and apply it to the 
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;
					var formData = new FormData();
                    formData.append('attachment', $('#form_file')[0].files[0]);

                    // let's compose Bootstrap alert box HTML
                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>' + messageText + '</div>';
                    
                    // If we have messageAlert and messageText
                    if (messageAlert && messageText) {
                        // inject the alert to .messages div in our form
                        $('#contact-form').find('.messages').html(alertBox);
                        // empty the form
                        $('#contact-form')[0].reset();
                    }
                }
            });
            return false;
        }
    })
});

0

Przecież Ty dodajesz obiekt formData w funkcji, która zwraca sukces, a nie w parametrze do wysłania.
Weź sobie w ogóle sprawdź posta w php, jakie dostajesz dane, upewnij się, że w poście nie masz pliku.
Sprawdzaj sobie zawsze, najpierw co dostajesz z requesta, za nim zaczniesz dalej działac z danymi.

0

nie moge dojsc do tego, ktos pomoze?

1 użytkowników online, w tym zalogowanych: 0, gości: 1