在jQuery表单提交上使用PHP表单验证

时间:2015-03-08 22:05:21

标签: php jquery forms

如何通过jQuery提交表单时使用我的php表单验证?

目前,我在PHP中使用了表单验证设置,但是在提交时没有调用它。因此,我可以提交一份我不想要的空表格。

如何更改此设置以便在提交之前使用我的PHP表单验证?

jquery的

(function() {
$('form').on('submit', function(e) {
    e.preventDefault(); // Disables default action of form submitting
    $.post('create.php', $(this).serialize(), function() { 
        console.log('Submission entered');
        window.location = 'contact_form.html'; // Redirect to contact_form.html
    });
})
})();

PHP

if (!empty($_POST)) {
$nameError = null;
$classError = null;

$name = $_POST['name'];
$class = $_POST['class'];

$valid = true;

// if $_POST['name'] is empty then assign the $nameError with a value
if (empty($name)) {
    $nameError = 'Please enter a name';
}

if (empty($class)) {
    $classError = 'Please enter a class';
}

// If valid execute PDO INSERT
if ($valid) {
    $pdo = Database::connect();
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $sql = "INSERT INTO class(name, class_id) values(?, ?)";
    $query = $pdo->prepare($sql);
    $query->execute(array(
        $name,
        $class
    ));
    Database::disconnect();

1 个答案:

答案 0 :(得分:0)

我会通过向我的脚本发送一个ajax请求来解决这个问题:

$('#your-form').submit(function() {
  // make ajax request
  $.ajax({
    url:'validate.php',
    data:$(this).serialize(),
    success:function(response) {
      // check if validation when ok
      // your script needs to send back a response
      // that tells if the validation passed or not
      // if the form is empty for instance you could either 
      // check it before making the ajax request or
      // perhaps return something in `response` that notifies you of this
      // then you could show an alert or something like that
    }
  });
  return false;
});

另一种方法是使用jquery进行检查,以便在将表单发送到验证脚本之前表单不为空:

$('#your-form').submit() {
  // check so form isn't empty
  $(':input').each(function() {
    if($(this).val() == '')
      // field was empty so return false
      return false;
  });
  // send form data to server
  return true;
});