2016-07-31 7 views
-1

페이지를 다시로드하지 않고 양식을 제출하는 방법 아약스를 사용해야한다는 것을 알고 있지만 어떻게해야합니까?페이지를 다시로드하지 않고 양식을 제출하는 방법

HTML 파일 :

<form name='myform' method="post" action="send.php"> 
       <span class="close-btn" id="close">&#10006;</span> 
       <p>Введите свои контактные данные</p> 
       <p>Мы Вам перезвоним</p> 
       <input type="text" name="name" placeholder="Имя" maxlength="30"> 
       <p class="Error" id="Error">Это поле обязательное для заполнения</p> 
       <p class="ErrorTwo" id="ErrorTwo">Некорректный ввод</p> 
       <input type="tel" name="phone" placeholder="Телефон" maxlength="13"> 
       <p class="Error" id="telError">Это поле обязательное для заполнения</p> 
       <p class="ErrorTwo" id="telErrorTwo">Некорректный ввод</p> 
       <input type="submit" value="Отправить заявку" name="save" id="save" disabled> 
       <p>Данные не передаються третьим лицам</p> 
      </form> 

PHP :

<?php 
$ToEmail = '[email protected]'; 
$EmailSubject = 'форма обратной связи'; 
$mailheader = "From: ".$_POST["email"]."\r\n"; 
$MESSAGE_BODY = "Имя: ".$_POST["name"].""; 
$MESSAGE_BODY .= "Телефон: ".$_POST["phone"].""; 
mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); 
?> 

JS :

/------------------- ----------확인--------------------------------------- -/

//validation name 
    document.myform.name.onchange= function() { 
     var name = document.myform.name.value; 
     if (name === "") { 
      document.myform.name.removeAttribute("class", "ready"); 
      document.myform.name.style.border = "1px solid #da3637"; 
      document.getElementById("Error").style.display = "block"; 
      document.getElementById("ErrorTwo").style.display = "none"; 
     } else { 
       document.myform.name.style.border = "1px solid #509d12"; 
       document.getElementById("Error").style.display = "none"; 
       var pattern = new RegExp("^[a-z]+$", "i"); 
       var isValid = this.value.search(pattern) >= 0; 
       if (!(isValid)) { 
        document.myform.name.style.border = "1px solid #da3637"; 
        document.getElementById("ErrorTwo").style.display = "block"; 
        document.myform.name.removeAttribute("class", "ready"); 
       } else { 
        document.getElementById("ErrorTwo").style.display = "none"; 
        document.myform.name.style.border = "1px solid #509d12"; 
        document.myform.name.setAttribute("class", "ready"); 
       } 
     } 
    }; 


    //validation phone 
    document.myform.phone.onchange = function() { 
     var name = document.myform.phone.value; 
     if (name === "") { 
      document.myform.phone.removeAttribute("class", "ready"); 
      document.myform.phone.style.border = "1px solid #da3637"; 
      document.getElementById("telError").style.display = "block"; 
      document.getElementById("telErrorTwo").style.display = "none"; 
     } else { 
       document.myform.phone.style.border = "1px solid #509d12"; 
       document.getElementById("telError").style.display = "none"; 
       var pattern = new RegExp("^\\d+$"); 
       var isValid = this.value.search(pattern) >= 0; 

       if (!(isValid)) { 
        document.myform.phone.style.border = "1px solid #da3637"; 
        document.getElementById("telErrorTwo").style.display = "block"; 
       } else { 
        document.getElementById("telErrorTwo").style.display = "none"; 
        document.myform.phone.style.border = "1px solid #509d12"; 
        document.myform.phone.setAttribute("class", "ready"); 
       } 
      } 
    }; 

    //filling the form 
    document.myform.onchange = function() { 
     var a = document.myform.name.getAttribute("class"); 
     var c = document.myform.phone.getAttribute("class"); 
     if (a === "ready" && c === "ready") { 
      document.getElementById("save").removeAttribute("disabled"); 
      document.getElementById("save").style.cursor = "pointer"; 
      document.getElementById("save").style.opacity = "1"; 
     } 
    }; 
+6

가능한 중복 페이지를 새로 고침하지 않고] (http://stackoverflow.com/questions/18169933/submit-form-without-reloading-page) –

+2

https://developer.mozilla.org/en/docs/AJAX를 참조하십시오. – binariedMe

답변

2

AJAX를 사용하십시오. 당신의 PHP 페이지에서,

function sendForm(formName){ 
     var http = new XMLHttpRequest(); 
     http.open("POST","YourPage.php"); 
     http.send(JSON.encodeForm(document.forms[formName])); 
     http.onreadystatechange = function(){ 
     if(http.readyState == 4 && http.status == 200){ 
      console.log(http.responseText); //PHP page's response handling 
     } 
     } 
    } 
    JSON.encodeForm = function(form){ 
     var array = {}; 
     for (key in form) { 
     var item=form[key]; 
     if(form.hasOwnProperty(key) && item == "[object HTMLInputElement]"){ 
      array[item.name]=item.value; 
     } 
     } 
     return JSON.stringify(array); 
    } 

다음 :

<form name='myForm' onsubmit='event.preventDefault(); sendForm("myForm");'>...</form> 

JS에서 : HTML에서 : 나는 JSON과 같은 양식을 enconding 권하고 싶습니다 [제출 형태의

$input = json_decode(file_get_contents("php://input") , true); 
echo "Saved"; 
0

제 생각에는 더 나은 옵션은 서버 측 파일 (some.php)의 데이터를 확인하고 클라이언트 측 파일에 대한 응답을 반환하는 것입니다.

php code는 다음과 같이됩니다 : 당신의 js 파일에

$var = $_POST['some']; 

if($var (bla bla bla)) 
    { echo 'ok.'; } else { echo 'Error'; } 

응답은 PHP 파일에서 에코 메시지입니다.

jsfiddle

편집 (추가 입력 마스크 정보) : 클라이언트 측 파일에 입력을 확인해야하는 경우

단지 (예를 jquery input mask에 대한) 일부 입력 마스크 라이브러리를 사용합니다. 이것은 자신의 검증 스크립트를 만드는 것보다 훨씬 쉬울 것입니다.

관련 문제