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

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>

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!

Cannot set input value with JS if it has 'autocomplete=off' attribute

EDIT: I have added more code and edited description to help to better illustrate the problem.
I have an input element with an 'autocomplete=off' attribute. I want to refresh the page and set that input text value to what was in it before (don't want the user to lose input data), so I store the value in the 'sessionStorage' and try to set that element with the stored value after the refresh; After form submission my input element gets blank. If I change my HTML page removing the autocomplete, it works fine (the element gets the value stored in the sessionStorage) but I don't want the autocomplete function for that element. There's a way to implement this?
JS:
function submitForm(e, op, id=NaN){
//e is used to build var notification//
//gonna skip details for the sake of simplicity//
var notification = 'somejson'
var formData = JSON.stringify(notification);
var xhr = new XMLHttpRequest();
if (op == 'add'){
sessionStorage.setItem("pv", $('#pv').val());
var pv = sessionStorage.getItem("pv");
sessionStorage.setItem('reload', 'true')
xhr.open("POST", "/sms_service/notifications/add", true);
xhr.send(formData);
xhr.onload = function() {
if (xhr.status == 200){
window.location.href = "/sms_service/notifications";
}
else {
window.location.reload();
document.getElementById("pv").value = pv;
console.log('pv', pv);
}
}
}
}
HTML:
<form onsubmit="event.preventDefault()" action="" method="POST" id="addForm" novalidate>
<div id="container">
<div class="col-8">
<input type="text" class="form-control" id="pv" autocomplete="off" show="on">
</div>
<span>
<button class="btn btn-primary btn-user" type="submit" value='add'
onClick="submitForm(this, 'add')" >Submit</button>
</span>
</div>
</form>
your code may have set the input value, then reset when reloading
the solution is
call document.getElementById("pv").value = pv;
at the top of the code
var pv = sessionStorage.getItem("pv");
document.getElementById("pv").value = pv;
sessionStorage.setItem("pv", $('#pv').val());
sessionStorage.setItem('reload', 'true')
xhr.open("POST", "/sms_service/notifications/add", true);
xhr.send(formData);
xhr.onload = function() {
if (xhr.status == 200){
window.location.href = "/sms_service/notifications";
}
else {
window.location.reload();
}
}
the previous possibility worked because the autocomplete function did function to fill in frequently used inputs

How to send multiple input values with same class name or id via ajax

I'm trying to send multiple input values via AJAX to my PHP script. It's working fine when I use getElementById. However I have the option to add a child. It iterates the input fields, then I get values only from the first child. I tried to use getElementsByClassName but it gives values as undefined. This is my code:
<div id="name-field" class="name-field row">
<div class="col-xs-12 col-sm-6 childname">
<div class="field text-left">
<label class="text-left">Name of child</label>
<input id="firstname" class="firstname" name="firstname" type="text" />
</div>
</div>
<div class="col-xs-12 col-sm-6 dateofbirth">
<div class="field text-left">
<label class="text-left">Date of birth</label>
<input type="text" class="date" id="thedate" />
</div>
</div>
</div>
Add Child
Next Step
//Iterate child function
jQuery(function($) {
$("#addChild").click(function() {
$(".name-field:first").clone().find("input").val("").end()
.removeAttr("id")
.appendTo("#additionalselects")
.append($('<a class="delete" href="#"><i class="fa fa-times"></i></a>'));
});
$("body").on('click', ".delete", function() {
$(this).closest(".name-field").remove();
});
});
//Sending values function
function btnSubmit(step) {
//Set Var with Name
//Set Var with DoB
if (step == 'step1') {
//values using ID
var Name = document.getElementById("firstname").value;
var DoB = document.getElementById("thedate").value;
//Values using classname
var Name = document.getElementsByClassName("firstname").value;
var DoB = document.getElementsByClassName("date").value;
//Create a Variable catVar Having the Var Name and Var DoB Concatinated with a --
var stepVar = Name + "--" + DoB;
$(".thevoornaam, .date").each(function() {
alert();
});
} else {
}
var xmlhttp;
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
}
}
xmlhttp.open("GET", "validations/btnSubmit.php?q=" + step + "&q2=" + stepVar, true);
xmlhttp.send();
}
I hope you guys understand what I'm trying to achieve with this, if I did't explain it correctly.
Thanks in advance.
using jQuery you can do it in this way.
var firstname = [];
$("#name-field .firstname").each(function(){
firstname.push($(this).val());
});
In firstname you will all the values.
Update
Here is a working pen.
https://codepen.io/smitraval27/pen/dmvwVB
document.getElementsByClassName("firstname")
returns an array... so the following will give you the elements value with index i. To get all the values you will need to do a ForEach.
document.getElementsByClassName("firstname")[0].value
Since you're using JQuery elsewhere, why not use...
$('.firstname')[0].val();
The most ideal way to do this is :
add a form wrapper to your fields (id="ajaxForm")
to have a name to all your form
fields and use the below code to generate the data to be passed to
your AJAX call
$("#ajaxForm").serialize()
The return value of $.serialize() can be directly used as the data for the ajax call
$("#ajaxForm").on("submit", function () {
var ajaxData = $("#ajaxForm").serialize();
$("#ajaxData").text(ajaxData);
$.ajax({
url:"",
type: "get",
data : ajaxData,
success: function (resp) {}
});
console.log(ajaxData);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="ajaxForm" onsubmit="return false" >
<input id="firstname" class="firstname" name="firstname" type="text" />
<input type="text" name="date" class="date" id="date" />
<input type="submit" value="submit">
</form>
<div id="ajaxData"></div>

Adding multiple forms and inputs with onclick events using javascript

I am currently working on an website project that my friends and I would like to publish in the future. I´m currently building the html and css side of the page and need to implement dynamic events (if that's how its called) in the page for customer input.
I have a very little understanding when it comes to javascript/jquery (I am able to get a general idea of what is happening, yet my syntax comprehension is poop) and have only a basic knowledge of html and css. Now, I am aware that my inquiry is extensive and I would really appreciate any help, or pointers in the right direction!
So far the different blocks of code that I have found and tried by googling have worked for me, but only in executing individual functions (e.g.: the toggle function works but the create.element function doesn't).
This is my current html code that I am trying to modify with Javascript:
<div class="bttiendas">
<button class="btndag">Agregar</button>
<button class="btndgu">Guardar</button>
</div>
<div class="rdatos">
<form class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>
</div>
What I am trying to accomplish with Javascript is as follows:
-To be able to create with javascript both .thf and .trf forms dynamically along with every other input/button that is inside each form with clicking the .btndag button (this is an onclick event followed by create.element if I'm not mistaken).
-For the .morehf <input button> have a hide/show toggle function for .trf and anything else inside that form.
-Toggle disabled in the .crf input text boxes with the .edithf <input button>.
-To be able to erase/remove both .thf and .trf forms (their input textboxes AND the buttons .morehf .edithf .erasehf) with the .erasehf <input button>.
-And to be able to save/submit (I am not sure which is the correct term here) any added and completely filled out forms fields (for when we want to send the changes to our database).
Again I would greatly appreciate any help you could give me, and thank you in advance for your time.
You can import jquery into your solution.
For step 1: you do not make sense. Do you mean you want to load data into your form from somewhere to edit data or something? how is this dynamic? It looks like static forms on a page.
For step 2:
<input class="morehf" onclick="toggleTrf()" type="button" value="+/-" />
<script>
function toggleTrf() {
$(".trf").toggle()
}
</script>
step 3:
<input class="edithf" onclick="disableInputs()" type="button" value="Edit" />
<script>
function disableInputs() {
if($(".crf").is(":disabled");){
//jquery 1.6+
$(".crf").prop('disabled', false);
//jquery 1.5 -
$(".crf").removeAttr('disabled');
}
else {
//jquery 1.6+
$(".crf").prop('disabled', true);
//jquery 1.5 -
$(".crf").attr('disabled','disabled');
}
}
</script>
step 4: it is not clear what you mean by erase the form but you can clear the text in the inputs
<input class="erasehf" thpe="reset" onclick="clearInputs()" value="Erase" />
<script>
function clearInputs() {
$("input").val("")
}
</script>
step 5:
<form action="some/path">
<input name="someName" type="text" text="random field" value="1" />
<button type="submit">submit</button>
</form>
That submit button will submit the form to whatever path you specify in your form action. As for saving to the database etc it is impossible to guess what technology you will use to do that.sorry about code formattin im typing on a phone.
I believe I have included everything the OP wanted. The non-jQuery approach (ES6). JSFiddle
First lets add a few helper variables:
let formSets = 0;
let createForm = function(id) {
return `<form data-id='${id}' class="thf">
<input class="morehf" type="button" value="+/-" />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="chf" type="text" placeholder="Lorem ipsum" readonly />
<input class="edithf" type="button" value="Edit" />
<input class="erasehf" type="reset" value="Erase" />
</form>
<form data-id='${id}' class="trf">
<input class="crf" type="text" placeholder="POS" readonly />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
<input class="crf" type="text" disabled />
</form>`;
};
Add the onclick event for the "add" function. We have to reassign the click events to the dynamically added elements or we could have done event delegation like I did for the remove button:
document.getElementsByClassName('btndag')[0].onclick = () => {
document.getElementById('a').innerHTML += createForm(++formSets);
for (let ii = 0; ii < formSets; ii++) {
document.getElementsByClassName("morehf")[ii].onclick = () => {
document.getElementsByClassName("trf")[ii].classList.toggle('hide');
}
document.getElementsByClassName("edithf")[ii].onclick = () => {
let form = document.getElementsByClassName("trf")[ii].children;
for (let i = 0; i < form.length; i++) {
let input = form[i];
if (input.disabled == true) {
input.disabled = false;
} else {
input.disabled = true;
}
}
}
}
};
Add the remove button a little differently using event delegation which allows us to target another element based on the parents target:
document.getElementById('a').onclick = function(e) {
let t = e.target;
if (t.className == 'erasehf') {
let me = t.parentNode;
let sib = me.nextElementSibling;
me.parentNode.removeChild(me);
sib.parentNode.removeChild(sib);
}
}
Finally, submit the data. This part is a little more vague simply because I am not exactly sure how you want the data formatted. But here is how you would submit the form using AJAX:
document.getElementsByClassName('btndgu')[0].onclick = function() {
Request("/linkto/save.asp").post({
//datahere
}).then(function () {
//on success
}, function () {
//on failure
});
}
Note that this uses a helper AJAX function that I made:
let Request = function(url, opt) {
// start loader
var AJAX = function(type, url, data, success, failure, cache) {
var InitRequest = new Promise(function(accept, reject) {
var request = new XMLHttpRequest(); // initiate new XMLHttpRequest
var done = false;
var compile = function(data) { //turn the data object into a usable source for the send function
var send = [];
for (var item in data) { // compile all data in "item=data" strings
send.push(item + "=" + encodeURIComponent(data[item]));
}
send = send.join("&"); // combine data to form "item1=data1&item2=dat2&item3=data3"
return send;
};
// if we choose not send any data, then the data variable will take the place of the success variable
// because of this, we have to also shift the failure function
if (typeof data === "function") {
success = data || accept;
failure = success || reject;
data = "";
} else {
success = success || accept;
failure = failure || reject;
data = compile(data);
}
if (type.toUpperCase() == 'POST') {
request.open(type.toUpperCase(), url, true);
// this header allows POST requests to work
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
} else if (type.toUpperCase() == 'GET') {
// for GET requests, we need to put all data in the url
// we would end up with test.php?item1=data1&item2=dat2&item3=data3
request.open(type.toUpperCase(), url + "?" + data, true);
} else {
console.error('Incorrect request type submitted: "' + type + '" is not supported.');
return false;
}
// in order for laravel to properly send ajax requests
request.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
request.onreadystatechange = function() {
if (!done) {
if (request.readyState === 4) { // when the readyState == 4, we have completed the request
if (request.status === 200 || request.status === 0 /*for ff bug*/ ) {
success(request.responseText, request);
} else { //if failed
try {
request.responseJSON = JSON.parse(request.responseText);
} catch (e) {
return false;
}
failure(request);
}
// hide the loader because the request has finished
done = true;
}
}
};
// send off the request
request.send(data);
});
return InitRequest;
};
// The "opt" variable also goes into place as the
// Cache reset
if (opt && typeof opt !== "string" && typeof opt !== "boolean") {
var DEFAULTS = {
type: "GET",
data: {},
cache: false,
success: function() {},
failure: function() {}
};
var o = $.extend(DEFAULTS, opt);
return AJAX(o.type, url, o.data, o.success, o.failure, o.cache);
} else {
return {
post: function(data, success, failure, cache) {
return AJAX("POST", url, data, success, failure, cache);
},
get: function(data, success, failure, cache) {
return AJAX("GET", url, data, success, failure, cache);
}
}
}
}
A little more information about sending data via AJAX
Data in your case should correspond with the ids:
{
0: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
},
1: {
trf: {
input1: "..",
input2: "..",
input3: ".."
}
}
}

JavaScript form opens "infinite" tabs

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

Categories