[英]Insert data in sql with ajax not working
我正在嘗試使用ajax和php在sql表中插入數據,但是它不起作用。 我的ajax給我的結果像它一樣有效,但是當我看桌子時,里面沒有。 不用ajax就能正常工作,所以我想我的php可以正常工作。
這是代碼:
HTML:
<form action="servico.php?p=cadUsr" method="POST" id="frmCadUsr">
Nome: <input type="text" maxlength="255" name="txtNome" id="txtNome"/>
Idade: <input type="text" maxlength="3" name="txtIdade" id="txtIdade"/>
<input type="submit" value="Enviar"/>
</form>
PHP:
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
switch($passo){
case "cadUsr":
cadUsr();
break;
default:
getRetorno();
break;
}
function getRetorno(){
echo "Este texto foi escrito via PHP";
}
function cadUsr(){
require("dbCon.php");
require("mdl_usuario.php");
$usr = $_POST["txtNome"];
$idade = $_POST["txtIdade"];
$resultado = usuario_cadastrar($con,$usr,$idade);
if($resultado){
echo "Cadastro efetuado com sucesso";
} else {
echo "O cadastro falhou";
}
}
?>
OBS:我需要將帶有url參數的表單動作作為cadUsr傳遞,因此它在php中調用該函數。
AJAX:
window.onload = function(){
var xmlhttp;
var frm = document.querySelector("#frmCadUsr");
var url = frm.getAttribute("action");
var nm = document.querySelector("#txtNome").value;
var idade = document.querySelector("#txtIdade").value;
frm.addEventListener("submit",function(e){
e.preventDefault();
try{
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("POST",url,true);
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//alert("Deu certo");
console.log(xmlhttp.responseText);
}
}
} catch(err){
alert("Ocorreu um erro.<br />"+ err);
}
});
}
PHP函數插入數據:
function usuario_cadastrar($conexao,$nome,$idade){
if($nome == "" && $idade == ""){
return false;
}
$sql = sprintf("insert into usuario (nome,idade) values ('%s',%s)",$nome,$idade);
$resultado = mysqli_query($conexao,$sql);
return $resultado;
}
我認為問題出在這里servico.php?p=cadUsr
。 您使用查詢字符串從表單復制action
屬性。 如果您從中刪除查詢字符串,我認為它將起作用。
侯賽因稱其為主要問題:
這個 :
$passo = (isset($_GET['p'])) ? $_GET['p'] : "";
不管用。 您正在發布帖子,無法獲取GET
變量。
您按value
調用value
,這將導致undefined
並且不會在數據庫中放置任何數據。
xmlhttp.send("txtNome=" + nm + "&txtIdade="+idade + "&p=cadUsr");
因此,刪除value
並將cadUsr
變量添加到send函數中的querystring中。 將PHP更新為:
$passo = (isset($_POST['p'])) ? $_POST['p'] : "";
它將起作用!
您可以通過添加console.log(xmlhttp.responseText);
查看回調代碼console.log(xmlhttp.responseText);
准備狀態成功功能。
另外,發送帖子時,您需要將requestheader content-type
為x-www-form-urlencoded。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.