Ajax在空白页面中显示响应

时间:2015-03-18 11:35:03

标签: php jquery ajax

使用ajax提交表单后,返回的结果将显示在新页面上。 chrome控制台几乎在每个元素中都返回一个错误:它不是一个函数验证,但php插入它们并显示在这个新页面中显示的结果。

$(document).ready(function () {
   $('#newsletter').submit(function(e){ 
   var $this     = $(this);
    e.preventDefault();

        $response = $('#response'),
        $mail     = $('#email'),
        testmail  = /^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/,
        hasError  = false;

    $response.find('p').remove();

    if (!testmail.test($mail.val())) {
       $response.html('<p class="error">Please enter a valid email</p>');
        hasError = true;
    }

    if (hasError === false) {

       $response.find('p').remove();
       $response.addClass('loading');

        $.ajax({
            type: "POST",
            dataType: 'json',
            cache: false,
            url: $this.attr('action'),
            data: $this.serialize()
        }).done(function (data) {
            console.log(data);
           $response.removeClass('loading');
           $response.html('<p>'+data.message+'</p>');
        }).fail(function() {
           $response.removeClass('loading');
           $response.html('<p>An error occurred, please try again</p>');
        })
    }


    return false;
   });
});

php code

  <?php

  $host   = "";
  $dbname = "";
  $user   = "";
  $pass   = "";

 $email    = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
 $datetime = date('Y-m-d H:i:s');

try {
$db = new PDO("mysql:host=$host;dbname=$dbname", $user, $pass);

if (empty($email)) {
    $status = "error";
    $message = "The email address field must not be blank";
} else if (!preg_match('/^[^0-9][A-z0-9._%+-]+([.][A-z0-9_]+)*[@][A-z0-9_]+([.][A-z0-9_]+)*[.][A-z]{2,4}$/', $email)) {
    $status = "error";
    $message = "You must fill the field with a valid email address";
} else {
    $existingSignup = $db->prepare("SELECT COUNT(*) FROM signups WHERE signup_email_address='$email'");
    $existingSignup->execute();
    $data_exists = ($existingSignup->fetchColumn() > 0) ? true : false;

    if (!$data_exists) {
        $sql = "INSERT INTO signups (signup_email_address, signup_date) VALUES (:email, :datetime)";
        $q = $db->prepare($sql);
        $q->execute(
            array(
                ':email' => $email,
                ':datetime' => $datetime
        ));

        if ($q) {
            $status = "success";
            $message = "You have been successfully subscribed";
        } else {
            $status = "error";
            $message = "An error occurred, please try again";
        }
    } else {
        $status = "error";
        $message = "This email is already subscribed";
    }
}

$data = array(
    'status' => $status,
    'message' => $message
);

echo json_encode($data);

$db = null;
}
catch(PDOException $e) {
echo $e->getMessage();
 }

显示的错误:未完成不是

中的功能
$response = $('#response'),
$mail     = $('#email'),
var $this     = $(this);

消息显示在空白页面中:

{"status":"success","message":"You have been successfully subscribed"}

解决。现在以另一种方式工作正常,但我想知道错误。 这工作

(function($,window,document,undefined){     &#39;使用严格的&#39;;

var $form = $('#newsletter');
var $response = $('#response');
$form.submit(function (e) {
    var formData = {
        'news' : $('input[name="news"]').val(),
        'email' : $('input[name="email"]').val(),
};
    $.ajax({
        type : 'POST',
        url  : 'news.php',
        data : formData,
        dataType : 'json',
        encode : true
    }).done(function (data) { 
        if (!data.success) {
         $('#response').html(data);
        $response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
        } else { 
           $('#response').html(data);
           $response.html('<div class="alert alert"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');

        }
    }).fail(function (data) {
        response.html('<div class="alert alert-error"><button class="close" data-dismiss="alert">x</button>' + data.message + '</div>');
        // for debug
        console.log(data)
    });

    e.preventDefault();
});
}(jQuery, window, document));

0 个答案:

没有答案