jquery没有将值添加到数据库,readystate = 0和status = 0

时间:2012-04-05 11:27:54

标签: php jquery mysql

我的脚本似乎不起作用。每次我尝试使用表单时,我都会在readystate = 0和status = 0时得到错误。任何帮助将不胜感激。 我有以下表格:

<form action="" method="post" >

    <input type="text" name="name" id="tekst"/><br/>
    <input type="text" name="name" id="autor"/><br/>
    <input type="submit" name="<?php echo $id; ?>" value="Send" id="submit"/>

</form>
<div class="response"></div>

然后,输入字段中的值由以下代码处理:

$("input#submit").click(function(){  
var id = $("input#submit").attr("name");
var autor =  $('input#autor').val();
var tresc = $('input#tekst').val();


$.ajax({
    type: "POST",
    url: "add_comment.php",
    data: 
    {id: id, 
    autor: autor, 
    tresc: tresc}, 
    success: function(data){
        $(".response").text(data);  
    },
   error:function(xhr,err){
    alert("readyState: "+xhr.readyState+"\nstatus: "+xhr.status);
    alert("responseText: "+xhr.responseText);

    }



});
});

这是我的add_comment.php:

<?php
$id = $_POST['id'];
$autor= $_POST['autor'];
$tresc = $_POST['tresc'];

if(isset($id) && isset($autor) && isset($tresc)){
include("db/connection.php");

$zapytanie= "INSERT INTO komentarze(id_ref, autor, tresc) values ('$id', '$autor', '$tresc')";
$wynik = $db->query($zapytanie);
echo "Added";
}else{
    echo "Problem";
}


?>

编辑: id_ref不是auto_increment字段。该脚本在localhost上运行

2 个答案:

答案 0 :(得分:1)

首先,您的表单不正确... name =“name”,class =“。response” ??

<form action="" method="post" >
    <input type="text" name="tekst" id="tekst"/><br/>
    <input type="text" name="autor" id="autor"/><br/>
    <input type="submit" name="id" value="Send" id="submit"/>
</form>
<div class="response"></div>

你的PHP文件应该是“

<?php
$id = $_POST['id'];
$autor= $_POST['autor'];
$tresc = $_POST['tekst'];

if(isset($id) && isset($autor) && isset($tresc)){
include("db/connection.php");

$zapytanie= "INSERT INTO komentarze(id_ref, autor, tresc) values ('$id', '$autor', '$tresc')";
$wynik = $db->query($zapytanie);
echo "Added";
}else{
    echo "Problem";
}
?>

答案 1 :(得分:0)

<form action="add_comment.php" method="post" >

<input type="text" name="tekst" id="tekst"/><br/>
<input type="text" name="autor" id="autor"/><br/>
<input type="submit" name="button" value="Send" id="submit"/>

</form>

在php中它应该是这样的

$id = $_POST['button'];
$autor= $_POST['autor'];
$tresc = $_POST['tekst'];

现在它应该正常工作。以前你犯了一个错误,就是在提交按钮字段中你传递了一个php变量,它可能包含任何东西而且你不知道它是否是动态的。所以你无法通过使用$ _REQUEST ['id']来获得它,因为它可能是这样的东西

$id = 1; or $id = 'dynamic string' ;