簡體   English   中英

在jQuery表單提交上使用PHP表單驗證

[英]Using PHP form validation on jQuery form submission

通過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();

我可以通過向我的腳本發送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;
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM