2017-01-10 70 views
0

儘管我看到「您的郵件已發送!」提醒,但我的表單仍未提交。誰能告訴我什麼是錯的?這裏是我寫的代碼。我在我的數據庫中有一個名爲消息的表格,用於插入從HTML表單輸入的表單數據。謝謝!使用HTML,Javascript,MySQL和PHP合併提交表單時出錯

HTML文件

<form action="javascript:contactSubmit();" name="front_home_contact"> 
    <div class="front_home_details_field"> 
     <input type="text" placeholder="Full Name" name="home_contact_field" required pattern="[A-z ]+"/> 
    </div> 
    <div class="front_home_details_field"> 
     <input type="text" placeholder="Phone Number" name="home_contact_field" required pattern="0[0-9]{9}" maxlength="10"/> 
    </div> 
    <div class="front_home_details_field"> 
     <input type="email" placeholder="E-mail" name="home_contact_field" required/> 
    </div> 
    <div class="front_home_details_field"> 
     <input type="text" placeholder="Subject" name="home_contact_field" required pattern="[A-z s]+"/> 
    </div> 
    <div class="front_home_details_field" style="height:151px;"> 
     <textarea placeholder="Message" name="home_contact_field" aria-invalid="false" required></textarea> 
    </div> 
    <input type="submit" value="Send" name="home_contact_field"/> 
</form> 

的JavaScript .js文件從Ajax響應

function contactSubmit(){ 

    document.front_home_contact.setAttribute("novalidate","true"); 
    var elems = document.getElementsByName("front_home_contact"); //or 
    var xhrx = (window.XMLHttpRequest)? new XMLHttpRequest(): new activeXObject("Microsoft.XMLHTTP"); 
    var data = new FormData(); 
    data.append("func","insertMsg"); 
    data.append("arg",elems); 
    alert("Your message was sent!"); 
     /*xhrx.onreadystatechange = function(){ 
     if(xhrx.readyState==4 && xhrx.status==200){ 
       reportSection.innerHTML= xhrx.responseText.trim(); 
       httpComplete +=1; 
       if (httpComplete == 3) elem.style.display="block"; 
     } 
     }*/ 
    xhrx.open('post','insertMessages.php',true); 
    xhrx.send(data); 
    for (i = 0; i< elems.length;i++){ 
     elems[i].value=""; 
    } 
} 

PHP文件(insertMessages.php

<?php 
    include "config.php"; 
    $function = $_POST['func']; 
    if ($function == "insertMsg"){ 
     $query = "INSERT INTO `messages`(`SenderName`, `PhoneNumber`, `Email`, `Subject`, `Message`) VALUES ('".$_POST['args'][0]."');"; 
     if(mysqli_query($con,$query)){ 
     echo "<script type='text/javascript'>alert('OK');</script>"; 
     } 
     else{ 
     echo "<script type='text/javascript'>alert('error');</script>"; 
     } 
    } 

?> 
+0

你在做一個AJAX調用或表單提交? –

+1

什麼是$ _POST ['args'] [0]'?這不會是5個值。如果它能起作用,那也可以讓你打開SQL注入。參數。 – chris85

+1

僅供參考,Ajax調用中的PHP警報在PHP中不起作用。 '$ _POST ['args'] [0]'是您傳遞5個佔位符的唯一值 – Thamilan

回答

0

直接無法顯示alert()

定義onreadystatechange並根據您的響應定義您要執行的操作。

直接在php響應中不通過script

通過success/error(如果可能,只需在發送響應中使用JSON),並在接收到響應後,檢查值並執行您想要執行的操作。

一樣,

xhttp.onreadystatechange = function() { 
    if (this.readyState == 4 && this.status == 200) { 
     if(this.responseText=="success"){ 
      alert('OK'); 
     }else{ 
      alert('error'); 
     } 
    } 
};