So im having 2 functions. Problem is in styep_id variable. I know that i can just declare it in second functions, but then he wont take out data from first function. So the question is how i can use the same variable without lost data on him
P.S It shouldn't be public variable, cos it wont work. It wont hold the data.
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// Ja ir tikko kā pievienots, tad tikai izmetīsim ārā no DOM
if (!styep_id == "") {
estpt_action_links_td_jqobj = $(this).parent();
estpt_tr_jqobj = estpt_action_links_td_jqobj.parent();
stya_id = $("td.service-type-est-position-estimate-position-type-name>input.stya-id-for-styep", estpt_tr_jqobj).val();
estpt_tr_jqobj.remove();
show_stya_delete_link_if_possible(stya_id);
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"));
}
}
And
function save_configuration(){
var estpt_for_estpgt = "";
// Pārbaudam vai visām tāmes pozīciju grupām ir norādītas tāmes pozīcijas
$('.estpt-for-estpgt').each(function(){
if ($(this).find('tr.action_record_tr').size() == 0){
estpt_for_estpgt = this;
return false;
}
})
if (estpt_for_estpgt == "") {
var form = $(this).closest('form');
form.submit();
// Dzēsīsim ārā no datu bāzes
authenticity_token = $("#authenticity_token").val();
request_url = "/service_type_est_positions/" + styep_id + "/destroy_from_service_type_config";
$.post(request_url, { authenticity_token: authenticity_token}, process_service_type_est_position_delete, "json");
} else {
$.alerts.okButton = 'Labi';
jError("Vismaz vienai Tāmes pozīciju grupai nav norādīta neviena Tāmes pozīcija!", "Kļūda");
}
return false;
}
function remove_estpgt_if_has_no_estpt(estpgt_id) {
// Paskatīsimies vai eksistē kāda tāmes pozīcija
if ($("#estpt_for_" + estpgt_id + ">tr:first").size() == 0) {
$("#estpgt_" + estpgt_id).remove();
$("#estpt_tr_for_" + estpgt_id).remove();
}
}
call your second function within the first and pass the variable as an argument:
function delete_estimate_position_type() {
save_configuration(styep_id)
}
function save_configuration(id){
request_url = "/service_type_est_positions/" + id + "/destroy_from_service_type_config";
}
You can use like this
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
// Get it from argument.
function remove_estpgt_if_has_no_estpt(estpgt_id,styep_id ) {
// Paskatīsimies vai eksistē kāda tāmes pozīcija
if ($("#estpt_for_" + estpgt_id + ">tr:first").size() == 0) {
$("#estpgt_" + estpgt_id).remove();
$("#estpt_tr_for_" + estpgt_id).remove();
}
}
Another option is set it in hidden field.
// html
<input type = "hidden" id="styep_id_newval" value="">
// End of html
function delete_estimate_position_type() {
var estpt_tr_jqobj, estpt_action_links_td_jqobj, styep_id, authenticity_token, request_url, stya_id;
styep_id = $(this).attr("styep_id");
// your other code goes here.....
$("#styep_id_newval").(styep_id.val());
// Your variable pass as argument
remove_estpgt_if_has_no_estpt($(this).attr("estpgt_id"),styep_id.val() );
}
}
Now you can easily access code using anywhere.
$("styep_id_newval").val();
Related
I have an html which has a form that a user could enter url if the value of the input text has www. in it i will create a variable and return it to the function then pass it to the ajax but it seems that when I check it(ajaxData var) in the console it says undefined.
<form action="" id="defaultForm">
<input type="text" id="url">
<button id="submit">Submit</button>
</form>
JS:
$(function () {
function myreturnValue() {
$('#defaultForm').submit(function () {
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
if (current.match('www.')) {
console.log('it already consists of www');
var returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
return returnValue;
} else {
var returnValue = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
return returnValue;
}
}); //end submit
}
var ajaxData = myreturnValue();
console.log(typeof ajaxData);
var data = 'data:{' + ajaxData + '}';
});
then in the ajax I will pass the data variable. I hope my explanation is kinda clear.
Currently in your code, myreturnValue function only execute a code to register an event listener to your form, without return value (your return statement will only be triggered on submit event), so that's why it will return undefined at the first time.
Try this:
Put your url detect logic in myreturnValue function
Then put a code to prevent default submit event to be fired
Finally register a event listener for submit button.
And your original regex www. means match www with one other character, like wwww. and www0. will be valid. You may consider changing it to other regex like this one
$(function() {
function myreturnValue() {
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
if (current.match(w)) {
console.log('it already consists of www');
var returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
return returnValue;
} else {
var returnValue = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
return returnValue;
}
}
$('#defaultForm').submit(function(e) {
e.preventDefault();
});
$('#submit').on('click', function() {
var data = 'data:{' + myreturnValue() + '}';
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="defaultForm">
<input type="text" id="url">
<button id="submit">Submit</button>
</form>
A few problems here.
Calling $('#defaultForm').submit(function () { binds a submit handler to the form. It does not submit the form nor execute the function. Please familiarize yourself with the documentation.
Your myreturnValue() doesn't return anything. You only have one top level line which is the above submit binding. Not only is it not executed, but return inside that function does not propagate up like you're expecting it to. Returning inside an event handler won't do anything in any context.
Don't declare vars inside if branches in general.
Here's a quick attempt to reorganize this code, but with this many problems the corrected code may depend on your specific needs.
(function () {
$('#defaultForm').submit(function (event) {
// prevent default form submit
event.preventDefault();
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
var value;
if (current.match('www.')) {
console.log('it already consists of www');
value = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
} else {
value = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
}
var data = 'data:{' + ajaxData + '}';
// Do whatever you want with data here
});
// If you want to now submit the form by hand...
$('#defaultForm').submit();
});
In your code, the myreturnValue() is only return the returnValue of the function in Submit. 'myreturnValue' function return anything because it doesn't any return value.
You executed unnecessary function to get the ajaxData.
To get the ajaxData, You only need to
$('#defaultForm').submit(function () {
contents
}
If fix the code simple...
$('#defaultForm').submit(function () {
var returnValue;
var w = 'www.';
var current = $('#url').val();
var appendW = w + current;
if (current.match('www.')) {
console.log('it already consists of www');
returnValue = 'site_url:' + current; //site_url:www.domain.com or http://
console.log(typeof returnValue);
} else {
returnValue = 'site_url:' + appendW; //www+url
console.log(current);
console.log(appendW);
console.log(returnValue);
}
console.log(typeof returnValue);
var data = 'data:{' + ajaxData + '}';
console.log('data : ', data)
});
Please, Note : http://codepen.io/onyoon7/pen/mRdJJV
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');"";
My JavaScript inside the head tag:
<script type="text/javascript">
function over1() {
var img1 = document.getElementById("1").src;
document.getElementById("big").src = img1;
}
function out() {
document.getElementById("big").src = "http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/shop-icon.png";
}
function london() {
var city = document.getElementById("city").value;
var check = city.toLowerCase();
var province = document.getElementById("province").value;
if (check == "london" && province == "ON") {
alert("Visit our company travel store at Masonville Mall!");
}
}
function checkinput() {
var email = document.contest.email.value;
var emailcheck = email.search("#");
if (!document.contest.name.value) {
alert("Enter a name!")
} else {
alert("Thank You " + document.contest.name.value + " " + document.contest.lastname.value + " For Entering The Contest!")
window.open(calculator.html,'_blank');
}
}
</script>
I have the simple JavaScript inside the HTML file, but Chrome won't read it. In Inspector View, it throws ReferenceErrors for all my functions. Please help.
Why do you say that, those are all functions, nothing is invoked from these functions. call the functions and see if they are invoked correctly or not
checkinput();
over1();
/* the rest of them */
When I am calling requestwidgets function under document.ready it is successfully getting called and call to handler is made.
But when the same function i am calling from some function it is not getting called
Note: This is only happening in IE11 browser
Below is the code
function CreateNewWidget() {
$elementName = $("#ux_widget_name").val();
$elementType = $("#ux_widget_type_dll").val();
$url = '?request=newelement&elementtype=' + $elementType + '&appguid=' + appguid + '&elementname=' + $elementName;
$.get($url, function (data) {
if (data == "True") {
RequestWidgets();
}
setTimeout("$.fn.slickBox.close()", 3000);
});
}
var elements = Array();
function RequestWidgets() {
$.get('/shared/test2.ashx?request=getelements&appguid=' + appguid, function (data) {
xmlDoc = $.parseXML(data);
elements = Array();
RenderElements(elements);
});
}
I am using jQuery to create an anchor and bind it with JavaScript function as follow:
$(document).ready
(
function()
{
var test = function(arg)
{
alert(arg);
}
var anotherTest = function(arg)
{
do something;
}
$('#id').click
(
var content = "Hello world";
var anchor = "<a href='javascript:void(0);' onclick='test(\"" + content + "\")' >test</a>";
$('#DivToBind').prepend(anchor);
);
}
);
And the problem is: the test function always alerts "a", no matter what the value of content is. If I change onclick function test to anotherTest, nothing happens but "anotherTest is not defined" appeared in the error console
Edit
To better identify my problem, I summarise my real code as follow
$(document).ready
(
function()
{
var deleteComment = function (comment)
{
commentInfo = comment.split('_');
var postid = commentInfo[0];
var enum = commentInfo[1];
var parentid = commentInfo[2];
var user = commentInfo[3];
var author = commentInfo[4];
var date = commentInfo[5];
$.get
(
"ajaxhandle.php",
{ref: 'commentdelete', pid: postid, d: date},
function(text)
{
if (text)
{
//alert(comment);
$('#' + comment).html('');
}
else
{
alert("Something goes wrong");
}
},
'text'
);
};
var test = function(arg) {alert(arg);};
$('#postCommentButton').click
(
function ($e)
{
$e.preventDefault();
var comment = $('#postdata').val();
var data = $('form#commentContent').serialize();
//alert(data);
$.post
(
"ajaxhandle.php",
data,
function($xml)
{
$xml = $($xml);
if ($xml)
{
//alert(45);
var success = $xml.find("success").text();
if (success == 1)
{
$('#postdata').val("");
var id = $xml.find("id").text();
var reference = $xml.find("reference").text();
var parentid = $xml.find("parentid").text();
var user = $xml.find("user").text();
var content = $xml.find("content").text();
var authorID = $xml.find("authorid").text();
var authorName = $xml.find("authorname").text();
var converteddate = $xml.find("converteddate").text();
var date = $xml.find("date").text();
var avatar = $xml.find("avatar").text();
comment = id + '\_wall\_' + parentid + '\_' + user + '\_' + authorID + '\_' + date;
//alert(comment);
var class = $('#wallComments').children().attr('class');
var html = "<div class='comment' id='" + comment + "' ><div class='postAvatar'><a href='profile.php?id=" + authorID + "'><img src='photos/60x60/" + avatar +"' /></a></div><div class='postBody' ><div class='postContent'><a href='profile.php?id=" + authorID + "'>" + authorName + " </a> <span>" + content + "</span><br /><div class='timeline'>Posted " + converteddate + "<br /><a href=''>Comment</a> | <a href=''>Like</a> | <a href='javascript:void(0);' onclick='deleteComment(\"" + comment + "\")' class='commentDelete' >Delete</a></div></div></div><div style='clear:both'></div><hr class='hrBlur' /></div>";
if (class == 'noComment')
{
//alert($('#wallComments').children().text());
//alert(comment);
$('#noComment').html('');
$('#wallComments').prepend(html);
}
else if(class = 'comment')
{
//alert(comment);
$('#wallComments').prepend(html);
}
}
else
{
alert("Something goes wrong");
}
}
else
alert("Something goes wrong");
},
'xml'
);
}
);
$(".comment").find('.commentDelete').click
(
function($e)
{
$e.preventDefault();
var comment = $(this).parent().parent().parent().parent().attr('id');
deleteComment(comment);
}
);
}
);
var test=... is inside a function, it's not going to be in scope on the page when you want to call it onclick the anchor.
to make it global you can leave off the var.
you could also do something like:
$(document).ready
(
function()
{
var test = function(arg)
{
alert(arg);
}
var anotherTest = function(arg)
{
//do something;
}
$('#id').click
(
function(){
var content = "Hello world";
var anchor = "<a href='javascript:void(0);'>test</a>";
$(anchor).click(function(){ test(content); });
$('#DivToBind').prepend(anchor);
});
}
);
Your example is incomplete. The call to bind click is missing a function wrapper (so it's a syntax error and won't even parse); there is no reference to calling anotherText;, and the anchor is never actually created, only a string. So it's not really possible to fix from there.
In general avoid creating dynamic content from HTML strings. As you are not HTML-escaping content, if it contains various special characters (<"'&) your script will fail and you may have a cross-site-scripting security hole. Instead, create the anchor and then write any dynamic attributes or event handlers from script:
$(document).ready(function() {
function test(arg) {
alert(arg);
}
$('#id').click(function() {
var content= 'Hello world';
$('test').click(function(event) {
test(content);
event.preventDefault();
}).appendTo('#somewhere');
});
});
It may be preferable to use a <button> styled like a link rather than a real link, since it doesn't go anywhere. A <span> styled as a link is another possibility, preferably with a tabindex attribute to make it keyboard-accessible in that case.
I think a lot of code is missing here.
But anyway, why won't you use jQuery power to bind events?
$(document).ready(function() {
var test = function(arg) {
alert(arg);
}
var anotherTest = function(arg) {
alert("another: " + arg);
}
$('#id').click(function() {
var content = "Hello world";
var anchor = $("<a href='#'>test</a>").click(function() { test(content); });
//apply anchor to DOM
});
});
I think this is what you're looking for:
$(document).ready(function() {
var test = function(arg) {
alert(arg);
};
var anotherTest = function(arg) {
alert("we did something else:" + arg);
};
$('#id').click(function() {
var content = "Hello world";
var anchor = $("<a>test</a>").click(function(event) {
event.stopPropagation();
// test(content);
anotherTest(content);
});
$('#DivToBind').prepend(anchor);
});
}
);
This example shows good use of event.stopPropagation(). Setting an anchor's href to void() or # is often a mistake.
If you're using jQuery, I would recommend using its event handler functions like so:
$(document).ready(function() {
var test = function(arg){
alert(arg);
}
var anotherTest = function(arg){
// do something;
}
$('#id').click( function(event){
var content = "Hello world";
var anchor = $("<a>test</a>");
anchor.click(function(event){
event.preventDefault(); // instead of javascript:void();
test(content);
});
$('#DivToBind').prepend(anchor);
});
});