Pomoc - Szukaj - Użytkownicy - Kalendarz
Pełna wersja: Problem z formularzem i Ajaxem
Forum PHP.pl > Forum > XML, AJAX
maryjan
Witam,

buduję stronę opartą na Bootstrap 3. Podpiąłem do niego plugin bootstrapValidator, który działa super. Posiada on również integrację z Ajaxem jednak mam problem ze spięciem go z formularzem w php.

Czy znajdzie się dobra dusza, która pomoże mi dopiąć formularz? Nie jestem biegły w ajaxie i js'ach uczę się na własnych błędach jednak stanąłem w miejscu i od 2 dni nie mogę nic w tej materii wykminić.

Chodzi o przesłanie ajaxem informacji z formularza i wysłanie ich poprzez php bez przeładowania strony.

HTML

  1. <form class="modalFormContainer">
  2. <div class="form-group">
  3. <input type="text" class="form-control input-lg" id="inputSubjectModal" name="url" placeholder="Your website URL" value="">
  4. </div>
  5. <div class="form-group">
  6. <input type="text" class="form-control input-lg" id="inputSubjectModal" name="email" placeholder="Your Email address" value="">
  7. </div>
  8. <div class="form-group">
  9. <input type="text" class="form-control input-lg" id="inputSubjectModal" name="name" placeholder="Your name (optional)" value="">
  10. </div>
  11. <div class="row">
  12. <div class="form-group">
  13. <div class="col-md-6 control-label"><p>Number of pageviews monthly:</p></div>
  14. <div class="col-md-6 selectContainer">
  15. <select name="reach" class="form-control">
  16. <option value="">Select Traffic</option>
  17. <option value="upto500000">Up to 500 000</option>
  18. <option value="500000-1000000">500 000 - 1 000 000</option>
  19. <option value="1000000-2000000">1 000 000 - 2 000 000</option>
  20. <option value="2000000-5000000">2 000 000 - 5 000 000</option>
  21. <option value="over5000000">over 5 000 000</option>
  22. </select>
  23. </div>
  24. </div>
  25. </div>
  26. <div class="row">
  27. <div class="col-md-6">
  28. <button type="submit" class="btn btn-default input-lg" id="submit">Send Message</button>
  29. </div>
  30. <div class="col-md-6"></div>
  31. </div>
  32. </form>


PHP

  1. <?php
  2. if($_POST)
  3. {
  4. require_once('class.translation.php');
  5. $lang = (isset($_POST["lang"]) && $_POST["lang"] != "") ? $_POST["lang"] : "en";
  6. $translate = new Translator($lang);
  7.  
  8. $to_Email = "pawel.slomka@adtaily.com";
  9. // $to_Email = "jarek@adtaily.pl";
  10.  
  11.  
  12. //check if its an ajax request, exit if not
  13. if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
  14.  
  15. //exit script outputting json data
  16. $output = json_encode(
  17. 'type'=>'error',
  18. 'text' => 'Request must come from Ajax'
  19. ));
  20.  
  21. die($output);
  22. }
  23.  
  24. //check $_POST vars are set, exit if any missing
  25. if(!isset($_POST["name"]) || !isset($_POST["email"]) || !isset($_POST["subject"]) || !isset($_POST["message"]))
  26. {
  27. $output = json_encode(array('type'=>'error', 'text' => $translate->__('error-empty-field')));
  28. die($output);
  29. }
  30.  
  31. //Sanitize input data using PHP filter_var().
  32. $user_Name = filter_var($_POST["name"], FILTER_SANITIZE_STRING);
  33. $user_Email = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
  34. $user_Subject = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
  35. $user_Message = filter_var($_POST["message"], FILTER_SANITIZE_STRING);
  36. $user_Checked = $_POST["send_copy"];
  37.  
  38. //additional php validation
  39. if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
  40. {
  41. $output = json_encode(array('type'=>'error', 'text' => $translate->__('error-email-wrong')));
  42. die($output);
  43. }
  44.  
  45. //proceed with PHP email.
  46. $headers = 'From: '.$user_Email.'' . "\r\n" .
  47. 'Reply-To: '.$user_Email.'' . "\r\n" .
  48. 'X-Mailer: PHP/' . phpversion();
  49.  
  50. $body .= 'Imię: '.$user_Name."\r\n\r\n";
  51. $body .= 'E-mail: '.$user_Email."\r\n\r\n";
  52. $body .= 'Temat: '.$user_Subject."\r\n\r\n";
  53. $body .= 'Wiadomość: '.nl2br($user_Message)."\r\n\r\n";
  54. $body .= 'Wiadomość wysłana z formularza kontakowego na stronie YieldBird';
  55.  
  56.  
  57. // send mail
  58. $sentMail = @mail($to_Email, $user_Subject, $body, $headers);
  59. if( $user_Checked == true )
  60. $sentCopy = @mail($user_Email, $user_Subject, $body, $headers);
  61.  
  62. if(!$sentMail)
  63. {
  64. $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
  65. die($output);
  66. }else{
  67. $output = json_encode(array('type'=>'message', 'text' => $translate->__('success-sent')));
  68. die($output);
  69. }
  70. }
  71. ?>


AJAX
  1. $(document).ready(function() {
  2. $('.contactForm')
  3. .bootstrapValidator({
  4. feedbackIcons: {
  5. valid: 'glyphicon glyphicon-ok',
  6. invalid: 'glyphicon glyphicon-remove',
  7. validating: 'glyphicon glyphicon-refresh'
  8. },
  9. fields: {
  10. name: {
  11. message: 'The username is not valid',
  12. validators: {
  13. notEmpty: {
  14. message: 'The username is required'
  15. },
  16. }
  17. },
  18. email: {
  19. validators: {
  20. notEmpty: {
  21. message: 'The email is required'
  22. },
  23. emailAddress: {
  24. message: 'The input is not a valid email address'
  25. }
  26. }
  27. },
  28. subject: {
  29. validators: {
  30. notEmpty: {
  31. message: 'The subject is required'
  32. }
  33. }
  34. },
  35. message: {
  36. validators: {
  37. notEmpty: {
  38. message: 'The message is required.'
  39. }
  40. }
  41. }
  42. }
  43. })
  44. .on('success.form.bv', function(e) {
  45. // Prevent form submission
  46. e.preventDefault();
  47. ga('send', 'event', 'Message', 'Sent', 'Messages has been sent successfully');
  48. // Get the form instance
  49. var $form = $(e.target);
  50.  
  51. // Get the BootstrapValidator instance
  52. var bv = $form.data('bootstrapValidator');
  53.  
  54. // Use Ajax to submit form data
  55. $.post($form.attr('action'), $form.serialize(), function(result) {
  56. $.ajax({
  57. type: 'POST',
  58. url: 'lib/contact.php',
  59. data: $('.contactForm').serialize(),
  60. success: function () {
  61. alert('form was submitted');
  62. },
  63. dataType: 'json'
  64. })
  65. }, 'json');
  66. });
  67. });
amii
1. Co to za konstrukcja .on('success.form.bv' tu nie powinien być submit ?
2. ga('send', 'event', 'Message', 'Sent', 'Messages has been sent successfully'); - tą funkcję masz zdefiniowaną ? (bo na listingu jej nie ma)
3. Do obiektu formularza odwołujesz się w różny sposób nie masz w nim zdefiniowanej akcji ale przede wszystkim NIE masz w ogóle klasy .contactForm do której się odwołujesz się z poziomu JS.
4. Jeśli po poprawieniu powyższych punktów nie będzie działać to uruchamiasz konsolę i sprawdzasz błędy w zakładkach network i konsola
maryjan
1. konstrukcja ta jest wymagana przez skrypt walidacyjny bootstrapValidator smile.gif

Rozwiązanie znalezione: problem z ajaxem rozwiązany i poprawnie kod powinien wyglądać następująco

  1. .on('success.form.bv', function(e) {
  2. // Prevent form submission
  3. e.preventDefault();
  4. ga('send', 'event', 'Message', 'Sent', 'Messages has been sent successfully');
  5. // Get the form instance
  6. var $form = $(e.target);
  7.  
  8. // Get the BootstrapValidator instance
  9. var bv = $form.data('bootstrapValidator');
  10.  
  11. // Use Ajax to submit form data
  12. $.post($form.attr('action'), $form.serialize(), function(result) {
  13. alert('form was submitted');
  14. }, 'json');
  15. });


2. funkcja "ga" odwołuje się do google analytics, który stwierdziłem, że nie ma sensu tu wklejać. Jest to zdarzenie wywoływane po poprawnym zwalidowaniu formularza, które odnotowuje konwersję.
3. Rzeczywiście, w htmlu dałem zły formularz (ten, który wkleiłem odnosił się do modalowego formularza).
4. rozwiązaniem jest kod, który wkleiłem powyżej, którym podmieniłem błędny JS.
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.