Submitting a form in an iframe with JavaScript - javascript

The iframe is on the same domain, I tried the following code, but none of it worked:
myframe.document.getElementById("myform").submit();
parent.top.frames[0].document.forms[0].submit();
myframe.document.getElementById("myform").submit();
MyIFrame = document.getElementById("myframe");
myIFrame.getElementById("myform").submit();
Update:
This is the HTML:
<html>
<body>
<iframe frameborder="0" scrolling="no" width="530" height="298"
src="/iframe.php" name="myframe" id="myframe">
<p>iframes are not supported by your browser.</p>
</iframe><br />
<form action="/styles.css" method="post" id="form1">
<input type="text" name="input1" value=""/>
<input type="text" name="input2" value=""/>
<input type="button" value="test" onclick="submitFrame()">
<input type="submit" value="submit">
</form>
<script>
function submitFrame(){
var MyIFrame = document.getElementById("myframe");
var MyIFrameDoc = (MyIFrame.contentWindow || MyIFrame.contentDocument);
if (MyIFrameDoc.document) MyIFrameDoc = MyIFrameDoc.document;
MyIFrameDoc.getElementById("myform").submit(); // ## error
}
</script>
</body>
</html>
iframe.php:
<form method="post" class="af-form-wrapper" id="myform" name="myform" action="/" >
<input type="text" name="input1" value="2073809442" />
<input type="text" name="input2" value="1" />
<input type="submit" name="submit" value="submit" />
</form>
Firebug says:
MyIFrameDoc.getElementById("myform").submit is not a function

Try this:
var MyIFrame = document.getElementById("myframe");
var MyIFrameDoc = (MyIFrame.contentWindow || MyIFrame.contentDocument);
if (MyIFrameDoc.document) MyIFrameDoc = MyIFrameDoc.document;
MyIFrameDoc.getElementById("myform").submit();
UPDATE
I can't figure out why this doesn't work, but here is something that does:
MyIFrameDoc.getElementById("mybutton").click();
iframe.php:
<input type="submit" name="submit" value="submit" id="mybutton" />
UPDATE 2
The reason you're getting the submit is not a function error is because you've named your submit button submit, so MyIFrameDoc.getElementById("myform").submit actually references an HTMLInputElement, not the HTMLFormElement.submit() method.
All you need to do is rename your submit button, e.g.:
<input type="submit" name="submit2" value="submit" />

Submit the Iframe's URL from javascript
if (window.parent.$("#IframeId").length > 0) {
window.parent.$("#IframeId")[0].contentDocument.forms[0].submit();
}

You do not need to post into iframe. You can use normal blank "visible" window. Define your form like this:
var request = document.createElement("FORM")
request.id = "request"
request.name = "request"
request.action = "callYour.php"
request.method = "POST"
request.target = "_blank"
and in your php, when you are done just close the window by:
window.close();
within the HTML part, or within embedded script tags. The new window temporarily opens up but closeses itself when it is completed.

Related

retrieve value from another page TAG

Here is a code to retrieve the value of a TAG which "id" is "token". This TAG is present in the page called "script.php". Javascript is working, but document.write(val) does not display anything...
<!DOCTYPE html>
<html>
<head>
<title>Void</title>
</head>
<body>
<iframe src="script.php" name="myFrame" id="myFrame"></iframe>
<script>
document.write('<br/>');
var doc = document.getElementById('myFrame');
var val = doc.contentWindow.document.getElementById("token").value;
document.write(val);
</script>
</body>
</html>
The page "script.php" contains the following code:
<form id="profile" action="" method="post" enctype="multipart/form-data">
<div>
<label>Username:</label>
<input id="username" type="text" name="username" value="az">
</div>
<br>
<div>
<label>Status:</label>
<input id="status" type="checkbox" name="status" disabled >
</div>
<br>
<input id="token" type="hidden" name="token" value="e4dea0c3a5a6246d98a6573f06ddfc97" />
<button type="submit">Submit</button>
</form>
As long as your iframe's domain is same as yours
var iframe = document.getElementById('myFrame');
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
alert(innerDoc.getElementById("token").value);
Several predefined variables in PHP are "superglobals" no matter their scope.For that reason you can access them from almost everywhere in your code.So try to reach them like that: var val = $GLOBALS['name_of your value'];

Issue with javascript retrieve form data for url

I am kind of new to javascript however I have created a submit form that I want to redirect me to a url based on form input. Here is my current code...
The issue I'm running into however is that the form is sending me the initial value rather than the updated form value (It is using "whatevs" no matter what).
HTML
<form id="Search-Form" onClick="genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Javascript
function genURL() {
var searchSubmit = document.getElementById("searchSubmit").value;
window.location = "randomsite/view" + searchSubmit;
}
Add return and use onsubmit:
<form id="Search-Form" onsubmit="return genURL()"><label>Value: </label>
<input type="text" id="search" placeholder="Enter Value"></input>
<div id="search-buttons">
<input id="searchSubmit" value="whatevs" type="submit" tabindex="1" />
</div>
</form>
Revise function like so:
function genURL()
{
location.href = "randomsite/view" + document.getElementById("search").value;
return false;
}
If you were to use onclick, it would go on the button, not the form.

Why does this code not add another field when clicking on the `add another field` input button?

Why does the following code not add another text input field when clicking on the add another field input button?
<html>
<head>
<script>
function add_field()
{
var elem = document.createElement("input");
elem.setAttribute('type','text');
elem.setAttribute('name','user');
document.body.insertBefore(elem, document.getElementById('su'));
}
</script>
</head>
<body>
<form name="input" method="get">
Put input here:<br>
<input type="text" name="user">
<input type="button" onclick="add_field()" value="Add another field"><br>
<input id="su" type="submit" value="Submit"><br>
</form>
</body>
</html>
According to the MDN reference page, you need to call parent.insertBefore(newElem, referenceElem). In your example, I suppose that <form> is the parent, not <body>. Changing the last line of your function to this:
var target = document.getElementById('su');
target.parentNode.insertBefore(elem, target);
will make it work.
jQuery solution here
<form name="input" method="get">
Put input here:<br>
<input id='ap' type="text" name="user">
<input id="addField" type="button" value="Add another field"><br>
<input id="su" type="submit" value="Submit"><br>
</form>
JavaScript
$('#addField').click(function(e)
{
$('<input type="text" />').insertBefore('#su')
});​​

onsubmit check if checked and change source

this doesn't seem to work, and resets checked...would like to only update if checked
<iframe id="time" name="time" type="text/html" src="http://time.is/"></iframe>
<form id="url" onsubmit="" method="post">
<input type="text" name="target" id="target" value="http://time.is" size="40"></form>
<input type="checkbox" name="check1" />
$('.url').submit {
if($('input[name="check1"]', this).is(':checked')) {
document.getElementById(time).src = url;
} else {
alert('no');
}
return false;
});
http://jsfiddle.net/ZZe5X/57/
Because you put check box out side the form but in code you call if ($('input[name="check1"]', this).is(':checked')) { should move check box inside form and also remove onsubmit=""
<div class="c">
<iframe id="time" name="time" type="text/html" src="http://time.is/" frameborder="0" allowtransparency="true"></iframe>
</div>
<form id="url" method="post" target="time">
<div>
<input type="text" name="target" id="target" value="http://time.is" size="40">
<input type="checkbox" name="check1" />
</div>
</form>
<script>
$(function(){
$('#url').submit (function(){
if ($('input[name="check1"]', this).is(':checked')) {
document.getElementById('time').src = url;
} else {
alert('no');
}
return false;
});
});
</script>
http://jsfiddle.net/ZZe5X/66/
There are multiple errors:
1.you need to add submit button inside html form (or have a way to trigger form submission with JavaScript), something like this:
<input type="submit"/>
2.the varible url is undefined, you may add the following line in the JavaScript
var url = $('#target').val();
3.
document.getElementById(time).src = url;
should be
document.getElementById('time').src = url;
4.change the first line of script from
$('.url').submit {
to
$('#url').submit(function() {
5.as Trinh Hoang Nhu said, check box should be inside form because you are using
if ($('input[name="check1"]', this)...
Here's the updated test

HTML form with two submit buttons and two "target" attributes

I have one HTML <form>.
The form has only one action="" attribute.
However I wish to have two different target="" attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.
How could I create two buttons, each submitting the same form, but each button gives the form a different target?
I do this on the server-side.
That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.
If you have multiple buttons, such as
<form action="mypage" method="get">
<input type="submit" name="retry" value="Retry" />
<input type="submit" name="abort" value="Abort" />
</form>
Note: I used GET, but it works for POST too
Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.
This method needs no Javascript.
Note: This question and answer was from so many years ago when "wanting to avoid relying on Javascript" was more of a thing than it is today. Today I would not consider writing extra server-side functionality for something like this. Indeed, I think that in most instances where I would need to submit form data to more than one target, I'd probably be doing something that justified doing a lot of the logic client-side in Javascript and using XMLHttpRequest (or indeed, the Fetch API) instead.
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.
<!DOCTYPE html>
<html>
<body>
<form>
<input type="submit" formaction="firsttarget.php" value="Submit to first" />
<input type="submit" formaction="secondtarget.php" value="Submit to second" />
</form>
</body>
</html>
This works for me:
<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />
<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />
In this example, taken from
http://www.webdeveloper.com/forum/showthread.php?t=75170
You can see the way to change the target on the button OnClick event.
function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}
<FORM name="myform" method="post" action="" target="" >
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">
Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!
<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">
<input type="submit" name="scheduled" value="Schedule Emails">
<input type="submit" name="single" value="Email Now">
</form>
twosubmits.php
<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}
if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
Example:
<input
type="submit"
onclick="this.form.action='new_target.php?do=alternative_submit'"
value="Alternative Save"
/>
Voila.
Very "fancy", three word JavaScript!
Here's a quick example script that displays a form that changes the target type:
<script type="text/javascript">
function myTarget(form) {
for (i = 0; i < form.target_type.length; i++) {
if (form.target_type[i].checked)
val = form.target_type[i].value;
}
form.target = val;
return true;
}
</script>
<form action="" onSubmit="return myTarget(this);">
<input type="radio" name="target_type" value="_self" checked /> Self <br/>
<input type="radio" name="target_type" value="_blank" /> Blank <br/>
<input type="submit">
</form>
HTML:
<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>
JS:
$('form').submit(function(ev){
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget)
})
http://jsfiddle.net/arzo/unhc3/
<form id='myForm'>
<input type="button" name="first_btn" id="first_btn">
<input type="button" name="second_btn" id="second_btn">
</form>
<script>
$('#first_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "https://foo.com";
form.submit();
});
$('#second_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "http://bar.com";
form.submit();
});
</script>
It is do-able on the server side.
<button type="submit" name="signin" value="email_signin" action="/signin">Sign In</button>
<button type="submit" name="signin" value="facebook_signin" action="/facebook_login">Facebook</button>
and in my node server side script
app.post('/', function(req, res) {
if(req.body.signin == "email_signin"){
function(email_login) {...}
}
if(req.body.signin == "fb_signin"){
function(fb_login) {...}
}
});
Have both buttons submit to the current page and then add this code at the top:
<?php
if(isset($_GET['firstButtonName'])
header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
if(isset($_GET['secondButtonName'])
header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>
It could also be done using $_SESSION if you don't want them to see the variables.
Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.
<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>
Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not
function v(){
var check = document.getElementsByTagName("input");
for (var i=0; i < check.length; i++) {
if (check[i].type == 'checkbox') {
if (check[i].checked == true) {
x[i]=check[i].value
}
}
}
console.log(x);
}
This might help someone:
Use the formtarget attribute
<html>
<body>
<form>
<!--submit on a new window-->
<input type="submit" formatarget="_blank" value="Submit to first" />
<!--submit on the same window-->
<input type="submit" formaction="_self" value="Submit to second" />
</form>
</body>
</html>
On each of your buttons you could have the following;
<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">
Then have a few small js functions;
<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}
function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>
That should do the trick.
e.submitEvent.originalEvent.submitter.value
if you use event of form

Categories