We have a form that should post data to an external domain. We are aware of the cross-domain limitations, therefore we want to use JSONP.
All parts are working fine, except for the part that should prevent a default form submission that reloads the page. Below is the form.
The html page:
<html lang="en">
<head>
<meta charset="utf-8">
<title>test</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://gateway.wildfx.com/test.js"></script>
</head>
<body>
<form method="POST" id="wild">
<fieldset>
<label for="email">Your email:</label>
<input type="text" name="email" id="wild">
<p class="wild_err">invalid</p>
<p>
<input type="hidden" id="wild_v" name="v" value="test2">
<input type="hidden" id="wild_l" name="l" value="">
<input type="hidden" id="wild_i" name="i" value="identifier">
<input type="hidden" id="wild_s" name="s" value="10612">
<input type="submit" id="wild_button" value="Check">
</p>
</fieldset>
</form>
</body>
</html>
Below is the Javascript. However, if the wild form is submitted, the page reloads instead of transfering the data with JSONp. In addition even the submission2 log isn't logged.
If tried to replace the .submit() with .click for the from button with correct ID but it isn't working either. What is wrong with the script?
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
console.log('submission1');
$("#wild").submit(function(e) {
console.log('submission2');
e.preventDefault();
if (isValidEmailAddress(e["e"])) {
var e = {};
e["e"] = $("#wild_email").val();
e["v"] = $("#wild_v").val();
e["i"] = $("#wild_i").val();
e["s"] = $("#wild_s").val();
e["l"] = $("#wild_l").val();
(function() {
var wildAPI = "https://gateway.wildfx.com/testjsonp.php?jsoncallback=?";
$.getJSON( wildAPI, {
tagmode: e,
format: "json"
})
.done(function( data ) {
$(".wild_message_container").text('Success. you are in');
setTimeout(function() {
$("#wildnotifier-container").hide();
$("#wildnotifier-overlay").hide();
}, 5000);
});
})();
} else {
$(".wild_error").show();
$("#wild_email").addClass("wild_input_error");
}
});
You load jQuery
You load your script
Your script tries to add an event handler to the form
You add the form to your page
Step 3 fails because the form doesn't exist. Move the script so it is after the form. (Or put it in a function and call it with the DOM is ready).
Related
I am trying to prefill some fields which are passed from URL as parameter pair. Having
www.example.com.com/myForm#myinput=123
as href send to end users, I am going to prefill the form field "myinput" with "123" after opening the link. However, the users will also see www.example.com.com/myForm#myInput=123 in their browser.
That's why I want to erase "myInput=123" from their URL. The reason for doing that is I don't want my users to see or even change the values in URL while filling the form.
I've tried
history.pushState(null, '', '/modifedURL')
either in HTML body "onload" or jquery "doc ready". As far I tried so far, this works only standalone without any parameter in URL like "www.example.com.com/myForm", but not with the additional injected parameters.
Here is simplified version of code what I got so far. Notice that the modifyURL Method is called successfully, but takes no effect on URL:
<head>
<meta charset="utf-8" />
</head>
<body onload="prefill();">
Your Body Content
<!-- Scripts at the bottom for improved performance. -->
<!-- jQuery, required for all responsive plugins. -->
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form id="myForm" method="POST">
<input id="myinput" maxlength="50" name="myinput" type="text" />
<br>
<input type="submit" name="submit" />
</form>
<script>
$(document).ready(function() {
//do some code after html is loaded
});
/*
window.onload = function () {
}
*/
function prefill() {
try{
var currentURL = window.location.href;
var n = currentURL.search("#");
var sPageURL = currentURL.substring(n+1);
var urlVal = getURLVal(sPageURL);
document.forms["myForm"]["myInput"].value = urlVal;
//change URL is called, but cannot change the URL!
modifyURL();
} catch(e){
alert("error " + e);
return false;
}
return true;
}
function modifyURL() {
history.pushState(null, '', '/modifedURL');
//even alert will fire, so pushState is skipped!!
alert('URL modified');
}
function getURLVal(query) {
//parse parameter pair in url
}
</script>
</body>
You can include the data diretly in your HTML, if it's meant to always be the same.
There are two ways:
1. <input id="myinput" maxlength="50" name="myinput" type="text" value="123" />
this actually puts the value inside your input field
2. <input id="myinput" maxlength="50" name="myinput" type="text" placeholder="123" />
this only displays it before any real value is inserted by the user (on submit you don't get any value)
I hope this is useful for you
I am trying to combine data from two HTML forms and then post it as a single form which is working fine except that some elements are not being copied from one form to the other. I have defined the following javascript function to combine form elements:
var form = document.forms['auth_form'];
var issuedata = window.opener.document.getElementById('Create').elements;
for (var i = 0; i < issuedata.length; i++) {
var data = issuedata[i];
alert(data.innerHTML);
if(data.type !== "submit")
form.appendChild(data);
}
Actual files
This is the first form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var childWindow = null;
function child_open() {
childWindow = window.open('new.html', "_blank",
"resizable=no,width=600, height=280,top=200,left=200");
}
function parent_disable() {
if (childWindow && !childWindow.closed)
childWindow.focus();
}
</script>
</head>
<body onclick="parent_disable();">
<input type="button" value="Create Jira Ticket" onclick="child_open()" />
<form name="auth_form" id="Create" method="post">
<input name="bug_status" value="NEW" type="hidden">
<input name="rep_platform" value="All" type="hidden">
<input name="component" value="AFAS" type="hidden">
<input name="bug_severity" value="Beeper Call" type="hidden"/>
<input type="hidden" name="comment" value="hello hi"><br>
</form>
</body>
</html>
and this is second form:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript">
var count = 0;
function submit_and_close() {
var form = document.forms['auth_form'];
var issuedata = window.opener.document.getElementById('Create').elements;
for (var i = 0; i < issuedata.length; i++) {
var data = issuedata[i];
alert(data.innerHTML);
if(data.type !== "submit")
form.appendChild(data);
}
alert(form.innerHTML);
form.submit();
// close the window after form submission is complete.
var docLoaded = setInterval(function() {
if (document.readyState !== "complete") {
return;
}
clearInterval(docLoaded);
//window.close();
}, 30);
}
</script>
</head>
<body>
<header>
<div id="dialog" title="JIRA Dialog">
<h1>JIRA Credentials</h1>
</div>
</header>
<div>
<form name="auth_form" id="auth_form" method="post">
<label> User Name: </label> <input type="text" name="username"><br>
<label> Password: </label> <input type="password" name="password"><br>
<input type="button" value="Log In" onclick="submit_and_close()">
</form>
</div>
</body>
</html>
For example I am not able to see the following elements being copied over from 'Create' form to 'auth_form' in second html page.
<input name="rep_platform" value="All" type="hidden">
<input name="bug_severity" value="Beeper Call" type="hidden"/>
Even after spending sometime debugging, I am not able to figure out why some elements are being succesfully copied while others not.
.elements returns a live collection of elements. When you append an element from the collection, it gets removed from the collection, so your index i into the collection get out of sync, and therefore every other element gets skipped.
Instead, just append the first element from the collection until the collection is empty. (Just detach the submit button element when it is encountered). Alternatively, loop through the collection from last to first rather than first to last.
(querySelectorAll() works because it returns a static collection, rather than a live one.)
Try changing your second form from ...
var issuedata = window.opener.document.getElementById('Create').elements;
to
var issuedata = window.opener.document.querySelectorAll('input[name]');
... and replace all innerHTML with outerHTML
I'm trying to learn javascript by making a simple price checking website using the Best Buy products API.
How do I "run" the javascript? My form takes in a product ID number (the SKU) and sends it to validateSKU() on submit. The function processData(data) searches for the product using the SKU.
Nothing is happening when I test the site, and any help would be great; thanks!
<!DOCTYPE html>
<html>
<head>
<title>Learn JavaScript</title>
</head>
<body>
<form id="bestBuyForm" name="bestBuyForm" onsubmit="validateSKU()">
<input id="SKU" name="SKU" required="" type="text">
<label for="SKU">SKU</label>
<input id="email" name="email" type="email">
<label for="email">Email</label>
<input class="button" id="submit" name="submit" type="submit">
</form>
<script>
function validateSKU() {
var SKU = document.forms["bestBuyForm"]["SKU"].value;
var bby = require('bestbuy')('process.env.BBY_API_KEY');
var search = bby.products('sku=' + SKU);
search.then(processData);
}
function processData(data) {
if (!data.total) {
console.log('No products found');
} else {
var product = data.products[0];
console.log('Name:', product.name);
console.log('Price:', product.salePrice);
}
}
</script>
</body>
</html>
Use web console to see what does happen and read about the console API.
Try to bind validateSKU with HTML element addEventListener method. Also you should prevent default form behaviour which cause page reloading on submit. Call event.preventDefault().
Working example code:
<html>
<form id="someForm">
...
<button type="submit">Submit</submit>
</form>
<script>
function validateSKU(event) {
console.log('IT works');
event.preventDefault();
// ...here your code
}
var form = document.getElementById('someForm');
form.addEventListener('submit', validateSKU, false);
</script>
</html>
I have an html form that loads the main portion of a document, postload an ajax request goes off and gets an xml file that is parsed out to create 'sub' forms which can be updated/submitted. This is the form 'preload'
<html>
<head>
<script src="jquery.js">
<script src="jquery.forms.js">
<script>
$(document).ready(function () {
//Script to execute when form is loaded
loadOrder(unid);
});
</script>
</head>
<body>
<form id="mainform" name="main" method="post" action="whatever">
<input type="hidden" id="unid" name="unid" value="123" />
</form>
<div id="orderForms">
</div>
</body>
</html>
Here is the form post load :
<html>...
<div id="orderForms">
<form id="order_1" name="order" method="post" action="whatever">
<input type="hidden" id="pid_1" name="pid" value="123" />
<input type="hidden" id="unid_1" name="unid" value="456" />
</form>
<form id="order_2" name="order" method="post" action="whatever">
<input type="hidden" id="pid_2" name="pid" value="123" />
<input type="hidden" id="unid_2" name="unid" value="789" />
</form>
</div>
</body>
</html>
JS code:
function loadOrders(unid){
var rUrl = "url";
$.ajax({type: "GET", url: rUrl, async: true, cache: false, dataType: "xml", success: postLoadOrders}) ;
}
function postLoadOrders(xml){
nxtOrder = 1;
var html="";
$('order',xml).each(function() {
// parses the xml and generates the html to be inserted into the <div>
});
$("#orderForms").html(html);
}
This all works, the main form loads, the 'hidden' forms in the <div> are written in. The trouble happens when I put a button on the main form that does this...
function submitOrder(){
$("#pid_1").val('555');
$("#order_1").formSerialize();
$("#order_1").ajaxSubmit();
}
If I alert($("#pid_1").val()) prior to the .val('555') it shows the original value, when I alert after, it shows the new value, however it submits the original value, and if I open the html in firebug the value isn't showing as changing.
If I put a hidden field into the main form, that exists when the document loads and change its value, not only does the new value post, it also shows as being changed when examining the source.
Any ideas?
$('order',xml).each(function() {
});
this is not Object in JQuery
You can edit:
$('[name=order]',xml).each(function() {
});
My Javascript is not redirecting. Here is what I tried:
<html>
<head>
<title>Hello world</title>
</head>
<body>
<form method="POST">
Search: <input id="searchterm" type="text" name="searchterm">
<input type="submit" value="Submit" onclick="processFormData()">
</form>
<script>
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = window.location.href + term;
}
</script>
</body>
</html>
I want user to be redirected to a specified url no matter of the url in browser. This should be universal on different machines. I am new to JS, please advise.
First, move the onclick event handler declaration to the <form> tag. Next, change it into an onsubmit event handler declaration. Finally add a return in front of it (to prevent default event handling, i.e. actually submitting the form):
<form method="POST" onsubmit="return processFormData();">
Search: <input id="searchterm" type="text" name="searchterm" />
<input type="submit" value="Submit" />
</form>
Then also add a return false; at the end of processFormData:
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = window.location.href + term;
return false;
}
Fiddle here: http://jsfiddle.net/xwcvq7bf/
Use location.host. Try this:
function processFormData()
{
var term = document.getElementById("searchterm").value;
window.location = "http://"+location.host+"/"+term;
return false;
}
And,
<form method="POST">
Search: <input id="searchterm" type="text" name="searchterm">
<input type="submit" value="Submit" onclick="return processFormData()">
</form>
So, now your url will be like this: http://www.example.com/searchTerm
You can specify the url itself,
window.location = "url"+term;
If you wanna get only the hostname(http://www.example.com),
window.location = location.hostname +"/"+term;
or If you wanna get the href(http://www.example.com/home/about.htm),
window.location = location.href +"/"+term;