JavaScript form opens "infinite" tabs - javascript

I have a script which gets a form with fields filled by itself, and I got a code that submits the form automatically every x second(s).
The problem is that I added this attribute (target="_blank") to the form, but the form kept on executing the code and creating a new tab infinitely.
I want my script to create a new tab for processing the form and the second time my script executes, to use the same tab to refresh the processing page.
Can I do that in JavaScript?
<form target="_blank" name="myForm" id="myForm" action="process.asp" method="post">
field 1:<input type="text" name="field1" id="field1" /><br>
field 2:<input type="text" name="field2" id="field2" /><br>
</form>
<script type="text/javascript"> // code which executes the submit of form operation
window.onload=function(){
var auto = setTimeout(function(){ autoRefresh(); }, 100);
function submitform(){
document.forms["myForm"].submit();
}
function autoRefresh(){
clearTimeout(auto);
auto = setTimeout(function(){ submitform(); autoRefresh(); }, 10000);
}
}
</script>`

Please Try with this code (Using Ajax). It will help you with ajax and it not open any new tab and help to submit form with Last Updated Date and Time.
It work on My Base.
Please Try it with Your Code.
<html>
<head>
</head>
<body>
<form target="_self" name="myForm" id="myForm" action="process.asp" method="post">
field 1:<input type="text" name="field1" id="F1" />
<br>
field 2:<input type="text" name="field2" id="F2" />
<br>
<p id="LastDt"></p>
</form>
<script type="text/javascript"> // code which executes the submit of form operation
window.onload = function () {
var auto = setTimeout(function () {
autoRefresh();
}, 100);
function submitform() {
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("LastDt").innerHTML = "Last Update : " + new Date();
}
};
// It send data on process.asp (silently).
xmlhttp.open("POST", "process.asp?field1=" + document.getElementById("F1").value + "&field2=" + document.getElementById("F2").value , true);
xmlhttp.send();
}
function autoRefresh() {
clearTimeout(auto);
auto = setTimeout(function () {
submitform();
}, 10000);
}
}
</script>
</body>
</html>

You could add same form in process.asp and after the first submit opens the new tab...use postMessage API to pass data to other tab and have it submit from there.
Or you could store the data in localStorage and use storage events in process.asp to listen for updates and post the data

Related

How to check status without loop and not have application freeze

I am not a javascript coder, but was trying to figure out a solution with using HTML Web Forms and Javascript... However, I am using a while loop to keep checking the status of a submitted job, but because I am doing this, the page freezes. Is there way to check the status without having the page freeze?
<!DOCTYPE html>
<html>
<body>
<p><span style="background-color:{color}; border-radius:3px; color:#ffffff; float:right; font-size:16px; padding:2px 4px 2px 4px"><a id='downLoad' href="" download='file' style='display:none' target='_blank'>Save file As</a></span><span style="font-size:24px"><span style="color:#d52b40">Print Survey Report </span></span></p>
<p>Enter the project <b>Print ID</b> and <b>File Name</b> then submit the report for print. Repot may take a few minutes, but a <b>Save File As link</b> will show when ready for download. Right click and select <b>Save Link As</b></p>
<form id='printSurvey'>
<input type="hidden" id="portalUrl" name="portalUrl" value="https://transportation.bd.esri.com/portal">
<input type="hidden" id="templateItemId" name="templateItemId" value="a19dc0354ade4e9da65086453d89aa4a">
<input type="hidden" id="surveyItemId" name="surveyItemId" value="901946f3a7f940f4bab7bbda9d7595e3">
<input type="hidden" id="featureLayerUrl" name="featureLayerUrl" value="https://transportation-rh.bd.esri.com/server/rest/services/Geotech/GeotechProjectInfoPointSDE/FeatureServer/2">
<input type="hidden" id="token" name="token" value="toekn was removed">
<input type="hidden" id="outputFormat" name="outputFormat" value="docx">
<input type="hidden" id="uploadInfo" name="uploadInfo[type]" value="arcgis">
<input type="hidden" id="uploadInfo" name="uploadInfo[parameters][folderId]" value="6128cd36706f40ddaaa387e9296032a9">
<input type="hidden" id="uploadInfo" name="uploadInfo[parameters][conflictBehavior]" value="rename">
<label for="queryParameters">Print ID:</label>
<input type="text" id="queryParameters" name="queryParameters[objectIds]" placeholder="i.e 1"><br><br>
<label for="outputReportName">Report Name:</label>
<input type="text" id="outputReportName" name="outputReportName" placeholder="Logging Report Name"><br><br>
<input type="hidden" id="outputPackageName" name="outputPackageName" >
<input type="submit" type="buton" value="Submit">
</form>
<script>
document.getElementById("outputReportName").addEventListener('focusout',function () {
document.getElementById("outputPackageName").value = this.value;
});
const downLoadTag = document.getElementById('downLoad');
function httpGet(url){
let xmlHttpReq = new XMLHttpRequest();
var url = url +'?portalUrl=https://transportation.bd.esri.com/portal&token=token was removedenter code here'
xmlHttpReq.open("GET", url, false);
xmlHttpReq.send(null);
return JSON.parse(xmlHttpReq.responseText);
}
window.addEventListener("load", () => {
function sendData() {
const XHR = new XMLHttpRequest();
// Bind the FormData object and the form element
const FD = new FormData(form);
// Define what happens on successful data submission
setTimeout(XHR.addEventListener("load", (event) => {
//alert(event.target.responseText['jobId']);
var responseArray = JSON.parse(event.target.responseText);
var jobID = responseArray['jobId'];
var urlPath = 'https://survey123.arcgis.com/api/featureReport/jobs/'+jobID
var status = 'esriJobExecuting'
alert('Report is being generated... This may take several minutes');
var countEnd = 0
while (status != 'esriJobSucceeded') {
var getRep = httpGet(urlPath)
if (getRep['jobStatus'] == 'esriJobSucceeded'){
var itemID = getRep['resultInfo']['resultFiles'][0]['id'];
var urlBeg = 'https://transportation.bd.esri.com/portal/sharing/rest/content/items/';
var urlEnd = '/data?token=token was removed';
downLoadTag.href = urlBeg +itemID+urlEnd;
//console.log(getRep['resultInfo']);
status = getRep['jobStatus'];
//console.log(getRep);
alert('Report is ready for download')
};
};
downLoadTag.style='display:show';
}), 5);
// Define what happens in case of error
XHR.addEventListener("error", (event) => {
alert('Oops! Something went wrong.');
});
// Set up our request
XHR.open("POST", 'https://survey123.arcgis.com/api/featureReport/createReport/submitJob');
// The data sent is what the user provided in the form
XHR.send(FD);
};
// Get the form element
const form = document.getElementById("printSurvey");
// Add 'submit' event handler
form.addEventListener("submit", (event) => {
event.preventDefault();
sendData();
});
});
</script>
</body>
</html>
I struggled with the same problem recently. There is a Web Workers API. It does everything in the background and doesn't block the main thread. It is easy to learn and understand. Just google Web Workers API and you will get it!

form button with javascript not function but adding "/?" to the end of my url

I have some simple code...
HTML:
<form>
<input type="text" placeholder="Search.." id='query'>
<button type="button" name="submitButton" id="submitBtn2" onclick="submitBtn()">SEND</button>
</form>
<iframe id="results" name="results" onload='javascript:resizeIframe(this);' src="javascript:void(0);"></iframe>
Javascript:
<script language="javascript" type="text/javascript">
function resizeIframe(obj) {
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
<script language="javascript" type="text/javascript">
function submitBtn() {
var search = document.getElementById('query').value;
console.log("search:" +search);
console.log(search.length)
if (search.length>0){
document.getElementById('results').src = 'data:text/html;charset=utf-8,' + escape('<h2>'+ search +'</h2>');
userAction(search);
}
}
</script>
<script language="javascript" type="text/javascript">
function userAction(res) {
var request = new XMLHttpRequest();
var api = 'myAPI';
var url= api + res;
request.open('GET', url, true);
request.onload = function () {
var data = this.response;
if (request.status >= 200 && request.status < 400) {
document.getElementById('results').src = "data:text/html;charset=utf-8," + escape(data);
} else {
console.log('error');
}
}
request.send();
}
</script>
Issue:
If I have a blank query field - then everything works as it should when I click the button (not changing anything - and I can see the logs from inside submitBtn()), however if I enter a value into the query field then when I click the button, it does not trigger my submitBtn() function.
Instead it redirects my url to "mycurrenturl"/? - I am not sure why it does this and adds /? to the end of my url.
The api I am trying to hit is an Azure functions HttpTrigger. I do not get the console.logs from within my submitBtn() function, so I am assuming it is an issue with the form when there is a value inputted?
Any help would be much appreciated.
Thanks!
The problem is only happening when you press Enter in the text field. That submits the form, it doesn't trigger a click on the button. The solution is to use the form's onsubmit handler:
<form onsubmit="submitBtn(); return false;">
return false; prevents the default submission action from happening.
If you do this, you can also remove the onclick from the submit button, and change it to type="submit". Then clicking on the button will trigger a form submit, which will then run the above code.

auto refresh DIV using AJAX and FORM with interval after pressing button

i have a simple javascript i use to feed a DIV with content from a script using AJAX. This happens only after the user clicks a button. What i want after the user pressed the button (once) and the DIV is filled with de output of the script:
disable the button
have the DIV to reload the script's output every 5 seconds using AJAX
< script language="Javascript">
function xmlhttpPost(strURL) {
var xmlHttpReq = false;
var self = this;
// Mozilla/Safari
if (window.XMLHttpRequest) {
self.xmlHttpReq = new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
self.xmlHttpReq.open('POST', strURL, true);
self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
self.xmlHttpReq.onreadystatechange = function() {
if (self.xmlHttpReq.readyState == 4) {
updatepage(self.xmlHttpReq.responseText);
}
}
self.xmlHttpReq.send(getquerystring());
}
function getquerystring() {
var form = document.forms['f1'];
var xword = form.xword.value;
qstr = 'addpost=' + escape(xword); // NOTE: no '?' before querystring
return qstr;
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>
<form name="f1">
<input name="xword" type="hidden" value="someword">
<input value="betaling gereed" type="button" name="btn" onclick='JavaScript:xmlhttpPost("script.php")'></p>
<div id="result"></div>
</form>
use setTimeout() javascript method as follows:
setTimeout ('xmlhttpPost("script.php")', 5000);
At the end of your updatepage() method, call this.
For example:
function updatepage(str){
document.getElementById("result").innerHTML = str;
setTimeout ('xmlhttpPost("script.php")', 5000);
}
To disable the button, you will need to add an id attribute to your button tag. Then you can disable like so:
document.getElementById('btn').disable();
To repeat the ajax call indefinitely:
var refresh = false,
btn = document.getElementById("btn");
btn.onclick = function(){
refresh = true;
this.disable();
fetchData("script.php");
}
function fetchData(strURL){
while(refresh){
setTimeout(xmlhttpPost(strURL), 5000);
}
}
And:
<form name="f1">
<input name="xword" type="hidden" value="someword">
<input value="betaling gereed" type="button" id="btn" name="btn"></p>
<div id="result"></div>
</form>
You are looking for JS Time Events?
w3shools jvascript time events
onclick="setInterval(func(), 5000)"
ok Edit:
i didnt test it, is to late
<input id="loadStuffButton" value="betaling gereed" type="button" name="btn" onclick='setInterval(xmlhttpPost("script.php"), 5000);'></p>
function xmlhttpPost(strURL) {
document.getElementById('loadStuffButton').disabled = true;
....
}
Edit 2: Test This
Quick and dirty without Ajax to show how setIntervalworks with 5 ms hehe
<form name="f1">
<input name="xword" type="hidden" value="someword">
<input id="loadStuffButton" value="betaling gereed" type="button" name="btn" onclick='setInterval(function(){xmlhttpPost("script.php")}, 500);'></p>
<div id="result">
test
</div>
</form>
<script>
i = 1;
function xmlhttpPost(strURL) {
document.getElementById('loadStuffButton').disabled = true;
updatepage(i++);
}
function updatepage(str){
document.getElementById("result").innerHTML = str;
}
</script>

Automatic click html button

I am making a chrome extension and I am stuck with javascript and pressing button on page. I have site with form like this on web(isn't mine so i can't edit it):
<input class="button" name="accept" type="submit" value=LoggIn">
And now I automatically open page with username and password filled but now I want that button will be clicked automatically.
Thx for help!
Edit:
I have code of script:
var tabID = 1;
chrome.tabs.create({index:tabID,url:"https://monostudby4frd.hisf.no:8001/",active:false,pinned:true},
function(tab) {
tabID = tab.id;
});
sleep(3000);
chrome.tabs.executeScript(null, {code:clickButton()});
sleep(3000);
chrome.tabs.getSelected(null, function(tab) {
chrome.tabs.remove(tabID);
});
function sleep(ms) {
var dt = new Date();
dt.setTime(dt.getTime() + ms);
while (new Date().getTime() < dt.getTime());
}
function clickButton() {
document.getElementById("accept").click();
}
And debugger says:
Uncaught TypeError: Cannot call method 'click' of null
Button inputs are simple: inputElem.click()
You can use jquery to trigger a click event.
You shouldn't really be auto-submitting a form, though.
<form onsubmit='doSomething();'>
<input id="submitButton" class="button" name="accept" type="submit" value="LoggIn">
</form>
<script type="text/javascript">
function doSomething() {
console.log("Clicked!");
}
$("#submitButton").trigger('click');
</script>

Trouble using simple ajax in jsp - contents populating and then disappearing

I am using a simple jsp to populate a drop down box (with addresses as options) based on an input parameter (postcode) using ajax in javascript. The javascript code is able to pull the required data, and sets the options in the select element, but just after a fraction of second, all changes disappear and the jsp is back to its initial state. Can you help me in troubleshooting the cause of this behaviour? Thanks in advance.
main JSP code: testajx.jsp
<form name="testform" method="POST" action="testajx.jsp" >
<h1><%=a%> testing <b>Postcode Lookup</b></h1>
<br>
<br>
<input type="text" name="ziporpostalcode" size="10" maxlength="7" value="<%=ziporpostalcode%>"/>
<input type="text" name="ziporpostalcodetest" size="10" maxlength="7" value=""/>
<input type="hidden" name="searchPostCodeHidden" value="">
<input type="button" name="searchPostCode" value="Search" onclick="if(ziporpostalcode.value == ''){alert('enter postcode');}else {searchPostCodeHidden.value = 'TRUE'; this.form.submit();}">
<input type="hidden" name="searchAddressHidden" value="">
<input type="button" name="test" value="test" onclick="alert(userAddress.value);alert('<%=userAddress%>');">
<input type=image name="op_xxx" value="Search Address xxx" src="\jsp\htdocs\assets\images2011\buttons\search_address.gif" alt="Search Address" onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />
<select name="userAddress" value="<%=userAddress%>" onchange="searchAddressHidden.value = userAddress.value; form.submit();">
<option>--- Select ---</option>
<%=addressOptions%>
</select>
<div id="ajax_res">a</div>
</body>
</form>
Results received from testajax.jsp:
<body>
<select name="userAddress">
<option>--- Select ---</option>
<%
String addressOptions = new String();
Picklist pl = new Picklist();
addressOptions = "";
String ziporpostalcode = request.getParameter("ziporpostalcode");
pl = PostcodeHandler.getAddressList(ziporpostalcode);
PicklistItem[] pli = pl.getItems();
//Iterator li = sAddressList.values().iterator();
for(int i=0; i<pl.getTotal(); i++)
{
addressOptions += "<option label=\""+pli[i].getPartialAddress()+"\" value=\""+pli[i].getMoniker()+"\">"+pli[i].getText()+"</option>";
session.setAttribute("addressOptions", addressOptions);
request.setAttribute("ziporpostalcode", ziporpostalcode);
request.setAttribute("searchPostCodeHidden", ziporpostalcode);
// addressOptions += "<option label='"+sAddressList.get(i).toString()+"' value='"+sAddressList.get(i).toString()+"'>"+sAddressList.get(i).toString()+"</option>";
}
String str="This is JSP string loading from JSP page in ajax, loading time :";
out.print(addressOptions);
%>
</select>
ajax javascript code is:
<script language="Javascript" type="text/javascript">
function createRequestObject(){
var req;
try {
// Firefox, Opera, Safari
req = new XMLHttpRequest();
} catch (e) {
// Internet Explorer
try {
//For IE 6
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
//For IE 5
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera');
}
}
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == 'get' || method == 'GET'){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("ajax_res").innerHTML = response;
document.getElementById("ziporpostalcodetest").value = 'response';
document.getElementById("testform").action = 'testajax.jsp';
alert('received something from Ajax');
}
}
}
You're sending an ajax request in the onclick of an <input type="image"> submit button. However, you're not blocking the button's default behaviour when the onclick is finished. The button's default behaviour is namely submitting the form where it is sitting in. You need to block the button's default behaviour by returning false in the onclick.
So, change
<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value)"href="#" />
to
<input type=image ... onclick="sendRequest('GET','testajax.jsp?ziporpostalcode='+ziporpostalcode.value); return false;"href="#" />
Unrelated to the concrete problem, you've severe design problems with this all. I'm not sure where you've learnt HTML, JSP and Ajax, but this all looks very 90's. Make sure that you're reading up to date resources. This may be a good starting point: How to use Servlets and Ajax?
Just tired to search an error in your code. Here is my (don't foget include jQuery core):
<div id="content"></div>
<script type="text/javascript">
function updateDivContent() {
var result = jQuery.ajax({
url: "your url",
type: "POST",
async: true,
cache: false,
data: // your form data, can use serialize from jquery
});
jQuery("div#content").html(result.responseText)
}
</script>

Categories