注意:未定义的索引:"使用Ajax和PHP

Error: "Notice: Undefined index:" with Ajax and PHP

本文关键字:使用 Ajax PHP 未定义 索引 注意 quot      更新时间:2023-09-26

这是我的javascript代码:

$( ".modifica_sore" ).click(function(){
var button = this;
$.ajax({
  type: "POST",
  url: "action/modifica_professori.php",
  data: {               
            nome: $(button).siblings('[name="nome"]').attr("value"),
            cognome: $(button).siblings('[name="cognome"]').attr("value"),
            id: $(button).siblings('[name="id"]').attr("value"),
            modifica_sore: $(button).siblings('[name="modifica_sore"]').attr("value"),
  },
  dataType: "html",
  success: function(msg)
  {
    alert("Aggiunto con successo");
    $("#risultato").html(msg);
  },
  error: function()
  {
    alert("Chiamata fallita, si prega di riprovare...");  callback in caso di fallimento
  }
});
  });

这是我的表单:

echo"<form method='POST'>";
echo"<fieldset>";
echo"<table>";
echo"<tr>";
   echo"<td>Nome</td>";
   echo"<td><input class='nome' name='nome' value='$nome'/></td>";
echo"</tr>";
echo"<tr>";
   echo"<td>Cognome</td>";
   echo"<td><input class='cognome' name='cognome' value='$cognome'/></td>";
echo"</tr>";
echo"<tr>";
   echo"<td></td>";
   echo"<td><input type='hidden' class='id' name='id' value='$id'/></td>";
echo"</tr>";
echo"<tr>";
     echo "<td> <input type='button' name='modifica_sore' class='modifica_sore'  value='Modifica' /> </td>";
    echo "<td> <input type='button' name='modifica_sore' class='modifica_sore' value='Elimina' /> </td>";
echo"</tr>";
echo"</table>";
echo"</fieldset>";
echo"</form>";

如果我不使用Ajax,它的工作,但与Ajax我有这个错误:

Notice: Undefined index: nome in C:'xampp'htdocs'xampp'action'modifica_professori.php on line 8
Notice: Undefined index: cognome in C:'xampp'htdocs'xampp'action'modifica_professori.php on line 9
Notice: Undefined index: id in C:'xampp'htdocs'xampp'action'modifica_professori.php on line 10
Notice: Undefined index: modifica_sore in C:'xampp'htdocs'xampp'action'modifica_professori.php on line 13
Notice: Undefined index: modifica_sore in C:'xampp'htdocs'xampp'action'modifica_professori.php on line 26

在modifica_professor .php中我使用$_POST var:

$nome = $_POST['nome'];
$cognome = $_POST['cognome'];
$id = $_POST['id'];
$_POST['modifica_sore']

但如果没有Ajax,问题是在javascript…:/谢谢你的帮助…

这是因为.modifica_sore按钮没有具有"nome""cognome"名称的<input>元素作为其兄弟姐妹。要获取"nome"的值,您应该使用如下命令:

$(button).closest("table").find('[name="nome"]').val();

没有.modifica_sore的兄弟(),所以表单元素的值不能正确提交。

我建议添加一个id属性的形式,然后使用选择器,如:

nome: $('#formid input[name="nome"]').attr('value')
cognome: $('#formid input[name="cognome"]').attr('value')
...

在您的ajax数据对象。

编辑:

既然你提到你不能修改表单,也许你可以尝试改变选择器像这样:

var form = $(button).parents('form');
...
data: {
  nome: form.find('input[name="nome"]').attr('value'),
  cognome: form.find('input[name="cognome"]').attr('value'),
  ...
},
...