2016-12-02 29 views
0

我有這段代碼,並在測試兩個值插入到mysql數據庫時,它只是不插入任何東西。我是在混合數值還是在我的代碼中存在錯誤?使用一個wamp服務器。發生以下錯誤;無法通過ajax格式插入表格

Undefined index: name in C:\wamp\www\info.php on line 3 
Undefined index: desc in C:\wamp\www\info.php on line 4 

但我試圖玩的價值,並不知道它。

的index.html

<html> 
<head><title></title></head> 
<body> 

<form id="myForm" action="userInfo.php" method="post"> 
Name: <input type="text" name="name" /><br /> 
Age : <input type="text" name="age" /><br /> 
<button id="sub">Save</button> 
</form> 

<span id="result"></span> 

<script src="jquery-1.8.1.min.js" type="text/javascript"></script> 
<script src="my_script.js" type="text/javascript"></script> 
</body> 
</html> 

userinfo.php

<?php 
     include_once('db.php'); 

     $name = $_POST['name']; 
     $age = $_POST['age'];     
     if(mysql_query("INSERT INTO user VALUES('$name', '$age')")) 
      echo "Successfully Inserted"; 
     else 
      echo "Insertion Failed"; 
?> 

的MyScript部分

$("#sub").click(function() { 
$.post($("#myForm").attr("action"), 
     $("#myForm :input").serializeArray(), 
     function(info){ $("#result").html(info); 
    }); 
}); 
$("#myForm").submit(function() { 
    return false; 
}); 

function clearInput() { 
    $("#myForm :input").each(function() { 
     $(this).val(''); 
    }); 
} 

更新:仍然沒有修復。獲取錯誤:

Notice: Undefined index: name in C:\wamp\www\userInfo.php on line 4 

Notice: Undefined index: age in C:\wamp\www\userInfo.php on line 5 
Insertion Failed 
+1

** **危險:您正在使用[**的OBS olete **數據庫API](http://stackoverflow.com/q/12859942/19068),它已從PHP中移除(http://php.net/manual/en/mysql.php)。您應該選擇[現代替代品](http://php.net/manual/en/mysqlinfo.api.choosing.php)。你很容易受到[SQL注入攻擊](http://bobby-tables.com/)**現代的API會使它更容易[防禦](http://stackoverflow.com/questions/60174/最好的方式,以防止SQL注入在PHP)自己從。 – Quentin

+0

1.不要在HTML代碼中混用單引號和雙引號(爲了整潔); 2.不要使用已棄用的'mysql_ *'函數(改用MySQLi/PDO); 3.注意SQL注入攻擊。 – Raptor

回答

-1

您可以分享您正在使用的JavaScript代碼嗎?沒有看到阿賈克斯呼籲,很難提供幫助。

我的兩美分將使用firebug或本地瀏覽器網絡流量觀察器來檢查頭髮送到服務器。你想確保當你運行你的ajax請求時,你傳遞所有的post參數。

另外,還要確保你的Ajax請求的類型是POST和您填寫您的.post的$調用的數據字段,如:

$.post('url_here', { "name": "form_name_value here", "desc" : "desc_for_value_here" }) 

UPDATE 對於serializeArray目標只有表單元素: https://api.jquery.com/serializeArray/

像:

$("#myForm").serializeArray() 
+0

添加了myscript,對不起 –

+0

對於序列化數組,您應該只定位到以下格式:https://api.jquery.com/serializeArray/ –

+0

嘿,爲什麼downvote? –