Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: [JavaScript][AJAX][PHP]Ajax contact-form, które nie działa w tle
Forum PHP.pl > Forum > Przedszkole
followc
Witam, zrobiłem zgodnie z instrukcjami contact-form z użyciem AJAXu. Po drobnych poprawkach pięknie maile wysyła, lecz nie tak jakbym chciał- w tle, tylko przekierowuje do strony mailer.php, gdzie wyświetla się komunikat o sukcesie. Mój niski poziom doświadczenia nie pozwala mi znaleźć błedu. Pomocy!



index.html
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <title>AJAX Contact Form Demo</title>
  5.  
  6. <link rel="stylesheet" href="style.css">
  7. </head>
  8. <div id="page-wrapper">
  9. <h1>AJAX Contact Form Demo</h1>
  10.  
  11. <div id="form-messages"></div>
  12.  
  13. <form id="ajax-contact" method="post" action="mailer.php">
  14. <div class="field">
  15. <label for="name">Name:</label>
  16. <input type="text" id="name" name="name" required>
  17. </div>
  18.  
  19. <div class="field">
  20. <label for="email">Email:</label>
  21. <input type="email" id="email" name="email" required>
  22. </div>
  23.  
  24. <div class="field">
  25. <label for="message">Message:</label>
  26. <textarea id="message" name="message" required></textarea>
  27. </div>
  28.  
  29. <div class="field">
  30. <button type="submit">Send</button>
  31. </div>
  32. </form>
  33. </div>
  34.  
  35. <script src="jquery-2.1.0.min.js"></script>
  36. <script src="app.js"></script>
  37. </body>
  38. </html>



mailer.php
  1. <?php
  2. // My modifications to mailer script from:
  3. // <a href="http://blog.teamtreehouse.com/create-ajax-contact-form" target="_blank">http://blog.teamtreehouse.com/create-ajax-contact-form</a>
  4. // Added input sanitizing to prevent injection
  5.  
  6. // Only process POST reqeusts.
  7.  
  8. $from='brydz@szlem.edu.pl';
  9. if ($_SERVER["REQUEST_METHOD"] == "POST") {
  10. // Get the form fields and remove whitespace.
  11. $name = strip_tags(trim($_POST["name"]));
  12. $name = str_replace(array("\r","\n"),array(" "," "),$name);
  13. $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
  14. $message = trim($_POST["message"]);
  15.  
  16. // Check that data was sent to the mailer.
  17. if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
  18. // Set a 400 (bad request) response code and exit.
  19. http_response_code(400);
  20. echo "Oops! There was a problem with your submission. Please complete the form and try again.";
  21. }
  22.  
  23. // Set the recipient email address.
  24. // FIXME: Update this to your desired email address.
  25. $recipient = "hello@example.com";
  26.  
  27. // Set the email subject.
  28. $subject = "New contact from $name";
  29.  
  30. // Build the email content.
  31. $email_content = "Name: $name\n";
  32. $email_content .= "Email: $email\n\n";
  33. $email_content .= "Message:\n$message\n";
  34.  
  35. // Build the email headers.
  36. $email_headers = "From: $name <$email>";
  37.  
  38. // Send the email.
  39. if (mail($recipient, $subject, $email_content, $from)) {
  40. // Set a 200 (okay) response code.
  41. http_response_code(200);
  42. echo "Thank You! Your message has been sent.";
  43. } else {
  44. // Set a 500 (internal server error) response code.
  45. http_response_code(500);
  46. echo "Oops! Something went wrong and we couldn't send your message.";
  47. }
  48.  
  49. } else {
  50. // Not a POST request, set a 403 (forbidden) response code.
  51. http_response_code(403);
  52. echo "There was a problem with your submission, please try again.";
  53. }
  54.  
  55. ?>



app.js
  1. $(function() {
  2.  
  3. // Get the form.
  4. var form = $('#ajax-contact');
  5.  
  6. // Get the messages div.
  7. var formMessages = $('#form-messages');
  8.  
  9. // Set up an event listener for the contact form.
  10. $(form).submit(function(e) {
  11. // Stop the browser from submitting the form.
  12. e.preventDefault();
  13.  
  14. // Serialize the form data.
  15. var formData = $(form).serialize();
  16.  
  17. // Submit the form using AJAX.
  18. $.ajax({
  19. type: 'POST',
  20. url: $(form).attr('action'),
  21. data: formData
  22. })
  23. .done(function(response) {
  24. // Make sure that the formMessages div has the 'success' class.
  25. $(formMessages).removeClass('error');
  26. $(formMessages).addClass('success');
  27.  
  28. // Set the message text.
  29. $(formMessages).text(response);
  30.  
  31. // Clear the form.
  32. $('#name').val('');
  33. $('#email').val('');
  34. $('#message').val('');
  35. })
  36. .fail(function(data) {
  37. // Make sure that the formMessages div has the 'error' class.
  38. $(formMessages).removeClass('success');
  39. $(formMessages).addClass('error');
  40.  
  41. // Set the message text.
  42. if (data.responseText !== '') {
  43. $(formMessages).text(data.responseText);
  44. } else {
  45. $(formMessages).text('Oops! An error occured and your message could not be sent.');
  46. }
  47. });
  48.  
  49. });
  50.  
  51. });




Turson
Na samym końcu $(form).submit(function(e){ daj return false
followc
wciąż to samo. rozumiem, że na samym końcu to tu:
  1. $(form).submit(function(e) {
  2. // Stop the browser from submitting the form.
  3. e.preventDefault();
  4.  
  5. // Serialize the form data.
  6. var formData = $(form).serialize();
  7.  
  8. // Submit the form using AJAX.
  9. $.ajax({
  10. type: 'POST',
  11. url: $(form).attr('action'),
  12. data: formData
  13. })
  14. .done(function(response) {
  15. // Make sure that the formMessages div has the 'success' class.
  16. $(formMessages).removeClass('error');
  17. $(formMessages).addClass('success');
  18.  
  19. // Set the message text.
  20. $(formMessages).text(response);
  21.  
  22. // Clear the form.
  23. $('#name').val('');
  24. $('#email').val('');
  25. $('#message').val('');
  26.  
  27. })
  28. .fail(function(data) {
  29. // Make sure that the formMessages div has the 'error' class.
  30. $(formMessages).removeClass('success');
  31. $(formMessages).addClass('error');
  32.  
  33. // Set the message text.
  34. if (data.responseText !== '') {
  35. $(formMessages).text(data.responseText);
  36. } else {
  37. $(formMessages).text('Oops! An error occured and your message could not be sent.');
  38. }
  39. });
  40. return false;
  41. });
Turson
var form = $('#ajax-contact');
$(form).submit(function(e)

jak dla mnie to się kupy nie trzyma i form powinien być
var form = '#ajax-contact';
followc
ta edycja niewiele zmieniła- działa tak jak działało przed nią. wysyła wiadomości, ale wciąż przekierowuje na mailer.php. Nie powinienem jakoś zedytować index.html, żeby zawierał w sobie mailer.php?
Turson
Daj jakiś alert w tej funkcji JS, bo nie wiadomo czy to się w ogóle wykonuje. Możliwe, że powinieneś był umieścić skrypty js w nagłówku dokumentu.
followc
wrzuciłem alerty w dwoch miejscach i faktycznie nic nie 'alertuje'. to nie jest tak, że ta funkcja odpowiedzialna jest za wysyłkę? jakim cudem więc maile dochodzą na moja skrzynkę?

  1. $(form).submit(function(e) {
  2. // Stop the browser from submitting the form.
  3. e.preventDefault();
  4.  
  5. // Serialize the form data.
  6. var formData = $(form).serialize();
  7.  
  8. // Submit the form using AJAX.
  9. $.ajax({
  10. type: 'POST',
  11. url: $(form).attr('action'),
  12. data: formData
  13. })
  14. .done(function(response) {
  15. // Make sure that the formMessages div has the 'success' class.
  16. $(formMessages).removeClass('error');
  17. $(formMessages).addClass('success');
  18.  
  19. // Set the message text.
  20. $(formMessages).text(response);
  21.  
  22. // Clear the form.
  23. $('#name').val('');
  24. $('#email').val('');
  25. $('#message').val('');
  26. alert('xx');
  27. //return false;
  28. })
  29. .fail(function(data) {
  30. // Make sure that the formMessages div has the 'error' class.
  31. $(formMessages).removeClass('success');
  32. $(formMessages).addClass('error');
  33.  
  34. // Set the message text.
  35. if (data.responseText !== '') {
  36. $(formMessages).text(data.responseText);
  37. } else {
  38. $(formMessages).text('Oops! An error occured and your message could not be sent.');
  39. }
  40. });
  41. alert('xx');
  42. return false;
  43. });
Turson
Maile dochodzą, bo formularz przekierowuje do mailer.php który wysyła wiadomość. Odpal konsolę w przeglądarce i podejrzyj
followc
Failed to load resource: the server responded with a status of 404 (Not Found)

w pliku zawierającym jQuery i pliku app.js. To mój serwer nie chce współpracować? Mogę temu jakoś zaradzić?
To jest wersja lo-fi głównej zawartości. Aby zobaczyć pełną wersję z większą zawartością, obrazkami i formatowaniem proszę kliknij tutaj.
Invision Power Board © 2001-2025 Invision Power Services, Inc.