Javascript and php execution priority in different browsers - javascript

I have a simple JS statement, which kind of "protects" me from using special characters in a login form on my website:
$("#login_button").click(function(){
formChecker();
});
function formChecker() {
var checkLogin = document.forms["loginForm"]["username"].value;
if ((checkLogin.indexOf("!") > -1) || (checkLogin.indexOf("#") > -1) || (checkLogin.indexOf("#") > -1)) {
alert("Special characters not allowed! Please use A-Z and numbers.");
document.location = "http://mywebsite.com/";
}
}
It works fine in Chrome. Whenever someone is using one of these characters, he is getting redirected instantly, so the php login script is not executed.
The problem occures when I am using it in Internet Explorer. It actually redirects my page but the php script is executed anyway. I have also tried window.location but it doesnt work at all in IE. What is the problem with this browser? Is the scipt priority different in different browsers?
What I mean is that on IE, even though the user is redirected, when he comes back to the website, he is logged in, but he shouldnt be. The chrome browser does not log in the user because page is redirected and it is how it should work.

This is not how to do form validation. There is no guarantee that click will be called on the button (eg the form might be submitted by pressing Enter); you aren't preventing the form from being submitted by doing a redirect (it's a race condition which might happen first); and also alert-and-redirect is pretty user-hostile.
You should be picking up the submit event on the form itself, and cancelling the event if you don't want the form to submit. For example add a div with id="formErrorMessage" to the page and then:
var goodUsernamePattern = /^[a-zA-Z0-9_-]+$/;
$('#loginForm').on('submit', function(event) {
if (!goodUsernamePattern.test(this.username.value)) {
event.preventDefault();
$('#formErrorMessage').text('Please enter a good username blah');
}
});

Related

Prevent user to leave page without the confirmation

I have found on StackOverflow this script that handles the issue when a user wants to leave the page, to ask him before doing it.
ISSUE
It is working fine (even though there is probably a much better solution) but I have realized that it is causing one "bug". When a user sends data from the form and the script asks him does he want to leave the page (because of the redirect) it still sends data. So, even if the user clicks on "Cancel" it will still proceed to the store() method and if the user adds something more and sends again the data I get duplicates. Is there a way to include "stop propagation" in this script?
CODE
window.onbeforeunload = function () {
return 'Are you sure you want to close this website?';
};
Additional question
Since this script is running with the Laravel Livewire, every time I click on any button related to the livewire (which won't redirect the user to the other page) script prompts the popup to ask if the user is sure he wants to leave the page. Is there any workaround (if you need some other code, write a comment because I am not sure which part could help you at all :) ) for this issue?
Try this:
<script>
window.onbeforeunload = function (e) {
e = e || window.event;
// For IE and Firefox prior to version 4
if (e) {
e.returnValue = 'Sure?';
}
// For Safari
return 'Sure?';
};
</script>
Here is a working jsFiddle

How to stop refresh the page form the beforeunload event?

i'm using the 'beforeunload' event to detect the refresh event from the webpage.how to stop refresh the page from beforeunload event and i should not show alert message
window.addEventListener("beforeunload", this.onUnload);
onUnload = e => {
e.preventDefault();
// how to stop refresh the page from here and i should not show alert message.
//it is showing alert message. i no need to show the alert.
e.returnValue = "sure do you want to reload?";
}
It is not possible to prevent unloading a page without notifying the user.
Imagine you want to go to github.com at a time you are viewing stackoverflow.com - but it will simply prevent you from navigating away!
However, there was a time some browsers used to prevent unloading silently when you assign an empty string to the returnValue. But I believe that age of evil is gone now.
When i understand your following comment corectly, then you simply need to return zero, or false. So in your function you write:
onUnload = e => {
//e.preventDefault();
return false;
}
When i do this, i get an automated response from the Browser (for me its Chrome), if i really wanna close this website. And its in my language, so its i18n-compilant
It basically says "Are you sure you wanna refresh/close this website, data may get lost" and than 2 buttons with "Refresh/Close" and "Abort"

Javascript function fails to perform task in Google Chrome

I've been researching this problem for a while, and given the immense amount of issues Google Chrome seems to have with Javascript, I've been having trouble finding anyone with this same issue.
The problem is this: when the anchor calls a new function which replaces the contents of a div, it shows the proper result for a moment before reverting to the default contents of the div prior to any changes by Javascript.
Here's the script:
function prologueThree() {
document.getElementById('content').innerHTML = document.getElementById('prologue3').innerHTML;
}
function prologueFour() {
userName = document.getElementById('yourname').value;
if(userName.length === 0) {
alert("Erm... are you sure that\'s your name?");
prologueThree();
} else {
document.getElementById('content').innerHTML = '<center> \
<img src="http://pokemonroleplay.thedevhome.net/images/Gameboy/characters/red.png"><br> \
Right, so your name is ' + userName + '! \
<br><br> \
<a onclick="prologueFive()"><button>>>Continue>></button></a></center>';
}
}
This is only a snippet of the script, but the entire thing works fine in Firefox and for the first three prologue functions it works fine in Chrome. It's only when it tries to run prologueFour that it freaks out and go back. I've also tried the Chrome developer console, but it never registers an error.
Thank you in advance for your help.
I went to your site
and I noticed you are binding an onclick to a submit button in your form without preventing the default behavior from executing, the default behavior being a form submission which refreshes the page and thus makes you lose your place and go back to the beginning. Use a plain old button or anchor tag like you do for your previous prologues. If you insist on using a submit for whatever reason, prevent the default behavior like so:
function prologueFour(e) {
typeof e.preventDefault === 'function'
? e.preventDefault()
: e.returnValue = false;
// now rest of code can continue without page refresh
}
I don't know if there are other issues, but >>Continue>> isn't exactly standards-compliant html, which could be causing problems. You should use > instead.

Is it possible to refresh a form only?

I have a form that when is submited it posts to a div. Ok, so I found the issue that i was getting double submissions, so i tried to apply some jquery plugins i found, but they were useless because if you double clicked fast enough I still got a double submission. From those I found i saw the best way to prevent it was with
if (this.beenSubmitted) return false;
else
this.beenSubmitted = true;
but then, I noticed that if the form needed to be sent again, the user would have to refresh the page in order to send it. In my case, I want them to be able to send again after is sent, (Im not contradicting myself, because it would be diferent content). To explain it better, this form post ideas. If you want to post 2 diferent ideas you would have to refresht he page to post. Preventing double submission would help from submitting the same idea twice if you clicked fast enough. So, what I did is that I added this "5000":
if (this.beenSubmitted) return false, 5000;
else
this.beenSubmitted = true;
So, now it refreshed my page. But im a little picky, lol. So I find it annoying that the whole page has to refresh. What if your typing and then it refreshes. I can always lower the 5000 I know, but I still find it annoying in case you start to browse the website or to zoom in, you end up refreshed.
So, my question is, is there any way to just refresh the form? or a better way to prevent double submission that actually works for this case (that ur able to submit after a few secs) ?
this is script:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
var addcontent = jQuery('#addcontent').attr('value');
if ( addcontent.replace(/\s/g,"") == "" ) return false;
if (this.beenSubmitted) return false,5000;
else
this.beenSubmitted = true;
$.ajax({
type: "POST",
url: "post.php",
data:"addcontent="+ addcontent,
success: function(){blah blah blah, ton sof code here including pagintion here, insert into a div here also, if u need this let me know.
});
</script>
Most of that I did it from asking questinos here. My Jquery and Ajax knowledge isnt the best one.
THanks for the help =}
Rate limiting to prevent malicious behavior in ExpressJS
The above link has something about putting a timer on the submit button so that you can't click it again within 3 seconds.
<script>
var submitTimer = new Collate(3000);
</script>
<form action="post" onsubmit="return submitTimer.idle();">
why don't u use the this.beenSubmitted = true approach and combine it with a timeout? for example after 5000ms u execute the timeout and set this.beenSubmitted to false.
The statement:
return false, 5000;
will always return 5000, the use of false is redundant and pointless.
To reset a form without reloading the page (which won't necessarily reset the form in some browsers), use a reset button or call the form's reset method. You can use an onreset listener to update the beenSubmitted property if the form is reset.
Multiple submission of a form has been an issue since forms were invented, it's usually dealt with at the server (if two identical requests are received, ignore the second).
Using script at the client is unreliable since you don't know what the server is doing and you have to guess whether or not the form needs to be resubmitted.

JavaScript log-in validation by-passed by IE8

I have a log-in web page that uses JavaScript for name and password validation. It works fine in Mozilla Firefox, but IE8 allows logging in without entering name and or password. It posts a script-restriction warning which, when you click on it, you can chose to enable the JavaScript. That's fine except you can just bypass that step by clicking the Log In button on the web page and you're in. That's a big problem. So it's not running the JavaScript. That defeats the whole purpose of the page.
This (xhtml) form tag calls the JavaScript:
form name="form1" action="TestAccess.htm" onsubmit="return butCheck_onclick()"
This input tag contains the log-in button:
input type="submit" class="center" value="Log In"
I need some kind of work-around so that I can fool IE into either running the JavaScript before loading the next page or some way of stopping the HTML from allowing the next page to load before it runs the JavaScript. But then why would I need the JavaScript if I could implement such restrictions in HTML? I hope I'm making sense. Thanks for any help you can give. ---Andy V.
Here's the JavaScript function I have:
<script language="javascript">
var global="";
function butCheck_onclick()
{
var password = document.form1.password.value;
var Name = document.form1.memName.value;
/*if(Name=="")
{
alert("Enter User name and password.");
} */
var swFound= "NF";
var valName= new Array();
valName[0]= "Roland";
valName[1]= "Korg";
valName[2]= "Peavy";
var valpassword= new Array();
valpassword[0]= "123";
valpassword[1]= "456";
valpassword[2]= "789";
for(var loop=0; loop < valName.length; loop++)
{
if(Name==valName[loop])
{
swFound="F";
if(Name!=valName[loop])
{
swFound="NF";
}
if(password!=valpassword[loop])
{
alert("Invalid password. Please enter a valid password.")
document.form1.password.focus();
document.form1.password.select();
return false;
}
}
}
if (swFound!="F")
{
alert("Invalid last name entry. Please enter a valid last name.")
document.form1.memName.focus();
document.form1.memName.select();
return false;
}
}
</script>
You should never do authentication on the client side. Always do your username/password check on the server side.
In your code, for example, all I would have to do is view the source of the page and copy/paste the username and password.
or even just copy paste the destination url.
Furthermore, simply disabling javascript would clearly be enough.
The only validation you might do on the clientside is determining (at registration time) if the entered values are of the right length, etc. (and duplicated on the server side)
EDIT:
see The definitive guide to form-based website authentication for some good advice from SO users on website authentication.
You can use this code:
form name="form1" action="TestAccess.htm"
input type="button" class="center" value="Log In" onclick="butCheck_onclick()"
function butCheck_onclick() {
// do validation returnig false if something is wrong
// when all is good submit the form
form1.submit();
}
IMPORTANT notes:
You force your users to have
javascript enabled. Maybe this is
not a problem in your project.
Do you realize that anyone who does a
"View source" will see the usernames
and passwords?
What's the purpose of JavaScript embedded passwords? "As is" anyone can see these just by doing "View Source"?
But basically you need return false not FROM within for loop but AFTER if your condition fails

Categories

Resources