通过AJAX获取验证错误从PHP [英] Getting validation errors from PHP via AJAX
问题描述
截至目前,我创建了一个简单的联系表单。
As of right now, I have created a simple contact form.
目前,我需要重新加载页面,如果我想验证与PHP的任何东西(我已经具备了客户端验证)。
Currently, I need to reload the page if I want to validate anything with PHP (I already have Client side validation in place).
不过,我想这样做,而不用重新加载我的网页。由于我没有经验与阿贾克斯我被搞糊涂了,所有我在网上看到的例子。
However, I want to do this without reloading my page. Since I have no experience with ajax I was confused by all the examples I saw on the internet.
我也想使用jQuery $。员额()
如果可能的话,但我认为AJAX不相同。
I would also like to use jQuery $.post()
if possible, but I think ajax does the same.
下面是一个简单的标记:
Here is the simple markup:
<form id="myForm" method="POST" action="">
<input name="name" class="<? if($errorsArray['email']) {echo "error";} ?>" type="email" required><br>
<input name="comment" class="<? if($errorsArray['name']) {echo "error";} ?> " type="text" required><br>
<input name="submit" type="submit" value="Send">
</form>
我的PHP:
My PHP:
$requiredFields = array('name', 'comment');
foreach ($requiredFields as $field) {
$errorsArray[$field] = true;
}
我赞同错误的类属性来表示一个错误。然而,这需要我重新加载页面,这是我不想做的事。 (我也做了同样的方式,让本已提交的数据是有错误)。
I echo "error" in the class attribute to signify an error. However, this requires me to reload the page, which I do not want to do. (I also do the same way to keep the already submitted values is there is an error).
我将如何使用Ajax来给每个字段(错误)类的加法:<?code>错误
How would I use ajax to give each field (with errors) the class addition: error
?
如果您需要任何更多的code,我会很乐意给它,只是给我一个评论。
If you need any more code, I will be more than happy to give it, just give me a comment.
推荐答案
首先,我从服务器端开始。
First, I start from the server-side.
由于要通过XHR请求提交表单,服务器应该返回数据作为JSON对象。
Since you want to submit the form via XHR request, the server should return the data as a JSON object.
使用JSON,你可以有一个包含结果
和可能的错误的一个结构化的数据
。
Using JSON, you could have a structured data containing result
and probable errors
.
那么,在您的 PHP文件以该形式将发送请求:
So, in your PHP file to which the form will send the request:
# Check whether the validation was successful
if ($validated === true) {
# Do your logic...
# Insert the posted data into database... etc.
# show success message
$response = array(
'error' => null,
'result' => array(
'message' => "Successfully message..."
)
);
} else {
# Show the error message
$response = array(
# In this case, get_readable_errors() method returns an array
# which contains the 'name' of the invalid fields as key
# and the validation error as value
# e.g.
#
# 'error' = array(
# 'name' => 'Validation error for name field',
# 'comment' => 'Validation error for comment field'
# ),
'error' => $validator->get_readable_errors(),
'result' => null
);
}
# send the output as JSON
echo json_encode($response);
然后,在客户端,你需要prevent默认提交表单。
Then, at the client-side, you need to prevent the default submission of the form.
使用jQuery,您可以使用 .submit()
方法来处理程序绑定到submit事件:
Using jQuery, you could use .submit()
method to bind a handler to the submit event:
var $form = $('#myForm'),
_updateView = function(data, $form) {
data.error === null &&
_showResult(data.result, $form) ||
_showError(data.error, $form);
},
// This function triggers if the ouput data has no error
_showResult = function(result, $form) {
// Clear all error messages
// Remove the old success message
// Insert the Success message
// Reset the form
$form[0].reset();
return true;
},
// This function triggers if the output is an error
_showError = function(error, $form) {
// Clear old success message
// Clear all old errors
// Show the error message of each field
$.each(error, function(field, err) {
$('input[name="'+ field +'"]')
.addClass('error')
// Insert the error message of the relevant field (optional)
.after('<small class="error">'+ err +'</small>');
});
};
在Ajax调用,使用 $。阿贾克斯()
:
$form.submit(function(e) {
/* Prevent the default submission */
e.preventDefault();
$.ajax({
url : 'PHP/file/URL',
type : 'POST',
dataType : 'json', /* <-- Parse the response as JSON object */
data : $form.serialize(),
success: function(data) {
// Update the view
_updateView(data, $form);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(errorMessage); // Optional
}
});
});
希望这有助于。
Hope this helps.
我刚才注意到您的评论中指出:
I've just noticed your comment states:
我已经做了与客户端验证。我想用PHP 验证还有,如果客户端失败(禁用JavaScript)
I already do that with the client side validation. I want to use php validation as well, if the client side fails (javascript disabled)
首先,从来不靠客户端验证的。客户可以轻松地禁用JavaScript和POST的有害数据。
First, never rely on the client-side validating. The client can easily disable the JavaScript and POST the harmful data.
其次,由于使用AJAX是可能只有在启用JavaScript,如果你需要把HTML格式的PHP输出非AJAX请求,您可以传递一个阿贾克斯=真
键/值对到服务器,并返回输出为JSON的视图。
Second, since using AJAX is possible only if the JavaScript is enabled, if you need to push the PHP output in HTML format on non-AJAX requests, you could pass a ajax=true
key/value pair to the server, and return the output as JSON to the view.
在 $阿贾克斯()
方法:
data : $form.serialize() + '&ajax=true',
然后检查 $的存在和价值_ POST ['阿贾克斯']
在服务器端,并确定是否发送为JSON或不输出。
Then check the existence and value of $_POST['ajax']
at the server-side and determine whether to send the output as JSON or not.
您也可以通过检查 HTTP_X_REQUESTED_WITH
确定 $的XHR请求_ SERVER
如下:
You could also determine the XHR request by checking the HTTP_X_REQUESTED_WITH
in $_SERVER
as follows:
function is_xhr_request()
{
return ($_SERVER['HTTP_X_REQUESTED_WITH'] === 'XMLHttpRequest');
}
这篇关于通过AJAX获取验证错误从PHP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!