I have a form that you can add data to a database. It is all done with jquery and ajax so when you press submit it validates the code and then if everything is correct it submits the post data with out refreshing the page. The problem is the form works the first time, but then when you go to submit another entry with the form it doesn't work. I thought it had something to do with the
我有一个可以向数据库中添加数据的表单。这一切都是用jquery和ajax完成的,所以当你按submit键时,它会验证代码,如果一切正常,它会提交post数据,而不会刷新页面。问题是表单第一次可以工作,但是当你提交另一个带有表单的条目时,它就不能工作了。我以为这和那件事有关。
$(document).ready(function(){
But I really have no idea. I've pasted some of the code below. It is pretty long, but this should give enough info to know what it's doing. The entire js file is at http://www.myfirealert.com/callresponse/js/AddUser.js
但我真的不知道。我粘贴了下面的一些代码。它很长,但是这应该提供足够的信息来了解它在做什么。整个js文件位于http://www.myfirealert.com/callresponse/js/AddUser.js
$(document).ready(function(){
$('#AddCaller').click(function(e){
//stop the form from being submitted
e.preventDefault();
/* declare the variables, var error is the variable that we use on the end
to determine if there was an error or not */
var error = false;
var Firstname = $('#Firstname').val();
...OTHER FORM FIELDS HERE
/* in the next section we do the checking by using VARIABLE.length
where VARIABLE is the variable we are checking (like name, email),
length is a javascript function to get the number of characters.
And as you can see if the num of characters is 0 we set the error
variable to true and show the name_error div with the fadeIn effect.
if it's not 0 then we fadeOut the div( that's if the div is shown and
the error is fixed it fadesOut. */
if(Firstname.length == 0){
var error = true;
$('#Firstname_error').fadeIn(500);
}else{
$('#Firstname_error').fadeOut(500);
}
if(Lastname.length == 0){
var error = true;
$('#Lastname_error').fadeIn(500);
}else{
$('#Lastname_error').fadeOut(500);
}
...MORE CONDITIONAL STATEMENTS HERE
//now when the validation is done we check if the error variable is false (no errors)
if(error == false){
//disable the submit button to avoid spamming
//and change the button text to Sending...
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
/* using the jquery's post(ajax) function and a lifesaver
function serialize() which gets all the data from the form
we submit it to send_email.php */
$.post("doadd.php", $("#AddCaller_form").serialize(),function(result){
//and after the ajax request ends we check the text returned
if(result == 'added'){
//$('#cf_submit_p').remove();
//and show the success div with fadeIn
$('#Add_success').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
document.getElementById('Firstname').value = "";
document.getElementById('Lastname').value = "";
document.getElementById('PhoneNumber').value = "";
document.getElementById('DefaultETA').value = "";
document.getElementById('Apparatus').value = "";
document.getElementById('DefaultLocation').value = "";
setTimeout(" $('#Add_success').fadeOut(500);",5000);
}else if(result == 'alreadythere'){
//checks database to see if the user is already there
$('#Alreadythere').fadeIn(500);
$('#AddCaller').removeAttr('disabled').attr('value', 'Add A Caller');
}
else{
//show the failed div
$('#Add_fail').fadeIn(500);
//reenable the submit button by removing attribute disabled and change the text back to Send The Message
$('#AddCaller').removeAttr('disabled').attr('value', 'Send The Message');
}
});
}
});
});
Right now, the first time you use the form it works great. and the button is reenabled, but then when you try to make another entry and click the button nothing happens.
现在,当你第一次使用这个表单时,它非常好用。这个按钮被重新启用,但是当你尝试创建另一个条目并单击这个按钮时,什么也没有发生。
Thanks for the help!
谢谢你的帮助!
EDIT: After the form submits the first time the button is still enabled and you can click on it, but when you click on it nothing happens... even if you don't fill in the form. It's like the click event of the form isn't firing the first time.
编辑:在表单提交第一次按钮仍然被激活后,你可以点击它,但是当你点击它时什么也没有发生……即使你不填写表格。就好像表单的单击事件不是第一次触发一样。
EDIT2 As requested, I'm going to post the HTML, it's behind a password protected site, so I can't send you the page link.
按照要求,我将发布HTML,它在一个密码保护的网站后面,所以我不能发送页面链接。
<form action='addcallers.php' method='post' id='AddCaller_form'>
<h2>Add Callers</h2>
<p>
First Name:
<div id='Firstname_error' class='error'> Please Enter a First Name</div>
<div><input type='text' name='Firstname' id='Firstname'></div>
</p>
<p>
Last Name:
<div id='Lastname_error' class='error'> Please Enter a Last Name</div>
<div><input type='text' name='Lastname' id='Lastname'></div>
</p>
...MORE FORM FIELDS HERE
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly >
</div>
</p>
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
<p id='cf_submit_p'>
<input type='submit' id='AddCaller' value='Send The Message'>
</p>
</form>
</div>
EDIT3 There is other ajax on the page too, but it's written in straight javascript. I'm not sure if that would affect the functionality in any way. But if needed I can post that ajax as well.
页面上还有其他ajax,但它是直接用javascript编写的。我不确定这是否会影响功能。但是如果需要的话,我也可以发布那个ajax。
EDIT4 I got the original tutorial from http://web.enavu.com/tutorials/create-an-amazing-contact-form-with-no-ready-made-plugins/ and modified it
EDIT4我从http://web.enavu.com/tutorials/create-an- amaz- contac -form- without - already -made-plugins/获得了最初的教程,并对它进行了修改
EDIT After putting in some different alerts, I found out that it does not do the conditional statement if(error==false)...
Any Idea why?
在输入一些不同的警报后进行编辑,我发现它不执行条件语句if(error==false)……知道为什么吗?
9 个解决方案
#1
4
most likely, it's the #DefaultLocation field, since it's a read only and you are resetting it after the first post:
很有可能是#DefaultLocation字段,因为它是只读的,您在第一篇文章之后重新设置它:
document.getElementById('DefaultLocation').value = "";
And never changing it's value back to something (or are you?) so you have to do one of the following:
永远不要把它的价值变回什么东西(或者你是?),所以你必须做以下的一件事:
- don't reset it
- 不重置
- set it's value with something after posing the form
- 在放置表单之后,设置它的值
- don't validate it at all since it's a read only and you are using it as a hidden input (which is wrong by the way)!
- 完全不要验证它,因为它是只读的,而且您将它用作隐藏的输入(顺便说一下,这是错误的)!
also, it can be the other "ajax" code you are talking about so please post that too here, also maybe you have other fields (elements) somewhere else on the page with same IDs like the ones in the form..
另外,它也可以是您正在讨论的另一个“ajax”代码,所以请在这里发布它,也可能您在页面的其他地方也有其他字段(元素),它们的id与表单中的相同。
anyway, here are sometips for you: 1- close the input tags correctly (add / to the end of it):
总之,这里有一些提示:1-正确关闭输入标签(添加/添加到末尾):
<input type='text' name='Firstname' id='Firstname' />
2- make sure all DIVs and Ps are closed...as it seems that you have an open P here:
2-确保所有div和Ps都关闭…看起来这里有一个开放的P
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
</p> <---- missing this one
<p id='cf_submit_p'>
3- you are redeclaring the error variable all the time, you don't need to do that:
3-你一直在重新声明错误变量,你不需要这样做:
if(Firstname.length == 0){
var error = true;
....
just use error = true;
without var this applies on all places you are changing its value only use var on initialization:
使用错误= true;在没有var的情况下,这适用于所有正在更改其值的地方,仅在初始化时使用var:
var error = false;
4- instead of this:
4 -而不是这样的:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
use:
使用:
$('#AddCaller').attr({'disabled' : 'disabled', 'value' : 'Adding...' });
5- if you are using DefaultLocation as a hidden field then instead of this:
5-如果你使用DefaultLocation作为一个隐藏字段,而不是这个:
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly />
</div>
use:
使用:
<input type="hidden" name="DefaultLocation" id="DefaultLocation" value="Something" />
#2
2
Try to change from using the click event handler to the form's submit event handler
尝试从使用单击事件处理程序更改为表单的提交事件处理程序
Change this : $('#AddCaller').click
改变这个:$ .click(“# AddCaller”)
To this : $('#AddCaller_form').submit
:$(' # AddCaller_form ')。submit
#3
1
Do not remove the attribute of disabled, set it to false.
不要删除已禁用的属性,将其设置为false。
This line
这条线
$('#AddCaller').removeAttr('disabled').attr(...
should be
应该是
$('#AddCaller').attr('disabled', false).attr(...
#4
0
I assume that by removing and adding attributes, the element is removed and replaced by the new one, but the handler is not re-attached. Try using $('#AddCaller').live('click', function(){ //code })
instead of .click()
我假设通过删除和添加属性,元素将被新的元素所取代,但是处理程序不会被重新连接。尝试使用$(' # AddCaller”)。live('click', function(){//code})而不是.click()
#5
0
This function send queries to php and can return results from the php file using ajax. I have left comments for guide. the first part with try & catch statements does not need modifications. go to #1 and #2
该函数将查询发送到php,并可以使用ajax从php文件返回结果。我给导游留下了意见。使用try & catch语句的第一部分不需要修改。到#1和#2
function ajaxFunction(){
var ajaxRequest;
//Browser compatible. keep it as it is
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//Browser compatible end
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//#2 opional: create functions to return data from your php file
$('#resultArea').html(ajaxRequest.responseText);
}
}
//#1 Set the form method, filename & query here here
ajaxRequest.open("GET", "serverTime.php?query=something", true);
ajaxRequest.send(null);
}
example:
例子:
<input type='submit' value='ajax-submit' onclick='ajaxFunction()' />
#6
0
quick jquery plugin for that since you might use this in almost every ajax form on your site:
快速jquery插件,因为你可以在你的网站上的几乎所有ajax表单中使用:
it will disable all fields that could trigger a submit event and also add a class on the form tag so that you can apply some styling, or showing a load message when the form is submitted:
它将禁用所有可能触发提交事件的字段,并在表单标记上添加类,以便您可以应用一些样式,或者在提交表单时显示加载消息:
jQuery.extend(jQuery.fn, {
formToggle: function (enable){
return this.each(function(){
jQuery(this)[(enable ? 'remove' : 'add') + 'Class']('disabled')
.find(':input').attr('disabled', !enable);
},
enable: function(){ return this.formToggle(true); },
disable: function(){ return this.formToggle(false); }
}
then on your jq ajax code:
那么关于jq ajax代码:
[...]
[…]
var $form = $(your_form).submit(function(){
$.ajax({
type: 'post',
url: "/whatever/",
data: $form.serialize(),
success: function (){ alert ('yay');},
complete: function(){ $form.enable();},
error: function(){ alert('insert coin')}
}
$form.disable();
return false;
});
It should be enough to properly block the submits while the forms is sending/receiving data. If you are really paranoid you can add a check so that it cannot be sent twice between the moment the user triggers the submit and the fields get disabled with : if ($form.is('.disabled')) return false; as first line of the submit handler, but it shouldn t be necessary really
当表单发送/接收数据时,应该足以正确地阻止提交。如果你真的很偏执,你可以添加一个检查,这样在用户触发提交和字段被禁用之间就不能发送两次:If ($form.is('.disabled'))返回false;作为提交处理程序的第一行,但是它实际上不应该是必需的
#7
0
Set some breakpoints in Firebug and watch if it goes somewhere. Button can lose its click handler after submit and applying effects. You probably need to assign click handler again after submit and stuff.
在Firebug中设置一些断点,观察它是否到达某个地方。按钮可以在提交和应用效果后失去它的点击处理程序。您可能需要在提交之后再分配一次单击处理程序。
#8
0
Not 100% on this but try setting the code as a separate function then rebinding the click event at the end.
不是100%的,但是尝试将代码设置为一个单独的函数,然后在最后重新绑定单击事件。
Example:
例子:
function addCaller(e) {
// your unchanged code
$('#AddCaller').click(addCaller(e));
}
$(document).ready(function(){
// added an unbind just in case
$('#AddCaller').unbind('click').click(addCaller(e));
});
#9
-2
Try to change this: $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
into that: $('#AddCaller').attr({'value' : 'Adding...' });
尝试改变这一点:$('#AddCaller')。attr({'disabled': 'true', 'value': ' add…' });到:$(“# AddCaller”)。attr({“价值”:“添加…' });
This should make it work.
这应该能让它工作。
#1
4
most likely, it's the #DefaultLocation field, since it's a read only and you are resetting it after the first post:
很有可能是#DefaultLocation字段,因为它是只读的,您在第一篇文章之后重新设置它:
document.getElementById('DefaultLocation').value = "";
And never changing it's value back to something (or are you?) so you have to do one of the following:
永远不要把它的价值变回什么东西(或者你是?),所以你必须做以下的一件事:
- don't reset it
- 不重置
- set it's value with something after posing the form
- 在放置表单之后,设置它的值
- don't validate it at all since it's a read only and you are using it as a hidden input (which is wrong by the way)!
- 完全不要验证它,因为它是只读的,而且您将它用作隐藏的输入(顺便说一下,这是错误的)!
also, it can be the other "ajax" code you are talking about so please post that too here, also maybe you have other fields (elements) somewhere else on the page with same IDs like the ones in the form..
另外,它也可以是您正在讨论的另一个“ajax”代码,所以请在这里发布它,也可能您在页面的其他地方也有其他字段(元素),它们的id与表单中的相同。
anyway, here are sometips for you: 1- close the input tags correctly (add / to the end of it):
总之,这里有一些提示:1-正确关闭输入标签(添加/添加到末尾):
<input type='text' name='Firstname' id='Firstname' />
2- make sure all DIVs and Ps are closed...as it seems that you have an open P here:
2-确保所有div和Ps都关闭…看起来这里有一个开放的P
<p>
<div id='Add_success' class='success'> The user has been added</div>
<div id='Alreadythere' class='error'> That user is already in the database</div>
<div id='Add_fail' class='error'> Sorry, don't know what happened. Try later.</div>
</p> <---- missing this one
<p id='cf_submit_p'>
3- you are redeclaring the error variable all the time, you don't need to do that:
3-你一直在重新声明错误变量,你不需要这样做:
if(Firstname.length == 0){
var error = true;
....
just use error = true;
without var this applies on all places you are changing its value only use var on initialization:
使用错误= true;在没有var的情况下,这适用于所有正在更改其值的地方,仅在初始化时使用var:
var error = false;
4- instead of this:
4 -而不是这样的:
$('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
use:
使用:
$('#AddCaller').attr({'disabled' : 'disabled', 'value' : 'Adding...' });
5- if you are using DefaultLocation as a hidden field then instead of this:
5-如果你使用DefaultLocation作为一个隐藏字段,而不是这个:
<div style="display:none;">
<input type='text' name='DefaultLocation' id='DefaultLocation' value= "Sometthing" readonly=readonly />
</div>
use:
使用:
<input type="hidden" name="DefaultLocation" id="DefaultLocation" value="Something" />
#2
2
Try to change from using the click event handler to the form's submit event handler
尝试从使用单击事件处理程序更改为表单的提交事件处理程序
Change this : $('#AddCaller').click
改变这个:$ .click(“# AddCaller”)
To this : $('#AddCaller_form').submit
:$(' # AddCaller_form ')。submit
#3
1
Do not remove the attribute of disabled, set it to false.
不要删除已禁用的属性,将其设置为false。
This line
这条线
$('#AddCaller').removeAttr('disabled').attr(...
should be
应该是
$('#AddCaller').attr('disabled', false).attr(...
#4
0
I assume that by removing and adding attributes, the element is removed and replaced by the new one, but the handler is not re-attached. Try using $('#AddCaller').live('click', function(){ //code })
instead of .click()
我假设通过删除和添加属性,元素将被新的元素所取代,但是处理程序不会被重新连接。尝试使用$(' # AddCaller”)。live('click', function(){//code})而不是.click()
#5
0
This function send queries to php and can return results from the php file using ajax. I have left comments for guide. the first part with try & catch statements does not need modifications. go to #1 and #2
该函数将查询发送到php,并可以使用ajax从php文件返回结果。我给导游留下了意见。使用try & catch语句的第一部分不需要修改。到#1和#2
function ajaxFunction(){
var ajaxRequest;
//Browser compatible. keep it as it is
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//Browser compatible end
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//#2 opional: create functions to return data from your php file
$('#resultArea').html(ajaxRequest.responseText);
}
}
//#1 Set the form method, filename & query here here
ajaxRequest.open("GET", "serverTime.php?query=something", true);
ajaxRequest.send(null);
}
example:
例子:
<input type='submit' value='ajax-submit' onclick='ajaxFunction()' />
#6
0
quick jquery plugin for that since you might use this in almost every ajax form on your site:
快速jquery插件,因为你可以在你的网站上的几乎所有ajax表单中使用:
it will disable all fields that could trigger a submit event and also add a class on the form tag so that you can apply some styling, or showing a load message when the form is submitted:
它将禁用所有可能触发提交事件的字段,并在表单标记上添加类,以便您可以应用一些样式,或者在提交表单时显示加载消息:
jQuery.extend(jQuery.fn, {
formToggle: function (enable){
return this.each(function(){
jQuery(this)[(enable ? 'remove' : 'add') + 'Class']('disabled')
.find(':input').attr('disabled', !enable);
},
enable: function(){ return this.formToggle(true); },
disable: function(){ return this.formToggle(false); }
}
then on your jq ajax code:
那么关于jq ajax代码:
[...]
[…]
var $form = $(your_form).submit(function(){
$.ajax({
type: 'post',
url: "/whatever/",
data: $form.serialize(),
success: function (){ alert ('yay');},
complete: function(){ $form.enable();},
error: function(){ alert('insert coin')}
}
$form.disable();
return false;
});
It should be enough to properly block the submits while the forms is sending/receiving data. If you are really paranoid you can add a check so that it cannot be sent twice between the moment the user triggers the submit and the fields get disabled with : if ($form.is('.disabled')) return false; as first line of the submit handler, but it shouldn t be necessary really
当表单发送/接收数据时,应该足以正确地阻止提交。如果你真的很偏执,你可以添加一个检查,这样在用户触发提交和字段被禁用之间就不能发送两次:If ($form.is('.disabled'))返回false;作为提交处理程序的第一行,但是它实际上不应该是必需的
#7
0
Set some breakpoints in Firebug and watch if it goes somewhere. Button can lose its click handler after submit and applying effects. You probably need to assign click handler again after submit and stuff.
在Firebug中设置一些断点,观察它是否到达某个地方。按钮可以在提交和应用效果后失去它的点击处理程序。您可能需要在提交之后再分配一次单击处理程序。
#8
0
Not 100% on this but try setting the code as a separate function then rebinding the click event at the end.
不是100%的,但是尝试将代码设置为一个单独的函数,然后在最后重新绑定单击事件。
Example:
例子:
function addCaller(e) {
// your unchanged code
$('#AddCaller').click(addCaller(e));
}
$(document).ready(function(){
// added an unbind just in case
$('#AddCaller').unbind('click').click(addCaller(e));
});
#9
-2
Try to change this: $('#AddCaller').attr({'disabled' : 'true', 'value' : 'Adding...' });
into that: $('#AddCaller').attr({'value' : 'Adding...' });
尝试改变这一点:$('#AddCaller')。attr({'disabled': 'true', 'value': ' add…' });到:$(“# AddCaller”)。attr({“价值”:“添加…' });
This should make it work.
这应该能让它工作。