2014-01-29 36 views
0

我是新來的Ajax概念。在這裏,我試圖將用戶詳細信息(註冊表單)插入到數據庫中。它將數據成功插入數據庫。但是,阿賈克斯是我的問題。表單提交與阿賈克斯錯誤消息

1)如果表單域爲空,我沒有收到任何錯誤消息。你可以看到我的下面的代碼,我已經在post.php頁面上進行了驗證。但是,它不會返回錯誤值。 2)它將空值存儲到數據庫中。 3)如果數據存儲成功我想獲得成功消息&如果數據無法存儲在數據庫中我想獲取錯誤消息。我應該如何做這些事情?

Ajax.js

$(function() { 
     $('form').on('submit', function (e) { 
      $.ajax({ 
      type: 'POST', 
      url: 'post.php', 
      data: $('form').serialize(), 
      success: function(msg) { 
       if(msg=='error_n') 
       { 
        $("#e_name").html('Name required');      
       } 
       if(msg=='error_m') 
       { 
        $("#e_mobile").html('Mobile required'); 
       } 

       //success and error alert 
       if(data="inserted") 
       { 
       alert("insertion success"); 
       } 
       else 
       { 
       alert("falid to insert into database"); 
       } 
      } 
      }); 
     e.preventDefault(); 
     }); 
     }); 

post.php中

<?php 

    include_once('config.php'); 

    $name = trim($_POST["name"]); 
    $mobile = trim($_POST["mobile"]); 

    if($name == "") 
    { 
     echo 'error_n'; 
    } 
    if($mobile == "") 
    { 
     echo 'error_m'; 
    } 

    try 
    { 
     $stmt = $conn->prepare("INSERT INTO sample (Name, Mobile) VALUES (?, ?)"); 
     $conn->errorInfo(); 
     $stmt->bindParam('1', $name, PDO::PARAM_STR); 
     $stmt->bindParam('2', $mobile, PDO::PARAM_STR); 
     $stmt->execute(); 
    } 
    catch(PDOException $e) 
    { 
     'Query failed to insert into database' .$e->getMEssage(); 
    } 

?> 

Homepage.php

<p>register <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a></p> 

<div id="light" class="white_content"> 
    <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a> 
    <form> 
     <input type="hidden" name="form" value="values" /> 
     name : <input name="name" id="name" type="text" /><span id="e_name"></span> <br /> 
     mobile : <input name="mobile" id="mobile" type="text" /><span id="e_mobile"></span> <br /> 
     <input type="submit" value="submit" /> 
    </form> 
</div> 
<div id="fade" class="black_overlay"></div> 

回答

2

後您的錯誤消息重新轉過來,你需要停止腳本執行。您當前的代碼仍會嘗試添加值,因此會覆蓋您的自定義錯誤消息。最有可能的就是你的PHP返回你的異常消息,而這不是你的JavaScript期望的。

if($name == "") 
{ 
    echo 'error_n'; 
    die(); // Stop here 
} 
if($mobile == "") 
{ 
    echo 'error_m'; 
    die(); // Stop here 
} 

此外,當您的數據庫插入成功時,請添加echo 'inserted';

+0

現在它沒有在db中存儲空值。沒關係。謝謝......但是,顯示成功和失敗的信息是我的問題之一。我沒有正確地獲得成功和失敗的消息。當空字段提交到數據庫時,它總是提醒'插入成功'。如果用戶提交空數據,它應該顯示所需的值。但它沒有.. – Karuppiah

+0

該行爲是不可能與該代碼。它應該返回'error_n',並且會被javascript捕獲。你可以檢查螢火蟲當你留下一些空的東西時,PHP返回JavaScript的值是什麼? –