使用表单密钥和AJAX提交表单

时间:2012-01-09 19:10:02

标签: php ajax forms

全部, 我有以下类,以便检查通过HTML创建的表单是否有效,并且如果有人执行ctrl + F5等,也会阻止表单提交两次。这是执行该操作的类:

<?php
class Form_Key
{

protected $oldKey;

public function __construct()
{

    // Ensure we have an available session
    if ( NULL == session_id() )
    {
        session_start();
    }

    // Grab our former key for validation
    if ( isset( $_SESSION['form_key'] ) )
    {
        $this->oldKey = $_SESSION['form_key'];
    }

    // Assign the new key
    $_SESSION['form_key'] = md5( uniqid( mt_rand(), TRUE ) );

}

public function isValid()
{
    return 'POST' == $_SERVER['REQUEST_METHOD']
        && isset( $_POST['form_key'] )
        && '' != trim( $_POST['form_key'] )
        && '' != trim( $this->oldKey )
        && $_POST['form_key'] === $this->oldKey;
}

public function getKey()
{
    return $_SESSION['form_key'];
}

public function getOldKey()
{
    return $this->oldKey;
}

public function render()
{
    return '<input type="hidden" name="form_key" value="' . $_SESSION['form_key'] . '" />';
}

public function __toString()
{
    return $this->render();
}

}  
?>

然后我有一个看起来像这样的表格:

require "form_key.php";
$form_key = new Form_Key;
<form action="about.php" method="post" name="create_memory" id="create_memory">
<input type="text" value="" id="lamecaptcha" name="lamecaptcha" />
<input type="text" value="" id="person_name" name="person_name" />
<?php echo $form_key; ?>
</form>

在验证方面(save_memory.php)我做了类似这样的事情:

require "form_key.php";
$form_key = new Form_Key;
if(isset($_POST) && $form_key->isValid()){
    echo "It is ok to submit";
}else{
    echo "Something went wrong";
}

如果我不通过ajax提交表单,所有这一切都很有效,但如果我通过AJAX提交表单,它总会给我一些错误的错误。以下是我通过AJAX提交表单的方式:

person_name = $("input#person_name").val();
memory = $("input#memory").val();
form_key = $("input#form_key").val();
var html_memory = $.ajax({
type: "POST",
url: "save_memory.php",
data: "person_name=" + person_name + "&memory=" + memory + "&form_key=" + form_key,
async: false
}).responseText;

alert(html_memory);

任何想法为什么会这样,我怎样才能通过AJAX提交表单?非常感谢你提前!

1 个答案:

答案 0 :(得分:1)

键输入的Jquery选择器无效。您必须将form_key的ID放入其中,如下所示:

 return '<input id="form_key" type="hidden" name="form_key" value="' . $_SESSION['form_key'] . '" />';

[编辑]

此外,您还必须调用生成输入的函数:

<?php echo $form_key->render(); ?>