How can I submit a form to a third-party website without it causing the page to reload (i.e. in the background)?
For some background, I'm trying to programmatically log a user into their google account in the background.
I can programmatically log them in using the following:
var div = document.createElement("div");
div.innerHTML = FORM_HTML;
var form = div.getElementsByTagName("form")[0];
form.action = "https://www.google.com/accounts/ServiceLoginAuth";
form.GALX.value = FORM_GALX; // dynamically obtained using AJAX
form.Email.value = USER_EMAIL;
form.Passwd.value = USER_PASSWORD;
form.submit();
This logs me in and opens up my Google dashboard. How can I prevent form.action from redirecting me?
Please note that this div is never actually added to a document, which is preferable but not required.
you can set the target to submit the form to an IFRAME
like that
<form target="transFrame" method="POST" action="http://...." ></form>
<iframe style="" name="transFrame" id="transFrame"></iframe>
You need to use AJAX to generate XMLHttpRequest best using any popular JS library such as jQuery, Prototype JS or Mootools.
you can use ajax or jquery for request to submit form in background if you want to submit form to secure connection i think they want allow submit form in this way..
Related
We are using a script that allows us to to change the follow up URLS of a form dynamically so we can use the same form across multiple assets but have different follow up pages.
The issue is that script only works when it loads the form itself rather than bringing it in via the visual editor. If we adjust the code as per the instructions on the developer site to make it work with the visual editor, it stops working.
We need to bring the form in via the editor because we have another script that only works on forms that are loaded in that manner. This script opens the follow up page in the parent window rather than the iframe.
Can you provide any suggestions?
Here's the code for the script:
Dynamic follow up URL:
<script type="text/javascript">// <![CDATA[
MktoForms2.whenReady(function(form){
//Add an onSuccess handler
form.onSuccess(function(values, followUpUrl){
//Take the lead to a different page on successful submit, ignoring the form's configured followUpUrl.
location.href = "http://solutions.healthcaresource.com/2346-staff-assessment-thank-you.html";
//return false to prevent the submission handler continuing with its own processing
return false;
});
});// ]]>
Use document.getElementById('iframe_id').src (given an iframe with an id of 'iframe_id'):
location.href = "http://solutions.healthcaresource.com/2346-staff-assessment-thank-you.html";
To this
document.getElementById('iframe_id').src = "http://solutions.healthcaresource.com/2346-staff-assessment-thank-you.html";
You can add Marketo variable to be able to give dynamic followup link.
Add following meta for variable, and use it in script. Code will be like this in your landing page.
<meta class="mktoString" id="ThankyouPage" mktoName="Follow-up Page" default="Add dynamic followup page here" allowHtml="false">
<script>
MktoForms2.whenReady(function (form) {
form.onSuccess(function(values, followUpUrl) {
location.href = ${ThankyouPage};
return false;
});
});
</script>
After submiting a form, a new page should open to be printed as pdf.
But by doing it like that <form action="page.php" method="POST" target="_blank"> the form with all the information still exists which is very, very bad. Instead of still showing the page with the form, I would now like to load another page within this windows/tab AND open
the print-window. With php and headers it's not possible, but with javascript should be right?
But how? I'm not used to javascript, so I have no idea how to handle this problem, but do you have an idea?
You can attach an onsubmit event to the form, f.ex:
document.getElementById('form').onsubmit = function() {
window.location = '/anotherpage.html';
}
This assumes that the form has an ID of "form".
I have a scenario where a user when clicks on a link, they are directed to a page in which I want to add a code to fetch a variable and redirect to another page.
i.e. user clicks on click here
on sample.tpl I want to write a code to redirect him to another page
<script>
window.location="http://example.com/?page_id=10"
but I want to send a variable too on this new link without appending it to the URL for security reasons.
How can I do it with some safe procedure?
Do ask me questions if it is not clear.
You could create a form with method="post", a hidden input with the value you want to pass and a submit button styled as a regular link (if you want to also manually send the form).
Then just submit the form manually or programmatically through the submit() method
Example (with automatic redirect after 3 seconds after page load)
http://jsbin.com/avacoj/1/edit
Html
<form method="post" action="http://mydomain.com/" id="f">
<input type="hidden" name="page_id" value="10">
<noscript><button type="submit">Continue</button></noscript> /* see below */
</form>
Js
window.onload = function() {
var frm = document.getElementById('f');
setTimeout(function() {
frm.submit();
}, 3000);
};
As a side note you may consider to insert a submit button inside <noscript></noscript> tag so the redirect will be possibile even when js is not available on the user device, so the page is still accessible.
Further to Fabrizio's answer someone has written a javascript function which will allow you to build the form and send it via POST at runtime.
POST is like GET (Where the variable is appended to the url) except the variable is sent via the headers. It is still possible to fake a POST request so you must perform some kind of validation on the data.
function post_to_url(path, params, method) {
method = method || "post"; // Set method to post by default, if not specified.
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", method);
form.setAttribute("action", path);
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
Used like so:
post_to_url("http://mydomain.com/", {'page_id':'10'}, "post");
Source: JavaScript post request like a form submit
We have a booking form that POSTs to the parent company website. Because this is a different domain we need to implement the GA _linkByPost to pass the GA tracking cookie info across domains.
As the booking form is in a .NET user control it does a postback. On postback we validate, wrap up the booking info, and write a form back to the client with hidden elements required by the target booking engine and add line of javascript to submit the form.
Below is the javascript function I'm using to submit the form:
function postBookingForm() {
var thisForm = document.getElementById('PostForm');
_gaq.push(['_linkByPost', thisForm]);
thisForm.submit();
}
And the relevant form info:
<form id="PostForm" name="PostForm" action="ClientBookingEngineUrl" method="post" >
booking form info in here
</form>
The result is that we fill in the form, hit submit which does a round trip to the server generates a new form and POSTs the info. This all works fine apart from the URL loses the GA cookie info from the query string. If I comment out the form submit line and look at source code I can see the GA cookie info on the querystring - but when posting, I do not see the querystring (using Fiddler).
To clarify:
The above technique works and does what we want with regards to POSTing form data to the booking engine and taking the user there.
If the submit line is commented out you can see the form with the modified action that has the GA stuff appended (using Firebug).
If the form is submitted with the submit line, the querystring info is removed (confirmed by Fiddler).
Am I missing something obvious? Are there some gotchas regarding JS submit, form POSTs and querystrings? Or is there a simple trick I'm missing?
Cheers
EDIT 1
An oddity has occured.
If I alert the form action before and after the _gaqPush then we can see the URL in its before and after state and it's as expected.
alert('1 form action = ' + thisForm.action);
_gaq.push(['_linkByPost', thisForm]);
alert('2 form action = ' + thisForm.action);
Alert 1 shows the pre-modified action and alert 2 shows the action with the GA info.
With the alerts in place it submits WITH the GA info in the query string.
If I comment out the alerts the GA info is NOT in the query string...
I'm starting to think the form or something is not ready so I'm trying it with JQuery's document ready.
EDIT 2
Wrapping the method call in document ready doesn't help. I'm confused as to why action URL is correct AFTER displaying it in an alert but incorrect if I don't alert it.
Answering this for posterity.
The problem is the _qaq (Google Analytics Queue) hasn't had time to modify the form before the call to submit() the form.
The solution is to push a function onto the _gaq object that submits the form so it will happen directly after the form modification is done.
function postBookingForm() {
var thisForm = document.getElementById('PostForm');
_gaq.push(['_linkByPost', thisForm]);
_gaq.push(function() { thisForm.submit(); });
}
I tried a simple HTML page that calls _gaqPush and submits immediately. This also fails.
Adding a 1000ms delay works (for the most part) so I suspect the alerts just gave the GA script time to modify the form.
I'm closing/accepting this as it seems down to submitting the form too quickly after the GA call.
I have HTML two forms, one that submits data upon entry to a database using PHP, the other directs the user to a paypal payment page, my problem is that the user would have to submit both forms which of course I do not want them to have to do. Is there anyway to use one submit button for two forms?
(Javascript is welcome)
You should be able to do this with JavaScript:
<input type="button" value="Click Me!" onclick="submitForms()" />
If your forms have IDs:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
If your forms don't have IDs but have names:
submitForms = function(){
document.forms["form1"].submit();
document.forms["form2"].submit();
}
A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));
document.forms.payPal.submit();
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.
The currently chosen best answer is too fuzzy to be reliable.
This feels to me like a fairly safe way to do it:
(Javascript: using jQuery to write it simpler)
$('#form1').submit(doubleSubmit);
function doubleSubmit(e1) {
e1.preventDefault();
e1.stopPropagation();
var post_form1 = $.post($(this).action, $(this).serialize());
post_form1.done(function(result) {
// would be nice to show some feedback about the first result here
$('#form2').submit();
});
};
Post the first form without changing page, wait for the process to complete. Then post the second form.
The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).
I didn't test the code, though.
If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();
if you want to submit two forms with one button you need to do this:
1- use setTimeout()
2- allow show pop up
<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);
}
</script>
<form target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>
javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.
edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.