[英]How would I check the value in form before sending it to server using ajax
I want to check the value enter in the form by user. 我想检查用户在表单中输入的值。 i have applied validation and its working.
我已经应用了验证及其工作。 The problem is that if user enter any form value incorrectly and then clicks submit, the whole page is refreshed and all input data is lost.
问题是,如果用户错误输入任何表单值,然后单击提交,则会刷新整个页面,并且所有输入数据都会丢失。
I want that validations is checked before passing it to server. 我希望在将验证传递到服务器之前检查其有效性。 One of my friends told me its possible with AJAX.
我的一位朋友告诉我,使用AJAX可能实现。 Can anyone guide a beginner on how to do this?
谁能指导初学者如何做到这一点?
You can use javascript instead and save the server from transferring some extra KBs and calculations by using Ajax (which technically is javascript but you send the request back to the server) 您可以改用javascript,并通过使用Ajax(从技术上讲是javascript,但将请求发送回服务器)来避免服务器转移一些额外的KB和计算。
Jquery has a plugin called validation that will make your life easier though: jQuery有一个称为验证的插件,可以使您的生活更轻松:
http://docs.jquery.com/Plugins/validation http://docs.jquery.com/插件/验证
There is a live demo in the link above 上面的链接中有一个现场演示
For example if you wanted to validate the username you could do this 例如,如果您想验证用户名,则可以执行此操作
<script>
$(document).ready(function(){
$("#commentForm").validate();
});
</script>
<form id="commentForm">
<input id="uname" name="name" class="required" />
</form>
yes you can use ajax or otherwise with your current approach you can use sessions to store user data and prevent it from being lost. 是的,您可以使用ajax或以其他方式使用当前方法,可以使用会话来存储用户数据并防止其丢失。 with ajax you can show response from the server to show to the user.
使用ajax,您可以显示来自服务器的响应以显示给用户。
$.ajax({
url: 'ajax_login.php',
type:'post'.
data:(/*data from form, like,*/ id: $('#username').val())
success: function( data ) {
if(data == 1) {
$('.feedback').html('data has been saved successfully');
//redirect to another page
}
else {
$('.feedback').html('data could not be saved');
$('.errors').html(data);
}
}
});
ajax_login.php would be something like
<?php
if(isset($_POST)) {
//do form validation if it is valid
if(form is valid) {
saveData();
echo 1;
}
else {
echo $errors;
}
}
?>
Do not need ajax. 不需要ajax。 Just set the onsubmit attribute of your form to "return checkfun();"
只需将表单的onsubmit属性设置为“ return checkfun();”即可。 and define checkfun some way like this:
并以如下方式定义checkfun:
function checkfun()
{
if ( all things were checked and no problem to submit)
return true;
else
{
alert('ERROR!');
return false;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.