将表单提交到同一页面而不重新加载

时间:2015-05-16 01:41:21

标签: javascript php jquery html ajax

我正在尝试使用Ajax发送表单而不刷新页面。表单提交到同一页面非常重要,这就是我使用url: 'customer-management?form_sent=yes'

的原因

HTML

<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">    
      <i onclick="$(this).closest(\'form\').submit()" id="' . $get_uncontacted_member->id . '" class="fa fa-phone-square called"></i>
</form>

JS

$('.called').click(function() {
    $.ajax({
        type: 'post',
        url: 'customer-management?form_sent=yes',
        data: $(this).attr('id');
        success: function(r) {
            alert(r);
        } 
    })
})

PHP

if (isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes') { return 'That worked!' }

页面重新加载,我想我做错了什么。

3 个答案:

答案 0 :(得分:2)

您没有正确传递数据。由于您正在执行POST请求,因此不应将数据作为查询字符串传递。而是通过data属性传递它。另外,添加return false;以便表单不会提交。

$.ajax({
    type: 'post',
    url: 'customer-management',
    data: { form_sent: 'yes' },
    success: function(r) {
        alert(r);
    } 
});

return false;

您可以删除此代码:

onclick="$(this).closest(\'form\').submit()"

答案 1 :(得分:1)

您必须return false;甚至onclick,否则浏览器会继续提交表单。

onclick="$(this).closest('form').submit(); return false;"

答案 2 :(得分:1)

试试这个:

<form method="post">
            <i id="<?php echo $get_uncontacted_member->id; ?>" class="fa fa-phone-square called"></i>
    </form>
    <script>
            $('.called').click(function()
            {
                    $.ajax({
                            type   : 'post',
                            url    : 'customer-management',
                            data   : {form_sent: 'yes',id:$(this).attr('id')},
                            success: function(r)
                            {
                                    alert(r);
                            }
                    })
            });
    </script>

PHP:

    <?php
if(isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes')
{
        echo 'That worked!';
        exit;
}
?>