2016-04-20 2 views
0

HTML на странице:улучшить и применить формат лучше блочного кода

<form> 
<input type="hidden" value="New Message" name="New Message" id="subject"> 
    <div class="col-md-3"> 
     <label for="name">Your Name: </label> 
     <span class="your-name"> 
     <input type="text" id="name" size="40" aria-required="true" aria-invalid="false"></span> 
    </div> 
    <div class="col-md-3"> 
     <label for="email">E-Mail: </label> 
     <input type="email" id="email"> 
    </div> 
    <div class="col-md-3"> 
     <label for="message">Tell Us Everything: </label> 
     <textarea cols="40" rows="1" name="message" id="message" ></textarea> 
    </div> 
    <div class="col-md-3"> 
     <div id="button-con"> 
      <input type="submit" value="Submit" id="submit" onClick="return check_values();"> 
      <img src="ajax-loader.gif" alt="Sending ..." style="visibility: hidden;" /> 
     </div> 
    </div> 
</form> 

расслоение плотной файла:

// JavaScript Document 

var http = createRequestObject(); 
var areal = Math.random() + ""; 
var real = areal.substring(2,6); 

function createRequestObject() { 
    var xmlhttp; 
    try { xmlhttp=new ActiveXObject("Msxml2.XMLHTTP"); } 
    catch(e) { 
    try { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");} 
    catch(f) { xmlhttp=null; } 
    } 
    if(!xmlhttp&&typeof XMLHttpRequest!="undefined") { 
    xmlhttp=new XMLHttpRequest(); 
    } 
    return xmlhttp; 
} 

function sendRequest() { 
    var rnd = Math.random(); 
    var name = escape(document.getElementById("name").value); 
    var email = escape(document.getElementById("email").value); 
    var subject = escape(document.getElementById("subject").value); 
    var message = escape(document.getElementById("message").value); 

    try{ 
    http.open('POST', 'http://my-domain.com/form.php'); 
    http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); 
    http.onreadystatechange = handleResponse; 
     http.send('$name='+name+'&email='+email+'&subject='+subject+'&message='+message+'&rnd='+rnd); 
    } 
    catch(e){} 
    finally{} 
} 

function check_values() { 
    var valid = ''; 

    var name = document.getElementById("name").value; 
    var email = document.getElementById("email").value; 
    var subject = document.getElementById("subject").value; 
    var body = document.getElementById("message").value; 
    if(trim(name) == "" || 
     trim(email) == "" || 
     trim(subject) == "" || 
     trim(body) == "") { 
      alert("Please complete all fields"); 
    } else { 
     if(isEmail(email)) { 
      document.getElementById("submit").disabled=true; 
      document.getElementById("submit").value='Please Wait..'; 
      sendRequest(); 
     } else { 
      alert("Email appears to be invalid\nPlease check and try again"); 
      document.getElementById("email").focus(); 
      document.getElementById("email").select(); 
     } 
    } 
} 

function handleResponse() { 
    try{ 
    if((http.readyState == 4)&&(http.status == 200)){ 
     var response = http.responseText; 
     document.getElementById("confirmation").innerHTML = response; 
     document.getElementById("confirmation").style.display =""; 
     } 
    } 
    catch(e){} 
    finally{} 
} 

function isUndefined(a) { 
    return typeof a == 'undefined'; 
} 

function trim(a) { 
    return a.replace(/^s*(S*(s+S+)*)s*$/, "$1"); 
} 

function isEmail(a) { 
    return (a.indexOf(".") > 0) && (a.indexOf("@") > 0); 
} 

PHP:

<?php 
error_reporting(0); 
    $page_title = "Contact Us Form"; 
    $email_it_to = "[email protected]"; 
    $error_message = "Please complete the form first"; 
    $confirmation = "Thank you, your message has been successfully sent."; 
?> 


<?php 
error_reporting(0); 

include 'blah.com/form_config.php'; 

if(!isset($_POST['rnd']) || !isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['subject']) || !isset($_POST['message'])) { 
    echo $error_message; 
    die(); 
} 
    $email_from = $email; 
    $email_subject = "Contact Form: ".stripslashes($subject); 
    $email_message = "Please find below a message submitted by '".stripslashes($name); 
    $email_message .="' on ".date("d/m/Y")." at ".date("H:i")."\n\n"; 
    $email_message .= stripslashes($message); 

    $headers = 'From: '.$email_from."\r\n" . 
    'Reply-To: '.$email_from."\r\n" . 
    'X-Mailer: PHP/' . phpversion(); 

    mail($email_it_to, $email_subject, $email_message, $headers); 

    echo "<b>$confirmation</b>"; 
    die(); 
?> 

код становится все вплоть до изменения текст на кнопку отправки, но не отправляется - любая помощь приветствуется.

Я не могу найти ошибку - я добавил и удалил несколько вещей, как методом проб и ошибок, но не могу показаться, чтобы получить его 100%

+0

Получаете ли вы '$ error_message' от вашего PHP скрипт? В какой момент это происходит точно? – Marcus

+0

Создание лучшего кода для HTML-кода. – Robert

ответ

1

выглядит как простая опечатка: http.send('$name=...

вы $, когда вы должны иметь амперсанд &

Изменение его http.send('&name= в вашем JavaScript (в пределах вашего try{} в функции sendRequest()) должны затем сохранить

if(!isset($_POST['rnd']) || !isset($_POST['name']) || !isset($_POST['email']) || !isset($_POST['subject']) || !isset($_POST['message'])) { 
    echo $error_message; 
    die(); 
} 

с удовлетворительного в вашем PHP, так как $_POST['name'] будет на самом деле быть набора, теперь это считается частью из строки запроса, а остальная часть кода почтовой программы будет выполняться.

+0

Эй, Маркус, я сделал то, что вы предлагали, но он все еще замерзает при переключении текста на кнопке. Он просто говорит «Пожалуйста, подождите ...» на кнопке и не будет прогрессировать - никаких сообщений об ошибках, кроме общего, которое я сделал для кода, если включена отчет об ошибках. –

+0

Какая ошибка возвращается точно? $ Error_message? – Marcus

+0

нет сообщений - просто отправьте кнопку изменения в «Пожалуйста, подождите ...» и остается там, не отправлено электронное письмо –

0

Вам просто нужно изменить следующую строку:

http.onreadystatechange = handleResponse;
http.send ('name =' + name + '& email =' + email + '& subject =' + subject + '& message =' + message + '& rnd =' + rnd);
// удаляем $ из имени при отправке значения переменной имени. }

-2

Извините за поздний ответ, и если проблема решена, это хорошо.

Но простой способ использовать Ajax на мой взгляд:

$.ajax({ 
 
type:'post', 
 
data:'&task=asdasd', 
 
url:'ajax.php', 
 
success:function(response){ 
 
alert(response); 
 
} 
 
})

Надежда это сэкономит время.

0

Я установил его, я просто игнорировать то, что JS пытается отправлять сообщения, как предложил Маркус, вот код необходимо:

$email_from = ($_POST['email']); 
$email_subject = "Contact Form: ".($_POST['subject']); 
$email_name = "Client Name: ".($_POST['name']); 
$email_message = "From Email: ".($_POST['email']); 
$email_message = "Their Message: ".($_POST['message']); 

mail($email_it_to, $email_subject, $email_name, $email_message, $headers);