2015-03-08 110 views
0

如何在通過jQuery提交表單時使用我的php表單驗證?在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(); 
+0

由於php在服務器上運行,這是不可能的(您必須發送表單到服務器以處理它)。你可以爲你的PHP腳本或類似的東西做一個Ajax請求。 – Cyclonecode 2015-03-08 22:07:27

+0

對於您的代碼,始終設置爲true無效嗎? – helloworld 2015-03-08 22:08:43

+0

@Cyclone那麼處理這個問題的理想方法是什麼?使用客戶端的jQuery驗證插件或?或者這是不是很理想用這種方式提交表單? – 2015-03-08 22:10:17

回答

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; 
}); 
+0

您希望使用哪種解決方案? – Cyclonecode 2015-03-09 23:25:51