Calling function from <form> - javascript

I am aware that you are not able to use the onLoad attribute in a <form> like <form id"form" onload="javascript:test()">, you can only do this in a <body>
My question is, is there any attribute that you can put in the to call a function when the form is loaded or is there a different way to do this?
EDIT:
So like this is it
<form jwcid="form">
<script>
function checkForChange() {
var approvalStatus = document.getElementById('licensingStatus').value;
if(approvalStatus == "Pass"){
document.getElementById('licensingApprovalDate').setAttribute("validators", "validators:maxDateToday,required");
} else {
document.getElementById('licensingApprovalDate').setAttribute("validators", "validators:maxDateToday");
}
}
</script>
.....

Forms don't use external data to build them (the body can load images, iframes can load external documents, etc).
So:
</form>
<script> /* The form has loaded. Do your stuff */ </script>

What do you mean with "form is loaded"? I think you mean "when the form is submited". The attribute is "onsubmit": <form id="form" onsubmit="javascript:test()">
Your funktion has to return either true or false whether the form shall be submitted or not.

Related

Trying to CSRF/XSRF test our website - can I use an iframe to POST?

I'm trying to test a specific POST endpoint in our website from CSRF attacks.
To do this, I'm trying to use an iFrame. When I submit the form the entire page redirects. I was under the impression that the iFrame window should only do the form submit, not the entire (root?) document?
sample code...
<html>
<body>
<p>
<h3>CSRF Test.</h3>
Click Me
</p>
<form id="csrfForm" action="http://www.someWebsite/postTest" method="POST">
<snipped>
</form>
<iframe name="someiframe"></iframe>
<script type="text/javascript">
function crossDomainPost() {
var iframe = $('#someiframe');
var form = $('#csrfForm');
iframe.add(form);
// Submit the form in the iframe.
form.submit();
}
</script>
</body>
</html>
Try setting target on the form to be the iframe
<form id="csrfForm" action="url" method="POST" target="someiframe">
Also, if you want to use Javascript to handle the post (because the the form might not always want to target the iFrame..
<-- No target attribute here -->
<form id="csrfForm" action="url" method="POST">
...
function crossDomainPost() {
var form = $('#csrfForm');
form[0].target = "someiframe";
form.submit();
}
(Hat Tip: #charlietfl and his comments in the OP).

Sending form data to HTML Page and Retrieving it with Javascript without any PHP/Python

I've read a few articles and a question thread on sending form data to another html page, but the solutions didn't solve the issue for me.
Basically, I have a form with a bunch of data:
<form id="registration" name="registration" action="register.html" method="POST">
In register.html, I tried accessing an input text field with id and name as "username" with this:
var x = document.getElementById("registration").elements.namedItem("username").value;
The console stated that it cannot read property of null. How can I access these values with Javascript only? Frameworks are fine but not PHP /Python.
I'm sure that none of this can be safe, so use caution.
If you don't care about the info being super obvious, then you can make the action of the the form the new page you want, and the method can be 'GET'.
EDIT: I should mention this will go through the url, as such
domain.com?someKey=someValue&someOtherKey=someOtherValue
On the new page, you can parse the url for the query string for everything.
You can grab that stuff out of the 'href' property from the location.
window.location.href
// * Credit for this puppy goes to theharls, nice and fast
var params = window.location.search.slice(1).split("&");
//=> ["say=Hi", "to=Mom"]
Another option on (modern ?) browsers is Local Storage.
Use javascript to to set things like,
localStorage.setItem('foo', 'bar');
Great reference for local storage here.
https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
I ran into something like this the other day. Turns out you can just get the values with jQuery.
var userName = $("input[type=text][name=username]").val();
Just put it into a function that's called in the form's onsubmit.
<script>
function getFormData() {
var userName = $("input[type=text][name=username]").val();
// Do what you want with the data
return true;
}
</script>
<form id="registration" name="registration" action="register.html" onsubmit="return getFormData();" method="POST">
<input type="text" name="username" />
</form>
However, this doesn't keep the data when you load the next page. To do that, just commit the value into sessionStorage.
function saveFormData() {
var userName = $("input[type=text][name=username]").val();
sessionStorage.setItem("user", userName);
return true;
}
And then on the next page (the one you're calling resgister.html) you can use this code to retrieve it.
var userName = sessionStorage.getItem("user");
I hope this helps!
A webpage can't receive POST data. Send it using method="GET" instead, then retrieve it on the target page using JS as follows:
<script>
var params = window.location.search.slice(1).split("&");
// params is ["say=Hi", "to=Mom"]
</script>
You can easily target the selectors by querySelector. The value will no longer be null.
<form id="registration" name="registration" action="register.html" method="POST">
<input type="text" class="username" value="abcdefg">
</form>
<script>
var x = document.querySelector("#registration .username").value;
//check your code in devtools
console.log(x);
</script>
jsfiddle

Infinite form submit with $(document).ready

i want to create a post form it'll get data from my url and post it to my database.
When i clicked the "Add" buton its working fine but when i try to add with $(document).ready function, I'm getting infinite loop. (My goal is submitting form every time i execute the file)
I've no knowlage about jquery and Im using this code:
<script type="text/javascript">
$(document).ready(function () {
document.forms["form1"].submit();
});
</script>
How can I get rid off infinite loop?
I'm guessing your form does not have action-attribute, hence it posts to itself. Add action attribute to the page you want to post to:
<form action="mypage.html"....
You will have to use cookie to store first load information and check it before submitting form. Set the expire time as per your project requirement. Before using jQuery cookie, you have add cookie plugin after jQuery library.
jQuery Cookie: jQuery Cookie plugin.
<script type="text/javascript">
$(document).ready(function () {
if (! $.cookie("cookieName")){
document.forms["form1"].submit(); // do your stuff
$.cookie("cookieName", "firstSet", {"expires" : 7}); // set cookie now
}
});
</script>
Hope will help!
Can you try?
$(document).one("ready",function(){
// submit form here
});
Use below code.
<form action="yourformname.html" method="post" enctype="multipart/form-data">
</form>
<input type="submit" value="Submit">
If there is any file upload control, then use enctype in form tag.
Maybe a flag can do the job.
var flag = true;
$(document).ready(function(){
if(flag){
// submit code here
flag = false;
}
});
Inside your form paste this line,
<input type="hidden" name="ispost" value="0" id="ispost">
And in jQuery add this, your issue will be resolved
<script type="text/javascript">
$(document).ready(function() {
if($('#ispost').val() != 'submit')
{
$('#ispost').val('submit');
$('#form1').submit();
}
});
</script>

onsubmit property fails to open new window

A quick question here regarding forms. I've searched the web and can't seem to figure out why what I've implemented isn't working.
The idea is simple. I have a form inside a JSP page. The form has an 'onsubmit' property defined to open a different jsp with some parameters. Inside the form I have a few buttons, one of which calls a JavaScript function, which in turn submits the form (under some conditions).
Here's the code:
JSP:
...
<form id='testForm' onsubmit="window.open('another.jsp')">
<input type="button" onclick="callJsFunction()" />
..
</form>
JavaScript:
function callJsFunction() {
if (launchNow == 1) {
var form = document.getElementById("testForm");
form.submit();
}
}
If I add target="_blank" to the form definition, a new window does open, but NOT the jsp I want to open. Ultimately, I want the form to perform a servlet action (using the action attribute) and then open the new jsp. Any ideas???
Thanks!
The solution to what I was looking for is found here: Javascript Post on Form Submit open a new window
Rather than setting target="_blank", I can set the target to the window I define and open. In my servlet, I redirect to the desired jsp, and it appears in the new pop-up window.
<form id='testForm' action='another.jsp' target='_blank'>
I might be wrong but is this what you are looking for?
Please see the working demo at this link: http://fiddle.jshell.net/vf6AC/show/light/ (don't work in the jsfiddle)
<form action="http://google.com" id="testForm">
<input type="submit" />
</form>​
<script type="text/javascript">
var testForm = document.getElementById("testForm");
testForm.onsubmit = function(e){
window.open("http://stackoverflow.com");
return true;
};​
</script>
See the jsfiddle here: http://jsfiddle.net/vf6AC/

Script not executed after FORM element

I have an .aspx page. I populate a public variable in the code behind (.cs) page and then access that variable in JS on client side. I have the script declared after the FORM tag as below :-
<body>
<form>
...
</form>
<script language="javascript" type="text/javascript">
debugger;
var data = "<%=cSharpData%>";
</script>
</body>
After postback this script does not get executed first time, but when I click on any other server button on the page, then it gets executed.
Any idea why?
Is your postback done with ajax?
If so then only part of the page is refreshed and the script is not executed again.
You can wrap it in a function and add that function to the postback callback handler.
This is how I did it on one site:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () { edit.update(); });
Putting some Javascript after a <FORM> element does not mean it will get processed after the form has been submitted. It gets processed as the HTML is rendered, which is what you are seeing.
If you want to run some Javascript after POSTing a form then you need to use a onClick handler, something like this:
<FORM NAME="myform" ACTION="" METHOD="GET">
<INPUT TYPE="text" NAME="inputbox" VALUE=""><P>
<INPUT TYPE="button" NAME="button" Value="Click" onClick="dosomejavascriptstuff()">
</FORM>
have you tried to execute it with jquery $(document).ready()?
something like:
<script language="javascript" type="text/javascript">
$(document).ready(function(){....});
</scrip>
updated
without jquery
/* registr event on document load */
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", log4link, false );
} else if ( document ) {
document.attachEvent("onreadystatechange",function(){
if ( document.readyState === "complete" ) {log4link();}
});}
Thanks for your replies. I got closer to the issue but I do not know the solution :(
The C# variable contains a path info as "D:\" and when I set this on a JS variable I get the error as "Unterminated String Constant".
How do I overcome this.
Actually this was the problem, why the script was not getting executed. As soon as I removed the "\", it worked !

Categories