I do not have much experience with programming and am looking for help figuring out why city and state webform fields are not getting populated by the google location api script when a form submits. We have about a 30% failure rate and don't appear to be hitting any api call limits and this is not due to invalid postal codes. Can't figure out what the issue is.
Background:
We have forms on our sites with these visible fields:
Name
Email
Postal Code
Country (picklist)
And these hidden fields (to be populated by a call from a script on the page):
City
State
The basic process we are looking for is:
When the user enters into the form a Postal Code length greater than or equal to 5 AND Country is not empty THEN call to google's location api and populate the forms hidden fields with City and State.
Here are the scripts we are using:
Script placed in Head:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
Script place before the body end tag:
<script type='text/javascript' >
$(document).ready(function() {
// Get city/state only if country has been selected and postal code is at least
// 5 characters long
$('#PostalCode,#Country').change(function() {
var postalCode = $('#PostalCode').val();
var countryCode = $('#Country option:selected').val();
if (postalCode.length >= 5 && countryCode !== '') {
getResponse(postalCode);
}
});
})
function getResponse(postalCode) {
var apiKey = 'OurAPIkeyIshere';
var baseUrl = `https://maps.googleapis.com/maps/api/geocode/json?&key=`;
var countryCode = $('#Country option:selected').val();
var componentFilter = `&components=country:${ countryCode }|postal_code:${ postalCode }&`;
var date = new Date();
var dateTime = `&_=${ date.getTime() }`;
var url = baseUrl + apiKey + componentFilter + dateTime;
$.support.cors = true;
$.ajaxSetup({ cache: false });
$.getJSON(url, function(response) {
var getStatus = response.status;
if (getStatus === 'OK') {
getCityState(response.results[0].address_components);
}
});
}
function getCityState(addressComponents) {
var city, state, nbhd, subLoc = '';
var hasCity, hasPostalTown, hasSubLoc = false;
$.each(addressComponents, function(index, addressComponent) {
var types = addressComponent.types;
$.each(types, function(index, type) {
switch(type) {
case 'postal_town':
postalTown = addressComponent.long_name;
hasPostalTown = true;
break;
case 'locality':
city = addressComponent.long_name;
hasCity = true;
break;
case 'sublocality':
subLoc = addressComponent.long_name;
hasSubLoc = true;
break;
case 'neighborhood':
nbhd = addressComponent.long_name;
break;
case 'administrative_area_level_1':
state = addressComponent.short_name;
break;
}
});
});
// set the city
if(hasPostalTown) {
$('#City').val(postalTown);
} else if(hasCity) {
$('#City').val(city);
} else if(hasSubLoc) {
$('#City').val(subLoc);
} else {
$('#City').val(nbhd);
}
// set the state
$('#State').val(state);
// reset flags
hasCity = false;
hasPostalCode = false;
hasSubLoc = false;
}
</script>
Related
I am making the payment using authorize.net weblink "https://test.authorize.net/gateway/transact.dll" on the sharepoint page.
After filling in the information and making the payment it doest not redirect the page on x_relay_url. Instead, it shows the error of "Sorry something went wrong" as below.
I tried to make the payment using sandbox account. it makes the payment transaction however after transaction it does not redirect on URL instead it shows the error.
var fingerprint1;
var amount1 = "95.00";
$(document).ready(function(){
});
function setFormAction(button) {
var theForm = $(button).parents('form:first')[0];
//sandbox
var loginid = "99NSdk8a"
var txnkey = "9s54MPz333NcVUm5"
//Randomize
var sequence = parseInt(1000 * Math.random());
var tstamp = GetSecondsSince1970 ()
//added for student rate--CHANGE THIS TO USE VARIABLES SET AT PAGE LOAD
if (theForm.student.checked) {
amount1 = "0.05";
} else {amount1 = "95.00"}
// set form action
if (theForm.payment_type[0].checked){
//theForm.action = "https://secure.authorize.net/gateway/transact.dll";
theForm.action = "https://test.authorize.net/gateway/transact.dll";
theForm.method="POST"
} else {
theForm.action = "http://trainingcenter.umaryland.edu/SaveRegistrations/save_registrationSuicidePrevention2019.aspx";
}
// set amount and fingerprint
theForm.x_amount.value = amount1;
theForm.x_fp_hash.value = fingerprint1;
theForm.submit();
return (true);
}
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');"";
I have the following code that is working in IE 8 but not in Chrome or Safari:
$(document).ready(function(){
$('.goRedIMG').on('click',function(event){
var ischecked = false;
var isOKtoSubmit = true;
var alertMessage = 'No tools have been selected';
var statusvar = '';
var transferstatusvar = '';
var action = $('#uTransaction option:selected').html();
$('.chkaction').each(function() { //loop through each checkbox
statusvar = $(this).closest('tr').children('.recordStatus').html();
transferstatusvar = $(this).closest('tr').children('.transferstat').html()
if($(this).prop('checked')) {
ischecked = true;
//alert(action);
// alert(statusvar);
// alert(transferstatusvar);
if (action == 'Recover'){
if (statusvar != 'OOS'){
// alert(statusvar);
isOKtoSubmit = false;
alertMessage = 'One or more records cannot be recoverd due to status not being OOS and Transfer Status not OK';
}
}
if(isOKtoSubmit && ischecked !== false && action !== '--Select One--'){
$('#toolActions').submit();
}else {
alert(alertMessage);
}
});
If a user chooses Recover and chooses a record that has a status that is in 'OOS' they are getting the alert message in Chrome that the record does not have the correct status. In IE if you choose the same record the alert message does not appear and that would be correct.
When I use your code like this:
var action = 'Recover';
var statusvar = 'OOS';
if (action == 'Recover') {
if (statusvar != 'OOS') {
alert('One or more records cannot be recoverd due to status not being OOS and Transfer Status not OK');
}
}
in both browsers it runs correctly. I think you have problem with your data.
In your original code try to use
alert(statusvar + ' - length:' + statusvar.length)
And check the character lenght of the variable. This way you can see if there is any funny character in your statusvar variable.
In this Code i try to get the value from text-field and dropdown listbox , I get values dynamically from user and send that value to webserices, In Given code get the value pass that values to webservice through javascript, but script didn't reponse to that code.. any one help me to fix this problem.
Here Code:
<body style=" "><script type="text/JavaScript" >
var xmlhttpuserid;
functionmyFunction() {
var checkid=new Array();
var userid = document.getElementById("userid").value;
for(var i=0;i<2;i++)
{
if(document.getElementById('domainid'+i).checked==true)
{
checkid[i]=document.getElementById('domainid'+i).value;
alert(checkid);
}
}
// var domainid = document.getElementById("").value;
//alert(userid);
var url= "../webservice/Passwordstation/ws_userauthpwdstation.jsp? userid="+userid+"&domain="+checkid;
alert(url);
xmlhttpduserid=GetXmlHttpObject();
if (xmlhttpduserid==null)
{
alert ("Your browser does not support Ajax HTTP");
return;
}
xmlhttpduserid.onreadystatechange=getuserid;
xmlhttpduserid.open("GET",url,true);
xmlhttpduserid.send(null);
}
function GetXmlHttpObject()
{
//alert("GetXmlHttpObject1");
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
function getuserid()
{
if (xmlhttpduserid.readyState==4)
{
var text=xmlhttpduserid.responseText;
//alert(text);
text=text.replace(/^\s+|\s+$/g,"");
// alert("Text 2"+text);
if(text.match("SUCCESS"))
{
alert("Authenticate successfully");
window.location="accountmain.jsp";
}
else
{
alert("Please check your User id");
}
}
}
I hope this will help you .
You can get them in java script and pass them in the query as query parameter as already doing for user id .
// var domainid = document.getElementById("").value;
//alert(userid);
var textboxval = document.getElamentById("mytextbox").value;
var dropDown = document.getElementById("ddlViewBy");
var dropDownValue= dropDown.options[dropDown.selectedIndex].value;
var url= "../webservice/Passwordstation/ws_userauthpwdstation.jsp? userid="+userid+"&domain="+checkid&textboxvalue="+textboxval&selectedFromDropDown="+dropDownValue;
Im having a issue, I need to combine 2 scripts together. One of which is a validation and the other is variables/ajax script. I tried but i cannot get it to work. I put it within the script under the area that checks if it has the needfilled element attached however it submits without executing the ajax call.
Script 1:
$(document).ready(function(){
$("#loading").hide();
// Place ID's of all required fields here.
required = ["parentFirstName", "parentLastName", "parentEmailOne", "parentZip"];
// If using an ID other than #email or #error then replace it here
email = $("#parentEmailOne");
errornotice = $("#error");
// The text to show up within a field when it is incorrect
emptyerror = "Please fill out this field.";
emailerror = "Please enter a valid e-mail.";
$("#theform").submit(function(){
//Validate required fields
for (i=0;i<required.length;i++) {
var input = $('#'+required[i]);
if ((input.val() == "") || (input.val() == emptyerror)) {
input.addClass("needsfilled");
input.val(emptyerror);
errornotice.fadeIn(750);
} else {
input.removeClass("needsfilled");
}
}
// Validate the e-mail.
if (!/^([a-zA-Z0-9_\.\-])+\#(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/.test(email.val())) {
email.addClass("needsfilled");
email.val(emailerror);
}
//if any inputs on the page have the class 'needsfilled' the form will not submit
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
return true;
}
});
// Clears any fields in the form when the user clicks on them
$(":input").focus(function(){
if ($(this).hasClass("needsfilled") ) {
$(this).val("");
$(this).removeClass("needsfilled");
}
});
});
Script 2:
// Form Varables
var parentFirstNameVal = $("#parentFirstName").val();
var parentLastNameVal = $("#parentLastName").val();
var emailaddressVal = $("#parentEmailOne").val();
var parentPhoneVal = $("#parentPhone").val();
var parentAddressVal = $("#parentAddress").val();
var parentAddressContVal = $("#parentAddressCont").val();
var parentCityVal = $("#parentCity").val();
var parentStateVal = $("#parentState").val();
var parentZipVal = $("#parentZip").val();
var parentListenVal = $("#parentListen").val();
var codeVal = $("#code").val();
var getUpdateVal = $("#getUpdate").val();
input.removeClass("needsfilled");
$("#message-space").html('<br /><br /><span class="greenText">Connected to Facebook.</span><br />');
$("#loading").show();
var counter = 0,
divs = $('#div1, #div2, #div3, #div4');
function showDiv () {
divs.hide()
.filter(function (index) { return index == counter % 3; })
.show('fast');
counter++;
};
showDiv();
setInterval(function () {
showDiv();
}, 10 * 600);
alert(parentFirstNameVal);
$.ajax({
type: "POST",
url: "includes/programs/updateEmailsTwo.php",
data: "parentFirstName="+parentFirstNameVal+"&parentLastName="+parentLastNameVal+"&UserEmail="+emailaddressVal+"&parentPhone="+parentPhoneVal+"&parentAddress="+parentAddressVal+"&parentAddressCont="+parentAddressContVal+"&parentCity="+parentCityVal+"&parentState="+parentStateVal+"&parentZip="+parentZipVal+"&parentListen="+parentListenVal+"&code="+codeVal+"&getUpdate="+getUpdateVal+"&ref=<?php echo $_SESSION["refid"]; ?>",
success: function(data){
$("#message-space").html('<br /><br /><span class="greenText">Complete</span><br />');
divs.hide()
}
});
In addition to the suggestions that #JeffWilbert gave, I am going to follow it up with some more suggestions to make your code a bit more cleaner and efficient.
First, just like you did in script 1, where you have an array of field names, you can do the same for script 2. Below is an example of what you can do make your code a bit more readable.
var fields = ['parentFirstName', 'parentLastName', 'parentEmailOne', 'parentPhone'];
var fieldsValue = [], dataString;
for(i = 0; i < fields.length; i++){
fieldsValue.push(fields[i] + "Val=" + $('#' + fields[i]).val());
}
dataString = fieldsValue.join("&");
Second, If Script 2 is not dependent on any variable declared from Script 1, I would convert Script 2 into its own function and call it from Script 1. I think adding all that code inside the else like Jeff suggested is not best.
function Script2(){
//Script 2 Code
}
$("#theform").submit(function(){
//Call Script 2
});
And Third, If you are going to submit the form via AJAX and not through its default method, I would recommend using .preventDefault and then handle the flow of the submission inside the event handler function.
$("#theform").submit(function(e){
e.preventDefault();
//rest of your code here.
});
The code in script 2 needs to go inside script 1 where I marked below with a comment; if your code in script 2 is submitting the form via ajax call then you don't need to return true if no errors are found, by doing so your telling the form to submit normally.
if ($(":input").hasClass("needsfilled")) {
return false;
} else {
errornotice.hide();
// SCRIPT 2 CODE HERE BEFORE THE RETURN
// If the ajax call in script 2 is submitting your form via ajax then change
// the line below to return false so your form doesn't submit
return true;
}