Javascript: Show message on submit - javascript

I want to show some message in span tag after my form gets submitted to the server. The problem is, the text disappears within seconds. Is it because the page is reloaded? Can anyone spot what is wrong with my function?
function placeOrder(form) {
if (validateLength(1, 32, form["bannerMessage"], form["messageError"]) &&
validateZipField(form["zipField"], form["zipError"]) &&
validateEmptyFields(form["dateField"], form["dateError"]) &&
validateEmptyFields(form["nameField"], form["nameError"]) &&
validateEmptyFields(form["phoneField"], form["phoneError"]) &&
validateEmptyFields(form["emailField"], form["emailError"])) {
// Submit the order to the server
form.submit();
document.getElementById("submitSuccess").innerHTML = "Submitted successfully";
} else {
alert("I'm sorry but there is something wrong with the order information.");
}
}

Exactly, you are sending the form to the server who will send back a complete page.
What you should do is have the new page contain the message that the form was successfully sent, or if there was a problem with the form (you do server-side validation, right?) -- give the details of the error.
For usability, it is important to make sure that you keep all of the form-fields you can. (E-Commerce fields are special, but keep everything else.)

Related

Bots are bypasing my script for blocking emails

I currently have a script for blocking non-business email addresses on my website form (Marketo) yet bots are still finding a way to bypass it. Today I got another "gmail" and "hotmail.fr" submission. Whenever I test my form it works but the bots are finding a way to bypass the script. I have also tried the honeypot method but it has not worked. They are also submitting with two-letter names, the past month has been really bad and I am desperate for help, I am not very good in JS so any help would be very much appreciated.
This is my script:
(function (){
// Please include the email domains you would like to block in this list
var invalidDomains = ["#gmail.","#yahoo.","#hotmail.","#live.","#aol.","#outlook.","#icloud.","#zoho.","#hubspot.","#gmx.","#yandex.","#mail.","#email.","#tutanota.","#trashmail.","#lycos.","#tutanota.","#protonmail."];
MktoForms2.whenReady(function (form){
form.onValidate(function(){
var email = form.vals().Email;
if(email){
if(!isEmailGood(email)) {
form.submitable(false);
var emailElem = form.getFormElem().find("#Email");
form.showErrorMessage("Must be Business email.", emailElem);
}else{
form.submitable(true);
}
}
});
});
function isEmailGood(email) {
for(var i=0; i < invalidDomains.length; i++) {
var domain = invalidDomains[i];
if (email.indexOf(domain) != -1) {
return false;
}
}
return true;
}
})();
</script>```
Some bots when they run, they don't even execute the JavaScript on the page. They just take the fields, find the post request the form is submitting, and submit the fields to them with pre-defined values. Thus, ignoring your validation completely.
So now the solution would be checking the post request values on the backend. Some people use the fact that some bots are dumb, and they include a honeypot field in their fields. They mark it hidden with CSS on the frontend, but again, some bots are dumb, and they will fill it out regardless and send it in the post request. Now you can have your sever throw that out right away.

Prevent user to send empty fields

My jQuery validation form warns user if he tries to send empty data if he clicks "Next" button.
Anyway, user still able to send empty data by pressing Enter.
So I used code below, it makes pressing Enter same with clicking "Next" button;
// this script makes pressing Enter gives error. But empty data still goes to database.
$('.form-horizontal').keypress(function (event) {
if (event.which === 13) {
$(".next").trigger('click');
}
});
This code only prevents user to go next step. But when user hits the Enter data being written to database even though he sees "Error Message".
*
Well, server-side verification prevents that easily. But why it's necessary keep server busy with that if we can prevent earlier?
Here is JsFiddle you can test the whole thing:
http://jsfiddle.net/6zu2vsj7/3/
*
Is there any way to make it work without keeping servers busy with empty fields? And I don't want to prevent user pressing Enter because this is not cool at all and not good for user experience.
You can add a condition to check whether the form is valid or not before you sending the data to server as below. hope this helps...
// Let's act like we send to database.
$(function(){
$('input[type=submit]').click(function(){
if($("#myform").valid()){
$.ajax({
type: "POST",
url: "sent.php",
data: $("#myform").serialize(),
beforeSend: function(){
$('#stepsuccess').html('Sent to the database. Strange.');
},
success: function(data){
$('#stepsuccess').html(data);
}
});
}
});
});
You just need to prevent the default behavior for that event
you can use this
$('.form-horizontal').keypress(function (event) {
if (event.which === 13) {
event.preventDefault();
$(".next").trigger('click');
}
});
Try this:
$(".form-horizontal").submit(function(e){
//do somethings or other validations
return false;
});
well! server side validation is necessary because client side validation is just for normal users! not hackers and robots! got it?!
in fact client side validation can be easily pass.

How do I refresh a value in php from javascript?

I have a form that I'm submitting using javascript. However, one of the checks it does uses a php script that queries an API and gets a user's password. This is for the purposes of form validation (i.e. if password doesn't match what we have on file..)
I'm using a php script to decode the password like this
function submitForm() {
var options = {
decoded_password: '<?php echo abc_decode($contactInfo['Password'])?>',
}
if (jQuery('#current_password').val() != options.decoded_password && $psc('#current_password').val()) {
render_alert('Your current password does not match what we have on file.');
return false;
} else {
$psc('#account-information').submit();
document.getElementById("account-information").reset();
}
Page loads, great, submit form, great. However, the variable is remembered from the first page load, so if I try to change the password again, it says my password doesn't match what is on file. If I reload the page, no problem.
Is there any way to change the value of $contactInfo['Password'] in javascript without a page reload?
You could try making an AJAX call instead. This won't require a page reload, but will still give you the opportunity to send the data back to the server. If you store the data in the $_SESSION variable it will persist across multiple calls.

JS/JQuery/PHP - How to echo errors on form validate failure, and jump to div on success?

I have a fixed-position form that can be scrolled out onto the document and filled out anywhere on the page. If they fail to fill out the form properly, the errors are currently echod out onto the form, which is the intended design for that aspect. What I don't currently know how to do is, if the form is completed and $errors[] is empty, to use jQuery scrollTop() to jump down to the bottom.
Could anyone help me out with this? Current javascript involved is:
$("#A_FORM_submit_button").click(function() {
$("#FORM_A").submit( function () {
$.post(
'ajax/FORM_A_processing.php',
$(this).serialize(),
function(data){
$("#A_errors_").html(data);
}
);
return false;
});
});
The PHP involved is simply
if (!empty($errors)){
// echo errors
} else { // echo success message} <-- would like to jump to div as well
edit-- for clarity: not looking to make the page jump happen in the php file, so much as return a value for the jq $.post function to check and then perform an if/else
I might be jumping the gun here but I believe your design is wrong which is why you are running into this problem.
The ideal way of handling form validation is to validate forms via Javascript and when users enter in their information you immediately show some indicator to ask them to correct it. As long as the validation is incorrect, you should not be accepting a form request or making any AJAX calls.
In the off-chance that they do successfully send the data, you should be doing a validation check via PHP as well which, if failed, would redirect to the original page with the form. From there you could do whatever error handling you want but ideally you would retain the information they entered and indicate why it was wrong (Javascript should catch this but I guess if it gets here the user might have JS off or your validation logic might be wrong)
If I understand correctly, it seems like you are doing your error handling with Javascript (that's fine) but showing the error via PHP. As Hydra IO said don't confuse client-side and server side. Make them handle what they need to handle.
Hope this helps.
#aug described the scenario very clearly.
In code it translates in something like this
$('form').submit(function(){
form_data = $(this).serialize();
if(!validate(form_data))
{
// deal with validation, show error messages
return false;
}
else
{
// Submit form, either via Ajax $.post() or by just returning TRUE
}
});
The validate() function is up to you to work out.

onunload - Check if Form was submitted

I have a form on a webpage.when the user moves from that page, I want to check that the form was submitted. If it was, then the user simply continues to the next page, if not, the user receives an alert msg and is brought back to the original page where the form resides.
I am not too familiar with javascript so I would appreciate some code snippets if that's possible?
GF
Your question is a bit vague. Your question implies that you're submitting the form asynchronously, but you said that you aren't familiar with JavaScript. Submitting a form asynchronously requires JS knowledge. Also, if you're actually submitting the form synchronously, the solution would have been too obvious (just render some JS conditionally on the server side).
If you're actually submitting the form asynchronously, then just set some token/toggle in as form's data-xxx attribute after the succesful form submit. E.g.
function submit(form) {
// Do your thing to submit it.
// And then on succes:
form['data-submitted'] = true;
return false;
}
Then, during beforeunload event you just check if the token/toggle is there and in case it's missing, return the message accordingly.
window.onbeforeunload = function() {
for (var i = 0; i < document.forms.length; i++) {
var form = document.forms[i];
if (form['data-submitted'] != 'undefined' && !form['data-submitted']) {
return "There is unsaved data!";
}
}
}
Note that you can't use unload event for this since it too late then to keep the page open.
Update: so the form is submitted synchronously. Okay, whatever server side language you're using, just let it conditionally render a JS window.onbeforeunload call when the form is not submitted (you obviously already know when the form is been submitted, how else would you be able to process it? ;) ). You also need to disable the window.onbeforeunload call when the form is about to be submitted.
Based on your question history I bet that you know PHP, so here's a PHP targeted kickoff example:
<?php
if (!$form_is_submitted) {
echo '<script>window.onbeforeunload = function() { return "There is unsaved data!"; }</script>';
echo '<form onsubmit="window.onbeforeunload=null">';
}
?>

Categories