1

我很不擅长 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
}

?>
4

2 回答 2

6

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

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

于 2013-05-23T17:55:57.697 回答
0

你必须从你的订阅方法中返回 false

您也可以验证电子邮件,如果它无效,您可以通过返回 false停止发送订阅

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

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

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

于 2013-05-23T18:20:18.593 回答