How can I submit two forms on single click? - javascript

I have to submit two forms; one is on the page, while the other is coming through combo change event using jquery. I have to get both of these forms values on the same page. Please help me I have already wasted much time.
My code looks like this:
this function which i'm calling on the button click to submit both forms
function forms_submit()
{
document.form1.submit();
document.form2.submit();
}

You cannot submit two forms.. since your are in a browser, you can only end to one page.. and it depends on which form you submit.. (unless you go the ajax way)
perhaps you want to merge the forms in a single form in your HTML..
Give some more info/code to get some more specific answers..

You can use XMLHTTPRequest to send both forms, (but that requires two requests you'd be wasting instead of one)
I would recommend joining the forms together.
anyways a codesample,
btnSubmitBoth.onclick = function () {
var xmlReq,
data = getFormsData(); // needed to be in format of "something=1&sometinelse=2"
if (typeof XMLHttpRequest !== 'undefined' && (window.location.protocol !== 'file:' || !window.ActiveXObject)) {
xmlReq = new XMLHttpRequest();
} else {
try {
xmlReq = new ActiveXObject('Msxml2.XMLHTTP.6.0');
} catch(e) { }
try {
xmlReq = new ActiveXObject('Msxml2.XMLHTTP.3.0');
} catch(e) { }
try {
xmlReq = new ActiveXObject('Msxml2.XMLHTTP');
} catch(e) { }
}
xmlReq.open("post", url, true);
xmlReq.send(data);
}

If your submit your reason, probably I could submit your 2 forms
-----------edited--------------
var whatever ='<span id='updated_values'><input type=hidden></span>';
use $('#div').append(whatever);
Each time you select a category trigger the whatever to append the an existing form as hidden form type, you need to catch the variables at time of form submission.
Hope this solves your issue.

Related

Fill TextBox with data on page load using javascript

I'm working with a Google-Extention which allows me to open a new tab containing a form. After the form gets filled out and saved, every time I open this tab again the form should be prefilled with the data saved earlier.
Here is how the data gets saved: WORKS!
function saveCheckoutData() {
var vName = document.getElementById('txbx_name').value;
chrome.storage.sync.set({'name': vName}, function() {
console.log(vName);
})
}
Here is how i get the data: WORKS!
function getdata() {
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
The code above gets called on button click and works perfectly!
But as soon I try to do this when the tab gets opened it doesn't work (the tab gets opened but there is nothing in the textbox): DOESN'T WORK!
function configAutofill(){
var newURL = "autofill_data.html";
chrome.tabs.create({ url: newURL });
chrome.storage.sync.get('name', function(data) {
var name = data.name;
if(name != null){
document.getElementById("txbx_name").value = name;
}
});
}
Does some one have an Idea why these lines do not work when creating a new tab?
Many thanks in advance.
Here's a question for you.
After creating a new tab, you access document.getElementById. Yes, but which document?
In your case, it would be the page calling create - which is not the created page.
In your case, it seems like you're opening a page that's part of the extension. Then you should just include code in it that will run on load.
You may want to check document.readyState:
if (document.readyState === "loading") {
document.addEventListener('DOMContentLoaded', getdata);
} else {
getdata();
}
If you're trying to do this with a webpage, you'll need a content script. Again, those normally execute after DOM is parsed - so just call getdata() at top level.

My page won't stop advancing to next page, even if required fields are not filled in [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
I want to verify in JavaScript that my required fields are not blank
I posted this earlier and none of the solutions worked. I did use some of the advice so I'm probably closer. When the user submits, it advances to the next page even if the required fields are not completed. I want it so that if any required fields are blank, it does not advance. How should I change my code to accomplish this?
<script type="text/javascript">
function insert() {
if (window.XMLHttpRequest) {
xmlhttp = new XLMHttpRequest();
} else {
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
cn1 = 'child_name'+document.getElementById('child_name').value;
ag2 = 'age'+document.getElementById('age').value;
hm3 = 'hometown'+document.getElementById('hometown').value;
bg4 = 'boy_girl'+document.getElementById('boy_girl').value;
fn5 = 'first_name'+document.getElementById('first_name').value;
ln6 = 'last_name'+document.getElementById('last_name').value;
email = 'email'+document.getElementById('email').value;
ad8 = 'address1'+document.getElementById('address1').value;
ad9 = 'address2'+document.getElementById('address2').value;
ct10 = 'city'+document.getElementById('city').value;
st11 = 'state'+document.getElementById('state').value;
zp12 = 'zip'+document.getElementById('zip').value;
var flagInvalid = false;
var tempArray = document.getElementsByClassName("required");
for (var i = 0; i < tempArray.length; i++)
{
if (tempArray[i].value == ""){
flagInvalid = true;
break;
}
}
if (flagInvalid == false) {
xmlhttp.open('POST', 'payment.php', true);
xmlhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xmlhttp.send(cn1&ag2&hm3&bg4&fn5&ln6&email$ad8&ad9&ct10&st11&zp12);
} else {
alert ("Please enter all required fields.");
}
}
</script>
See this fiddle. Your logic seems to work fine. Is there something else going on with the page?
Is it just that flagInvalid is always coming up 'false'? and so the ajax call is always made?
EDIT: I had another thought. Are you running the insert() function from a button? Or an anchor tag. If you are using a button like this fiddle and your button is inside a form then it will still run the insert() function, but will submit the form right away and it might seem like your page is going somewhere else.
Try using the strict comparison operator on this line:
if (tempArray[i].value === ""){

javascript: GoToPage for my iframe with a remote source

I have a feed from Coupons.com in the form of an iframe in my webpage and I want to run some JavaScript on this iframe. I want it to open on a page other than the default which is the first page.
If you go to http://www.coupons.com you can see the same feed I am working with.
Above the coupons is a list of pages 1-10. If you move the cursor over page 3 (for example) it reads javascript:GoToPage(3), which seems very simple, but I can't figure out how to script it and make that page 3 show up instead of page 1. Please help, thanks in advance-
they are reloading the page via ajax.
something like that (copied from another question that i answered):
HTML
JAVASCRIPT
function xmlhttp() {
var x;
try {
x = new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) {
try {
x = new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
x = new XMLHttpRequest();
} catch (e) {
x = false;
}
}
}
return x;
}
function page(idMenu) {
var http = xmlhttp();
if (!http) {
alert('XmlHttpRequest non supporté');
} else {
var url = 'pageOutput.php?pageNo=' + idMenu;
http.open('GET', url, true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
document.getElementById('pageContent').innerHTML = http.responseText;
}
}
http.send();
}
}
now all you have left to do is create a PHP where you check whatever menu ID is called and echo page content according to $_GET['pageNo']. if you already got your pages on many PHP/HTML you may also just do include and echo them...
if(isset($_GET['pageNo'])){
//echo page code here according to $_GET['pageNo'] value
}else{
//echo main page
}
EDIT: You may also add URL param to refer the current page so the user can reload your page from a new window without having no params loaded...
EDIT: Iframe version will just reload the whole iframe, if you look when you change page you see the iframe blink. i strongly recommand using a div content, much easyer.

Dynamic multiple location form submit with javascript

I'm trying to write some JavaScript for my website that will select all the forms on a page, add an event listener for when they are submitted, and then route the values submitted to the main action page and an additional alternate page.
Here's what I have so far:
Send.php:
<script type="text/javascript">
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) {
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); // Not entirely sure if this is necessary
form.submit();
}
function addEvent(elm, evType, fn, useCapture) {
if (elm.addEventListener) {
elm.addEventListener(evType, fn, useCapture);
return true;
}
else if (elm.attachEvent) {
var r = elm.attachEvent('on' + evType, fn);
return r;
}
else {
elm['on' + evType] = fn;
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
}
else {
window.onload = function() {
oldonload();
func();
}
}
}
function addSubmits() {
var fs=document.forms;
for(var i=0;i<fs.length;i++){
//addEvent(fs[i],"submit",post_to_url('http://www.gwtwg.com/recieve.php', {'email' : 'test.com'}), false)
}
}
addLoadEvent(addSubmits);
</script>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"]; ?>">
<input type="text" name="email" />
<input type="submit" value="Submit!" />
</form>
Right now the script just freezes up, but if I replace: "post_to_url('http://www.gwtwg.com/recieve.php', {'email' : 'test.com'})"
with:
"alert("foobar")"
I get an alert when I load the page and when the form is submitted. (It should only occur when the button is submitted).
Any thoughts on whats wrong?
So, the problem here is really that you're not using any JS library. Personally I would recommend that you use jQuery, but any of the major ones will work. All of the functions you showed have more robust equivalents in the various JS libraries, so it's silly to try and debug them when you can just replace them with better-tested, more robust versions, for free.
If you were using jQuery, here's how (I think) you could do what you want to do:
var URL = "http://www.gwtwg.com/recieve.php"; // Define your site's URL
$(function() { // setup an onReady (similar to onLoad) handler
$("form") // get all forms on the page
.submit(function() { // hook up an onSubmit handler to them
var params = $(this).serialize(); // get this form's data
$.post(URL, paprams);// POST the data your server
});
});
Now, I haven't actually tested any of that, but it should work (and even if it doesn't, hopefully you get the idea). Also, notice how much shorter it is? Yet another benefit. The important thing though is, if you use established code, that's been reviewed by hundreds of eyeballs, you won't spend time re-inventing the wheel. Also, far more importantly, you won't waste time begging people on the Internet to help you debug your version of that wheel ;-)

Getting setting cookies on different domains, with JavaScript or other

I need to set/get the cookies stored at first.example while browsing second.example, I have full access of first.example but I only have JavaScript access (can manipulate the DOM as I want) on second.example.
My first approach was to create an iframe on second.example (with JS) that loaded a page like first.example/doAjax?setCookie=xxx and that did an AJAX call to say first.example/setCookie?cookieData=xxx which would set the cookie on first.example with the data we passed around.
That pretty much worked fine for setting the cookie on first.example from second.example - for getting a cookie I basically followed the same procedure, created the iframe that loaded first.example/doAjax?getCookie and that would do an AJAX call to say first.example/getCookie which would read the cookie info on first.example and return it as a JSON object.
The problem is that I'm unable to bring that JSON cookie object back to second.example so I can read it, well maybe I could just bring it when the AJAX call is complete using "window.top" but there's timing issues because its not relative to when the iframe has been loaded. I hope I am clear and was wondering if there's an easier solution rather than this crazy iframe->ajax crap, also seems like this won't even work for getting cookies in SAFARI.
You could inject a script element into HEAD of the document with a callback that passes the cookie you need to whatever function needs it.
Something like:
<script type="text/javascript">
var newfile=document.createElement('script');
newfile.setAttribute("type","text/javascript");
newfile.setAttribute("src", 'http://first.com/doAjax?getCookie&callback=passCookie');
document.getElementsByTagName("head")[0].appendChild(newfile);
</script>
And the page first.com/doAjax?getCookie could do this:
passCookie({'name':'mycookie', 'value':'myvalue'});
Put this PHP-File to first.com:
//readcookie.php
echo $_COOKIE['cookiename'];
On second.com you can use this javascript to get the value:
function readCookieCallback()
{
if ((this.readyState == 4) && (this.status == 200))
{
alert("the value of the cookie is: "+this.responseText);
}
else if ((this.readyState == 4) && (this.status != 200))
{
//error...
}
}
function buttonClickOrAnything()
{
var refreshObject = new XMLHttpRequest();
if (!refreshObject)
{
//IE6 or older
try
{
refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return;
}
}
}
refreshObject.onreadystatechange = readCookieCallback;
refreshObject.open("GET", "http://www.first.com/readcookie.php");
refreshObject.send();
}
Regards,
Robert
For SETTING cookies you can change my script as follows:
The new PHP-Script:
//writecookie.php
setcookie($_GET['c'], $_GET['v']);
And the JavaScript:
function buttonClickOrAnything()
{
var refreshObject = new XMLHttpRequest();
if (!refreshObject)
{
//IE6 or older
try
{
refreshObject = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
refreshObject = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
return;
}
}
}
refreshObject.open("GET", "http://www.first.com/writecookie.php?c=cookiename&v=cookievalue");
refreshObject.send();
}
That should work on all browsers.

Categories

Resources