2015-11-27 4 views
-4

скриншота ошибкиИспользование Ajax с моей контактной формой

enter image description here

Эй я пытаюсь создать контактную форму для моей страницы контактов. Кажется, я не могу получить форму для отправки мне электронной почты входов от формы при нажатии кнопки «Отправить форму».

... Это мой HTML

<form class="send-with-ajax" method="post" action="send_form_email.php"> 

      <div class="row"> 
       <div class="three columns alpha"> 
        <label for="first_name">First Name <span>required</span></label>     
        <label for="last_name">Last Name <span>required</span></label> 
       </div> 
       <div class="seven columns omega"> 
        <input type="text" required placeholder="First Name" id="first_name" name="name"> 
        <input type="text" required placeholder="Last Name" id="last_name" name="name"> 
       </div> 
      </div> 

      <div class="row"> 
       <div class="three columns alpha"> 
        <label for="email">Your Email <span>email required</span></label> 
       </div> 
       <div class="seven columns omega"> 
        <input type="email" required placeholder="[email protected]" id="email" name="email"> 
       </div> 
      </div> 

      <div class="row">   
       <div class="three columns alpha"> 
        <label for="comments">Message</label> 
       </div> 
       <div class="seven columns omega"> 
        <textarea placeholder="Enter you message, and please include your artist name. you can put either or choose between Pervis or Duijuan" id="comments" name="comments"></textarea> 
       </div> 
      </div> 

      <div class="seven columns offset-by-three"> 
       <button type="submit">Submit Form</button> 
       <div class="ajax-response"></div> 
      </div> 
</form> 

... Это мой Javascript

$("form.send_form_email").submit(function(e) { 
    e.preventDefault(); 
    var form = $(this), 
    validationErrors = false; 

$('.form-error-msg').remove(); 

form.find("input[type='email'], input[required]").each(function(index){ 
     var inputValue = $(this).val(), 
      inputRequired = $(this).attr('required'), 
      inputType = $(this).attr('type'); 

$(this).removeClass('form-error'); 
     if(inputRequired && inputValue == '') { 

$(this).after('<div class="form-error-msg">Please fill out this field.</div>'); 

$(this).addClass('form-error'); 
      validationErrors = true; 
     } else if(inputType == 'email' && !isValidEmail(inputValue)) { 

$(this).after('<div class="form-error-msg">Please enter an email address.</div>'); 
      $(this).addClass('form-error'); 
      validationErrors = true; 
     } 
    }); 

if (!validationErrors) { 
     form.find('button:submit, input:submit').html('Sending...'); 
     form.find('.ajax-response').empty(); 
     $.post(form.attr('action'), form.serialize(), 
      function(data) { 
       if (data.bFormSent) { 
        form.find('.ajax-response').empty().html(data.aResults[0]); 
        form.find('button:submit, input:submit').html('Submit Form'); 
        form.find('#email, #first_name, #last_name #comments').val(''); 
       } else { 
        form.find('.ajax-response').empty().wrapInner('<div class="form-error-msg"></div>'); 
        form.find('.ajax-response div').html(data.aErrors[0]); 
        form.find('button:submit, input:submit').html('Try Again'); 
       } 
      }, 'json'); 
    } 
}); 

... Это мой PHP

<?php 

if(isset($_POST['email'])) { 

// EDIT THE 2 LINES BELOW AS REQUIRED 

$email_to = "myemail"; 

$email_subject = "this subject"; 

function died($error) { 

    // your error code can go here 

    echo "We are very sorry, but there were error(s) found with the form you submitted. "; 

    echo "These errors appear below.<br /><br />"; 

    echo $error."<br /><br />"; 

    echo "Please go back and fix these errors.<br /><br />"; 

    die(); 

} 

// validation expected data exists 

if(!isset($_POST['first_name' ]) || 

    !isset($_POST['last_name']) || 

    !isset($_POST['email']) || 

    !isset($_POST['telephone']) || 

    !isset($_POST['comments'])) { 

    died('We are sorry, but there appears to be a problem with the form you submitted.');  

} 

$first_name = $_POST['first_name']; // required 

$last_name = $_POST['last_name']; // required 

$email_from = $_POST['email']; // required 

$telephone = $_POST['telephone']; // not required 

$comments = $_POST['comments']; // required 

$error_message = ""; 

$email_exp = '/^[A-Za-z0-9._%-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; 

if(!preg_match($email_exp, $email_from)) { 

$error_message .= 'The Email Address you entered does not appear to be valid.<br />'; 
} 
$string_exp = "/^[A-Za-z .'-]+$/"; 
if(!preg_match($string_exp,$first_name)) { 

$error_message .= 'The First Name you entered does not appear to be valid.<br />'; 
} 

if(!preg_match($string_exp,$last_name)) { 

$error_message .= 'The Last Name you entered does not appear to be valid.<br />'; 
} 

if(strlen($comments) < 2) { 

$error_message .= 'The Comments you entered do not appear to be valid.<br />'; 
} 

if(strlen($error_message) > 0) { 

died($error_message); 
} 

$email_message = "Form details below.\n\n"; 

function clean_string($string) { 

    $bad = array("content-type","bcc:","to:","cc:","href"); 

    return str_replace($bad,"",$string); 
} 

$email_message .= "First Name: ".clean_string($first_name)."\n"; 

$email_message .= "Last Name: ".clean_string($last_name)."\n"; 

$email_message .= "Email: ".clean_string($email_from)."\n"; 

$email_message .= "Telephone: ".clean_string($telephone)."\n"; 

$email_message .= "Comments: ".clean_string($comments)."\n"; 

// create email headers 

$headers = 'From: '.$email_from."\r\n". 

'Reply-To: '.$email_from."\r\n" . 

'X-Mailer: PHP/' . phpversion(); 

@mail($email_to, $email_subject, $email_message, $headers); 

?> 
+0

Почему вы использовали '@Mail ($ email_to, $ EMAIL_SUBJECT, $ email_message, $ заголовки);' Параметр '@' подавляет все. –

+0

Опишите вашу проблему подробно. Что не работает. Что. Вы получаете сообщения об ошибках. – Steve

+0

@Steve Я не получаю электронные письма от формы, когда я отправляю форму. –

ответ

1

Ах человек! Только сейчас я увидел ваш скриншот. Вы не выполнение PHP-файла с использованием сервера! Вам нужно запустить его с помощью Apache/PHP Server.

How to run php files on my computer

Вы должны запустить веб-сервер (например, Apache) и перейдите к вашему локального хоста, в основном, вероятно, на порт 80.

Что вы действительно должны сделать, это установить дополнительные все-в-одном, например, XAMPP, он связывает Apache, MySQL PHP и Perl (если вы были такими склонен), а также несколько других инструментов, которые работают с Apache и MySQL - плюс кросс-платформа (вот что e 'X' в 'XAMPP' означает).

После установки XAMPP (и есть установщик, поэтому он не должен быть трудно) открыть панель управления для XAMPP, а затем нажмите кнопку «Пуск» кнопки рядом с Apache - обратите внимание, что в приложениях, требующих a , вам также нужно будет запустить MySQL (и вы сможете подключиться к нему через интерфейс phpMyAdmin ). После того, как вы запустили Apache, вы можете найти http://localhost.

Опять же, независимо от того, выбираете ли вы XAMPP (что я бы рекомендовал ), вам просто нужно запустить Apache.

Еще один

Короче:

  1. Установите WAMP

  2. Поместите этот файл в C: \ WAMP \ WWW \ ProjectName \ имя_файла.PHP

  3. Перейти в браузер: http://localhost/ProjectName/filename.php

+0

что изменилось? для OP/будущих посетителей и меня ;-) –

+0

@ Fred-ii- Omg! Извините, я допустил эту ошибку. Я напишу. Я прокомментировал это. См. Выше вопрос. –

+1

См. [Мои комментарии к OP ...] (http://stackoverflow.com/questions/33956000/using-ajax-with-my-contact-form#comment55672008_33956000) –

Смежные вопросы