防止表单刷新页面Javascript

时间:2013-05-23 17:55:02

标签: php javascript jquery ajax

我在javascript上非常糟糕,我正在尝试进行AJAX调用,但是我从表单中获取了我的值,它只是刷新页面,甚至无法观察AJAX调用是否成功。

这是我的HTML:

<form class="form-horizontal" id="subscribe-form" name="subscribe-form" onSubmit="return subscribe();">
    <fieldset>
        <p>
                         Subscribe
        </p>
        <div class="input-prepend input-append">
           <input name="subscribwEmail" class="span2" id="InputEmail" type="email" placeholder="Email">
           <input type="submit" class="btn btn-inverse" />
        </div>
    </fieldset>
</form>

JS:

function subscribe() {
    var emailForm = $('#subscribwEmail').val();
    $('#subscribe-form').hide(); // hide email form
$('#subscribeDiv').prepend('<img id="process" src="http://www.mydomain.com/assets/img/process.gif" />')

$.ajax({
    type: "POST", 
    url: "../../actions/ajax-subscribe.php",
    data: {
        email: emailForm
    },
    dataType: "json",
    success: function (data) {
        if (data[0] == 1) { // test if response was 1 or 2

            $('#process').hide(); // hide img

            $('#subscribeDiv').append('<p>Thank you for subscribing!</p>');
        } else {

            $('#process').hide(); // hide img

            $('#subscribeDiv').append('<p>There was an error subscribing the email.</p>');
        }
    }
})

};

Ajax的subscribe.php

<?php
include ('phpfunctions.php');

$email = $_POST['email'];
$ip = $_SERVER['REMOTE_ADDR'];
$con = mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME) or die('ERROR WITH SQL CONNECTION CONTACT ADMIN');

$email = cleanString($con, $email);

$query = "INSERT INTO `subscribers` (`email`, `ip`) VALUES ('$email', '$ip');";

if ($result = mysqli_query($con, $query)) {

echo json_encode(1); // all ok inserted
} else {

echo json_encode(0); // failed
}

?>

2 个答案:

答案 0 :(得分:6)

您不会取消点击事件,因此表单会提交。

return false;添加到subscribe方法的末尾。

答案 1 :(得分:0)

您必须订阅方法返回错误

此外,您可以验证电子邮件,如果无效,您可以停止发送订阅返回false

您还可以停用提交按钮。 (formObj带有subscribe参数)

        formObj.submit.disabled = true;
        formObj.submit.value = 'Log In...';

但如果出现问题,你必须启用它。