Javascript toggle button fails the if condition - javascript

Guys what am I doing wrong? On my pc this code: simple toggle shows me false === True when I call the function for the first time. Why it goes on else when status is false?
var status = false;
function toggleStatus() {
var message = "status:" + status;
if (status === false) {
message += "===FALSE";
status=true;
} else {
message += "===TRUE";
status=false;
}
alert(message);
}

It will be because there's already a window.status defined (which is a string, and used for the text in the browser status bar).
Because you're not protecting the global namespace from your code, the status variable is being defined as a global on the window object. Presumably the browser is going to stomp all over that.
This however should work https://jsfiddle.net/72rf8g8p/:
(function(){
var status = false;
function toggleStatus() {
var message = "status:" + status;
if (status === false) {
message += "===FALSE";
status=true;
} else {
message += "===TRUE";
status=false;
}
alert(message);
}
toggleStatus();
})();
You can also simply change the name of your variable to something else, such as myStatus:
var myStatus= false;
function toggleStatus() {
var message = "myStatus:" + myStatus;
if (myStatus=== false) {
message += "===FALSE";
myStatus=true;
} else {
message += "===TRUE";
myStatus=false;
}
alert(message);
}

Related

HTTP Parameter pollution attack

I developed a web application and deployed into the server and my security team come up with the below security remidiation issue.
Reflected HTML Parameter Pollution (HPP) is an injection weakness vulnerability that occurs when an attacker can inject a delimiter and change the parameters of a URL generated by an application. The consequences of the attack depend upon the functionality of the application, but may include accessing and potentially exploiting uncontrollable variables, conducting other attacks such as Cross-Site Request Forgery, or altering application behavior in an unintended manner. Recommendations include using strict validation inputs to ensure that the encoded parameter delimiter “%26” is handled properly by the server, and using URL encoding whenever user-supplied content is contained within links or other forms of output generated by the application.
Can any one have the idea about how to prevent HTML parameter pollution in asp.net
here is the script code in the webpage
<script type="text/javascript" language="javascript">
document.onclick = doNavigationCheck ;
var srNumberFinal="";
function OpenDetailsWindow(srNumber)
{
window.open("xxx.aspx?SRNumber="+srNumber+ "","","minimize=no,maximize=no,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no,width=800,directories=no,resizable=yes,titlebar=no");
}
function OpenPrintWindow()
{
var querystrActivityId = "<%=Request.QueryString["activityId"]%>";
if(querystrActivityId != "")
{
var url = "abc.aspx?id=" + "<%=Request.QueryString["id"]%>" + "&activityId=" + querystrActivityId + "";
}
else
{
var hdrActivityId = document.getElementById('<%=uxHdnHdrActivityId.ClientID%>').value;
var url = "PrintServiceRequestDetail.aspx?id=" + "<%=Request.QueryString["id"]%>" + "&activityId=" + hdrActivityId + "";
}
childWinReference=window.open(url, "ChildWin","minimize=yes,maximize=yes,scrollbars=yes,status=yes,toolbar=no,menubar=yes,location=no,directories=no,resizable=yes,copyhistory=no");
childWinReference.focus();
}
function NavigateSRCopy(srNumber)
{
srNumberFinal = srNumber;
if (srNumber != "undefined" && srNumber != null && srNumber != "")
{
new Ajax.Request('<%= (Request.ApplicationPath != "/") ? Request.ApplicationPath : string.Empty %>/xxx/AutoCompleteService.asmx/CheckFormID'
, { method: 'post', postBody: 'srNumber=' + srNumber, onComplete: SearchResponse });
}
}
function SearchResponse(xmlResponse)
{
var xmlDoc;
try //Internet Explorer
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.loadXML(xmlResponse.responseText);
}
catch(e)
{
try // Firefox, Mozilla, Opera, etc.
{
parser=new DOMParser();
xmlDoc=parser.parseFromString(xmlResponse.responseText,"text/xml");
}
catch(e)
{
alert(e.message);
return;
}
}
if(xmlDoc.getElementsByTagName("string")[0].childNodes[0] != null)
{
formID = xmlDoc.getElementsByTagName("string")[0].childNodes[0].nodeValue;
}
else
{
formID = null;
}
if(formID != null && formID != "")
{
window.location.href = '/CustomerSupportRequest/CreateServiceRequest.aspx?id=' + formID + '&TemplateSR=' + srNumberFinal + '&Frompage=CopySR';
return true;
}
else
{
alert("This Service Request cannot be copied because it meets at least one of these conditions: \t\t\n\n * It was created prior to 10/15/2008 \n * It was auto generated as part of the Report Requeue Process \n * It was auto generated as part of the ERA Requeue Process \n * It was not created online");
}
}
function UpdateChildCases()
{
var modalPopup = $find('modalParentChildComments');
modalPopup.show();
}
function HideParentChildPopup()
{
var modalPopup = $find('modalParentChildComments');
modalPopup.hide();
return false;
}
function HideErrorSRNumsPopup()
{
var modalPopup = $find('modalParentErrorSRNumDisplay');
modalPopup.hide();
return false;
}
function HideRetrySRNumsPopup()
{
var modalPopup = $find('modalRetrySRNumDisplay');
modalPopup.hide();
return false;
}
function RemoveParent_ChildFlag(type)
{
var childCases = document.getElementById("<%=uxHdnChildCases.ClientID %>");
var msg = "";
var btn;
if(type == "Child")
{
if(childCases.value.indexOf(',') != -1)
msg = "Are you sure you want to remove the Child flag from this Service Request?";
else
msg = "This is the only child associated to the parent case. Removing the child flag will also remove the parent flag from the associated case. Choose OK to remove the flags, or Cancel to close this dialog";
btn = document.getElementById('<%=uxRemoveChildFlag.ClientID%>');
}
else
{
msg = "Removing the parent flag from this case will also remove the child flag from all associated cases. Are you sure you want to remove the Parent flag from this Service Request?";
btn = document.getElementById('<%=uxRemoveParentFlag.ClientID%>');
}
if(btn)
{
if(!confirm(msg))
{
return false;
}
else
{
btn.click();
}
}
}
function limitTextForParentChildComments()
{
var objLblCharCount = document.getElementById('uxLblPCCharCount');
var objTxtComments = document.getElementById('<%=txtParentComment.ClientID%>');
if (objTxtComments.value.length > 1500)
{
objTxtComments.value = objTxtComments.value.substring(0, 1500);
}
else
{
objLblCharCount.innerHTML = 1500 - objTxtComments.value.length + " ";
}
setTimeout("limitTextForParentChildComments()",50);
}
function ValidateInputs()
{
var lblErrorMessage = document.getElementById('<%=lblCommentErrorTxt.ClientID%>');
var objTxtComments = document.getElementById('<%=txtParentComment.ClientID%>');
if(objTxtComments.value.trim() == "")
{
lblErrorMessage.style.display = "block";
return false;
}
}
</script>
As per OWASP Testing for HTTP Parameter pollution, ASP.NET is not vulnerable to HPP because ASP.NET will return all occurrences of a query string value concatenated with a comma (e.g. color=red&color=blue gives color=red,blue).
See here for an example explanation.
That said, your code appears to be vulnerable to XSS instead:
var querystrActivityId = "<%=Request.QueryString["activityId"]%>";
If the query string parameter activityId="; alert('xss');" (URL encoded of course), then an alert box will trigger on your application because this code will be generated in your script tag.
var querystrActivityId = ""; alert('xss');"";

If Statement Not Acting As Expected

$(document).ready(function(){
logger();
});
function logger()
{
if(localStorage.getItem("status") === null)
{
$("#test").html("Not logged in.");
$("#buttonlogin").click(function(){
var ul = $("#userlogin").val();
var pl = $("#passlogin").val();
$.post("includes/logger.php", {type : "login", user : ul, pass : pl}, function(dlogin){
if(dlogin == 1)
{
$("#outlogin").html("Please enter a username.");
$("#userlogin").focus();
}
else if(dlogin == 2)
{
$("#outlogin").html("Please enter password.");
$("#passlogin").focus();
}
else if(dlogin == 3)
{
$("#outlogin").html("This username doesn't exist.");
$("#userlogin").focus();
}
else if(dlogin == 4)
{
$("#outlogin").html("This username and password don't match.");
$("#userlogin").focus();
}
else
{
localStorage.setItem("status", dlogin);
logger();
}
});
});
$("#buttonregister").click(function(){
var ur = $("#userregister").val();
var pr = $("#passregister").val();
var cpr = $("#confirmpassregister").val();
$.post("includes/logger.php", {type : "register", user : ur, pass : pr, cpass : cpr}, function(dregister){
if(dregister == 1)
{
$("#outregister").html("Please enter a username.");
$("#userregister").focus();
}
else if(dregister == 2)
{
$("#outregister").html("Please enter a password.");
$("#passregister").focus();
}
else if(deregister == 3)
{
$("#outregister").html("Please enter a confirm password.");
$("#cpassregister").focus();
}
else if(dregister == 4)
{
$("#outregister").html("Password and confirm password do not match.");
$("#passregister").focus();
}
else if(dregister == 5)
{
$("#outregister").html("This username is already taken.");
$("#userregister").focus();
}
else
{
localStorage.setItem("status", dregister);
logger();
}
});
});
}
else
{
$("#test").html("You are logged in.");
$("#buttonlogout").click(function(){
localStorage.removeItem("status");
logger();
});
}
}
The above code is meant to check whether or not a localStorage variable is in existence or not. If it is then only allow the log out button to be pressed. If is doesn't then let the two forms to work. Once it is done with either it is supposed to recheck if the variable is set and then do as I said above. However it ignores it when a user logs in and allows the forms to run. If you refresh however it works fine. I cannot for the life of me figure out why this is happening, and it is beginning to piss me off. Any help would be appreciated.
On your else statement, try adding:
$('#buttonlogin').unbind('click');
$('#buttonregister').unbind('click');
If I understand your problem correctly, what's happening is those events are registered when you first run $("#buttonlogin").click(function()....
It doesn't matter that you call logger() again and the if statement is false the second time around. If you want to disable these callbacks you have to do it explicitly.

How to stop execution when form validation in javascript

I have two questions from the coding below.
First, now i would like to perform validation before submission. How can I stop submission if some errors are detected from the validation function? Is it simply return false after each of the error msg? however, it seems still check all fields instead of stopping after getting one error.
Second, i would like to insert the data via php. Everytime, it can successfully add the data to the database, however, it always alert "Error: error". I dunno where does the error come from...
$(document).ready(function()
{
$('#test').click(function(){
validation();
});
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
}
else
{
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
}
else
{
}
//return false;
} // end of #validation
$('form').submit(function(){
validation();
$.ajax({
type: 'POST',
data:
{
loginID: $("#loginID").val(),
// some data here
},
url: 'http://mydomain.com/reg.php',
success: function(data){
alert('successfully.');
},
error: function(jqXHR, textStatus){
alert("Error: " + textStatus);
}
});
return false;
});
});
you can use return false.It will stop the execution
<form onSubmit="validatdeForm();"></form>
function validatdeForm()
{
//here return true if validation passed otherwise return false
}
or
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
it should be something like below. return false stop execution of script when error is there.
function validation(){
var loginID=$("#loginID").val();
if (loginID=="" || loginID==null)
{
$('#errorID').empty();
$('#errorID').append(
'<h6>' + "The Login Name cannot be empty" + '</h6>');
$("#errorID").show();
return false;
}
else
{
return true;
}
// check pw
$("#errorPW").hide();
if ($("#loginPW").val()=="" || $("#loginPW").val()==null)
{
$('#errorPW').empty();
$('#errorPW').append(
'<h6>' + "The Login Password cannot be empty" + '</h6>');
$("#errorPW").show();
return false;
}
else
{
return true;
}
return true;
} // end of #validation
Design your validation function as below,
function validation()
{
var isValid = true;
if(field validation fail)
{
isValid = false;
}
else if(field validation fail)
{
isValid = false;
}
return isValid;
}
basic idea behind code is to returning false whenever your validation fails.
To make a proper form validation, I will suggest you go about doing it in a more organized way. It is easier to debug. Try this:
var validation = {
// Checking your login ID
'loginID' : function() {
// Login ID validation code here...
// If a validation fails set validation.errors = true;
// Additionally you can have a validation.idError that contains
// some error message for an id error.
},
// Checking your password
'loginPW' : function() {
// Password validation code here...
// If a validation fails set validation.errors = true;
// As with id, you can have a validation.pwError that contains
// some error message for a password error.
},
'sendRequest' : function () {
if(!validation.errors) {
// Code for whatever you want to do at form submit.
}
}
};
$('#test').click(function(){
validation.errors = false;
validation.loginID();
validation.loginPW();
validation.sendRequest();
return false;
});
function validateimage() { if($("#photo").val() !== '' ) {
var extensions = new Array("jpg","jpeg","gif","png","bmp");
var image_file = document.form_useradd.photo.value;
var image_length = document.form_useradd.photo.value.length;
var pos = image_file.lastIndexOf('.') + 1;
var ext = image_file.substring(pos, image_length);
var final_ext = ext.toLowerCase();
for (i = 0; i < extensions.length; i++)
{
if(extensions[i] == final_ext)
{
return true;
}
}
alert(" Upload an image file with one of the following extensions: "+ extensions.join(', ') +".");
//$("#error-innertxt_photo").show().fadeOut(5000);
//$("#error-innertxt_photo").html('Enter valid file type');
//$("#photo").focus();
return false;
}

Check if a user Is fan of a Facebook page

After logged in I am trying to return if the user is either not a fan of a Facebook page, but the result is always "undefined". But if I replace "return" to "alert" works perfectly.
function pageFan()
{
FB.api({ method: 'pages.isFan', page_id: '175625039138809' }, function(response) {
showAlert(response);
});
}
function showAlert(response)
{
if (response == true) {
return 'like the Application.';
} else {
return "doesn't like the Application.";
}
}
var like = pageFan();
document.getElementById('debug').innerHTML = like; //return undefined
This question has already been answered.
Relevant Javascript:
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
That's because the return in showAlert is not returning "into" the pageFan function. The showAlert function is passed as a callback, meaning it will be called later, outside of pageFan's execution. I think you need to read more about callback functions and asynchronous programming.
function showAlert(response)
{
if (response == true) {
document.getElementById('debug').innerHTML = 'like the Application.';
} else {
document.getElementById('debug').innerHTML = "doesn't like the Application.";
}
}

Why does my form still submit when my javascript function returns false?

Here is my Javascript formvalidator function:
function companyName() {
var companyName = document.forms["SRinfo"]["companyName"].value;
if (companyName == ""){
return false;
} else {
return true;
}
}
function companyAdd() {
var companyAdd1 = document.forms["SRinfo"]["companyAdd1"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function companyCity() {
var companyCity = document.forms["SRinfo"]["companyCity"].value;
if (companyCity == ""){
return false;
} else {
return true;
}
}
function companyZip() {
var companyZip = document.forms["SRinfo"]["companyZip"].value;
if (companyZip == ""){
return false;
} else {
return true;
}
}
function enteredByName() {
var enteredByName = document.forms["SRinfo"]["enteredByName"].value;
if (enteredByName == ""){
return false;
} else {
return true;
}
}
function dayPhArea() {
var dayPhArea = document.forms["SRinfo"]["dayPhArea"].value;
if (dayPhArea == ""){
return false;
}
}
function dayPhPre() {
var dayPhPre = document.forms["SRinfo"]["dayPhPre"].value;
if (dayPhPre == ""){
return false;
} else {
return true;
}
}
function dayPhSub() {
var dayPhSub = document.forms["SRinfo"]["dayPhSub"].value;
if (companyAdd1 == ""){
return false;
} else {
return true;
}
}
function validateForm() {
if (companyName() && companyAdd() && companyCity() && companyZip() && enteredByName() && dayPhArea() && dayPhPre() && dayPhSub()) {
return true;
} else {
window.alert("Please make sure that all required fields are completed.");
document.getElementByID("companyName").className = "reqInvalid";
companyName.focus();
return false;
}
}
Here are all of my includes, just in case one conflicts with another (I am using jquery for their toggle()):
<script type="text/javascript" src="formvalidator.js"></script>
<script type="text/javascript" src="autoTab.js"></script>
<?php
require_once('mobile_device_detect.php');
include_once('../db/serviceDBconnector.php');
$mobile = mobile_device_detect();
if ($mobile) {
header("Location: ../mobile/service/index.php");
if ($_GET['promo']) {
header("Location: ../mobile/service/index.php?promo=".$_GET['promo']);
}
}
?>
<script src="http://code.jquery.com/jquery-1.7.1.js"></script>
Here is my form tag with the function returned onSubmit:
<form method="POST" action="index.php" name="SRinfo" onsubmit="return validateForm();">
The validation works perfectly, I tested all fields and I keep getting the appropriate alert, however after the alert the form is submitted into mysql and sent as an email. Here is the code where I submit my POST data.
if($_SERVER['REQUEST_METHOD']=='POST') {
// Here I submit to Mysql database and email form submission using php mail()
It would seem to me that this line is likely blowing up:
companyName.focus();
The only definition I see for companyName is the function. You can't call focus on a function.
This blows up so the return false is never reached.
I would comment out all the code in the validation section and simply return false. If this stops the form from posting then there is an error in the actual code performing the validation. Add each part one at a time until the error is found.
My guess is the same as James suggests that you are calling focus on the function 'companyName'. The line above this seems to be trying to get the element from the document with the same name but you are not assigning this to a variable so that you can call focus on it.

Categories

Resources