Why is enabling and disabling a button not working? - javascript

I am trying to enable a submit button for a form only if the user has input the correct captcha (which is displayed as a image) value inside a textbox. captcha is the id of the textbox.
For each key up on this textbox there will be an AJAX request which is sent to a file called a ErrorProcessing.php.Then it will provide a HTML variable which is either "wrong text entered" or null. The submit button then gets enabled only based on that value. This works.
However the problem is that for every key up on that textbox submit button first becomes enabled and then becomes disabled. In the end it is okay. But I am trying to get rid of the enabling the submit button for every key up if the HTML variable is null. The rest of the code is okay. register-submit2 is the id of the submit button. Can any one help me?
$(document).ready(function() {
$("#captcha").keyup(function(e) {
var captcha = $("#captcha").val();
var datastring = 'captcha=' + captcha;
$.ajax({
type: "POST",
url: "my_url/ErrorProcessing.php",
data: datastring,
success: function(html) {
if (html == "wrong text entered") {
$('#register-submit2').prop('disabled', 'true');
} else {
$('#register-submit2').prop('disabled', 'false');
}
}
});
});
});

Use true/false without quotes. String form will be considered as true.
$('#register-submit2').prop('disabled', false);
Or you can skip the if using
$('#register-submit2').prop('disabled', html == "wrong text entered");

Related

How to hide the form permanently and display form submitted

Can someone suggest me how to hide the form from a user once they have submitted successfully and display the message form submitted and this should be visible to the user each time they log in? So far, I am able to collect and save the information to MySQL database. If you need the code I would add it here. Any help truly appreciated.
OR
How can I disable the entire form upon submit and still display all the data entered in the form field permanently? Please help me with the approach I am desperate to find the answer for this.Thank you
While submitting data in database make an entry of is_form_submitted as true. When users logs in, you just need to check is_form_submitted. If its true, so can hide form else you can show the form.
If you are using an AJAX for form submission, then on AJAX's success response, you can hide the form.
In HTML, you can add disply:'none' css for hiding form.
use ajax
$("form").css("display", "initial");
event.preventDefault(); //prevent default action
var post_url = //get form action url
var request_method = //get form GET/POST method
var form_data = $(this).serialize(); //Encode form elements for submission
$.ajax({
url: post_url,
type: request_method,
data: form_data
}).done(function (response) { //
$(".form").css("display", "none");
$("#results").html(response);
});
when getting response display : none the form

AJAX submits form, but it won't stop but it insert data into database

I'm working on a message board and inputs forms have to be validated if javascript is disabled. If javascript is enabled it has to have AJAX to stop refresh and submit form.
I have an html form which is validated by php. And now I'm trying to add jquery and ajax to stop page refresh.
I added a loading gif and inactive inputs field on submit button. But when I add $.ajax gif won't stop spinning and fields won't become active. After I refresh the page I can see that the input data was added to database.
I'm quite new in using ajax and maybe you could help me find a solution to my problem.
here is my code:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
// getting input values by id
var fullname = $("#fullname").val();
var message = $("#message").val();
// array for input values
var data = { fullname : fullname,
message : message };
//disabled all the text fields
$('.text').attr('disabled','true');
//show the loading sign
$('.loading').show();
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "validation.php",
//dataType : 'json',
data: data,
cache: false,
success: function(data){
alert('success');
}
}).done(function(result) {
if (result == "")
form.submit();
else
alert(result);
}).fail(function() {
alert('ERROR');
});
});
});
I get success and input value alert, when I use dataType : 'json', I get error alert.
I would appreciate any kind of help.
maybe once you display .gif image than you are not going to hide the same .gif image again although your ajax finished or stop or fail (in any case).
So, on success of ajax add below two lines to hide .gif and enable text fields.
//enabled all the text fields
$('.text').prop("disabled", false);
//hide the loading sign
$('.loading').hide();
Whole code seems like this,
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "validation.php",
data: data,
cache: false,
success: function(data){
//enabled all the text fields
$('.text').prop("disabled", false);
//hidethe loading sign
$('.loading').hide();
alert('success');
}
});

After validating & submitting form, reset form + change some css styles

I have a simple html contact form with validation check.
I would like to have some commands executed after a successful form submission. But the way I've set this whole thing up... I can't make it work.
HTML contact form:
<form id="mycontact_form" name="form_name" method="post" onsubmit="return validateForm();" action="https://domain.tld/cgi-bin/sendformmail.pl">
validateForm.js:
function validateForm() {
//validating input fields
if (!valid){
return false;
} else {
if(condition1 == true)
{
document.form_name.submit(); return;
}
else {
// doing stuff to form content
document.form_name.submit(); return;
}
}
}
When the submit button is pressed, the form is validated and will be submitted to the perl script sendformmail.pl which return a HTML Status 204 so the user stays on this page and is not redirected (that's the only way I got this part to work).
Now what I would like to have after a successful submission is:
clear/reset the form and
some minor UI stuff: change background of 2 elements + placeholder/inner text of 2 input fields for thank you message.
But for example if I put document.form_name.reset() after the document.form_name.submit(), it's too fast. It resets the form before submissions. I also tried to call another (independent) function after the validateForm() in the onsubmit but that seems to be wrong (well, at least it's not working).
So I guess I need to put these 2 things (reset + CSS changes) in a separate function and call it after a successful form submission.
But how, where and when?
I'm very interested to learn a simple yet effective solution. (but jQuery is also available)
Thank you for your help.
If your email script is on the same domain as your contact form, try submitting it via ajax. Here's a simple jQuery example, which would be in your onsubmit handler:
if (valid) {
$.ajax({
url: "/cgi-bin/sendformmail.pl",
method: "POST",
data: $("#mycontact_form").serialize()
})
.done(function() { // this happens after the form submit
$("#mycontact_form")[0].reset();
});
}
return false; // don't submit the form again non-ajax!
Otherwise, if on different domains, try setting the target of your form to the id of a hidden iframe on your page. Since this is cross-domain, you have no real way of knowing the result of the form submit due to the same origin policy. You can simply hope for the best and reset the form after X number of seconds:
if (valid) {
$("#mycontact_form").submit();
// clear form 3 seconds after submit
window.setTimeout(function() {
$("#mycontact_form")[0].reset();
}, 3000);
}
Both of these approaches keep the user on the same page without a refresh.
I ended up using beforeSend with ajax instead of done. And instead of resetting the form I chose to clear the value of the input fields/textarea (there are only 3). I also included the preferred 'post-submission' style of the input fields/textarea in beforeSend to leave nothing to chance.
Anyway, thank you for helping me & pointing me in the ajax direction.
$.ajax({
url: "/cgi-bin/sendformmail.pl",
method: "POST",
data: $("#mycontact_form").serialize()
beforeSend : function (){
// clear value of input fields/textarea & disable them
// use placeholders for "Thank you." etc.
}
});

JavaScript Form Validation Query

I've just wrote some validation code so as to check if either of my radio buttons from my web form have been selected before they are submitted. I've just starting learning php as I want to be able to store the value of each radio button in a .csv file.
Because I have my action attribute set to trigger a php script, I get my alert box, but as soon as I click OK after pressing submit the browser goes straight to the php script (inevitably).
Is there a way I can return to my initial index.html after the alert message?
I have not actually written any php as yet, so would this go in the php script or the javascript?
Heres my code so far:
$("#submit").on("click", function() {
var radio = $("input[type=radio][name=emotion]")[0].checked;
var radio2 = $("input[type=radio][name=emotion]")[1].checked;
var radio3 = $("input[type=radio][name=emotion]")[2].checked;
if(!radio && !radio2 && !radio3) {
alert("You must select at least one word!");
}
else {
alert("Please rate the next item!")
}
});
In Jquery you should use .submit() function to validate a form.
Then to avoid to submit the form you can use the function event.preventDefault()
And if you want to go to the index you can use window.location = "yourURL"
You must use form.onsubmit().
For example, if your form's name is myForm:
document.forms['myForm'].onsubmit = function()
{
if (this.elements['emotion'].value)
{
alert("Please rate the next item!");
}
else
{
alert("You must enter at least one word!");
return false;
}
}
And after alert "Please rate the next item!" form will be send.
Actually you can use jquery $.post() , an easy solution is just to post your php page without leaving index page.
http://api.jquery.com/jquery.post/
$.post( "yourpage.php" );
You probably have the input type of the submit button as submit? Set this to button, so the action doesn't take place and only jQuery is executed.
But then you have to submit the form by jQuery when validation was successful:
document.myFormId.submit();

How do I stop the page reload after selecting an autocomplete suggestion

I made an autocomplete for a form input field that allows a user to add tags to a list of them. If the user selects any of the suggestions, I want the page to use add the new tag to a section of tags that already exist without the page reloading.
I want this to happen with 3 scenarios:
The user types in the tag, ignores the autocomplete suggestions and presses enter.
After typing in any part of a query, the user selects one of the autocomplete suggestions with the arrow keys and presses enter.
After typing in any part of a query, the user clicks on one of the autocomplete suggestions with the mouse.
I have been able to make scenario 1 work flawlessly. However, scenarios 1 and 2 make the page reload and still doesn't even add the tag to the list.
Scenarios 1 and 2 are both called by the same function:
$j("#addTag").autocomplete({
serviceUrl:'/ac',
onSelect: function(val, data){
addTag(data);
}
});
And here is the code for addTag():
function addTag(tag){
var url = '/addTag/' + tag;
//Call the server to add the tag/
$j.ajax({
async: true,
type: 'GET',
url: url,
success:function(data){
//Add the tag to the displayed list of already added tags
reloadTagBox(data);
},
dataType: "json"
});
//Hide the messages that have been displayed to the user
hideMessageBox();
}
Scenario 1 code:
function addTagByLookup(e, tag){
if(e && e.keyCode == 13)
{
/*This stops the page from reloading (when the page thinks
the form is submitted I assume).
*/
e.preventDefault();
//If a message is currently being displayed to the user, hide it
if ($j("#messageBox").is(":visible") && $j("#okayButton").is(":visible")){
hideMessageBox();
}
else{
//Give a message to the user that their tag is being loaded
showMessageBox("Adding the tag <strong>"+tag+"</strong> to your station...",'load');
//Check if the tag is valid
setTimeout(function(){
var url = '/checkTag/' + tag;
var isTagValid = checkTag(tag);
//If the tag is not vaid, tell the user.
if (isTagValid == false){
var message = "<strong>"+tag+"</strong>"+
" was not recognized as a valid tag or artist. Try something else.";
//Prompt the user for a different tag
showMessageBox(message, 'okay');
}
//If the tag is valid
else{
addTag(tag);
}
}, 1000);
}
}
}
I know I used the e.preventDefault functionality for a normal form submit in scenario 1, but I can't seem to make it work with the other scenarios and I'm not even sure that is the real problem.
I am using pylons as the MVC and using this tutorial for the autocomplete.
So in case anyone wants to know, my problem was had an easy solution that I should have never had in the first place.
My input tag was embedded in a form which submitted every time the input tag was activated.
I had stopped this problem in scenario 1 by preventing the default event from occurring when the user pressed enter. But since I didn't have access to this event in the jQuery event .autocomplete(), I couldn't prevent it.

Categories