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>
Related
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
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.
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
I have this Javascript and HTML code for my button:
function lockoutSubmit(button) {
var oldValue = button.value;
button.setAttribute('disabled', true);
button.value = '...processing...';
setTimeout(function(){
button.value = oldValue;
button.removeAttribute('disabled');
}, 3000)
}
<button style="margin-right:-160px;" type="submit" name="gen" onclick="lockoutSubmit(this)" class="btn btn-danger btn-block">Generate account!</button>
The code works fine for disabling the button for 3 seconds but the button is no longer posting to "gen".
Change the innerHTML instead of the value and bind the parameters to the settimeout instead of relying on the context.
Also button value might not be what you think it is:
http://www.w3schools.com/tags/att_button_value.asp
<html>
<head>
<script>
function _Unlock(){
var tB = document.getElementById('gen');
tB.removeAttribute('disabled');
tB.innerHTML = 'Generate account!';
localStorage.setItem('Lock', 0);
}
function Unlock(){
var tS = localStorage.getItem('Lock');
if (tS != '1') _Unlock()
else{
setTimeout(function(e, v){
_Unlock()
}, 3000)
}
}
function setToLock(){
localStorage.setItem('Lock', 1);
}
</script>
</head>
<body onload = 'Unlock()'>
<!-- Do you have a form and is it setup correctly? -->
<form action = '' method = 'post' id = 'myForm' onsubmit = 'setToLock()'>
<button id = 'gen' type = 'submit' name = 'gen' disabled = 'disabled'>...processing...</button>
<form>
</body>
</html>
So i am trying to make a function that searches trough an xml file, my results are given but the page is refreshed and keeps loading. I figured this was because of a submit but i used return false and i still have the same problem. Can anyone help me?
Below is my code
<script type="text/javascript">
function loadXMLDoc(XMLname)
{
var xmlDoc;
if (window.XMLHttpRequest)
{
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
else if (ActiveXObject("Microsoft.XMLDOM"))
{
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
</script>
</head>
<body>
<form id="oForm" name="oForm" onsubmit="search(); return false">
<input type="text" name="name" id="txt_name" size="30" maxlength="70">
<input type="submit" value="klik" onclick="search()"/>
</form>
<script type="text/javascript">
function search(){
name = document.oForm.name.value.toLowerCase();
xmlDoc=loadXMLDoc("data.xml");
var nodeList = xmlDoc.getElementsByTagName("article");
for (var i = 0; i < nodeList.length; i++) {
var titleNode = nodeList[i];
if(titleNode.getElementsByTagName("title")[0].childNodes[0].nodeValue.toLowerCase() == name){
document.write("<div style='width:450px;'>")
document.write("<p>"+titleNode.getElementsByTagName("title")[0].childNodes[0].nodeValue+"</p>");
document.write("<p>"+titleNode.getElementsByTagName("description")[0].childNodes[0].nodeValue+"</p>");
document.write("<p>"+titleNode.getElementsByTagName("urltext")[0].childNodes[0].nodeValue+"</p>");
document.write("</div>")
}
}
}
</script>
I would like to repeat that i do get results i only lose my layout and the page keeps loading. I made this for safari/safari mobile so i would apreciate it if someone could present a solution. I cant use any serversided scripts either since i need to be able to cache this offline so i figure it has to be javascript.
Ty in advance
EDIT
<input type="text" name="name" id="txt_name" size="30" maxlength="70">
<input type="button" value="klik" onclick="search();"/>
name = GetElementById("txt_name").value.toLowerCase();
Assuming the xml processing code works, do it like this - document.write WIPES the page
PS: Firefox MAY not work as expected due to linefeeds in the XML:
<html>
<head>
<script type="text/javascript">
function loadXMLDoc(XMLname) {
var xmlDoc;
if (window.XMLHttpRequest) {
xmlDoc=new window.XMLHttpRequest();
xmlDoc.open("GET",XMLname,false);
xmlDoc.send("");
return xmlDoc.responseXML;
}
else if (ActiveXObject("Microsoft.XMLDOM")) {
xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async=false;
xmlDoc.load(XMLname);
return xmlDoc;
}
alert("Error loading document!");
return null;
}
var xmlDoc=loadXMLDoc("data.xml");
var nodeList = xmlDoc.getElementsByTagName("article");
function search(theForm) {
var name = theForm.myname.value.toLowerCase();
var html = "";
for (var i = 0; i < nodeList.length; i++) {
var titleNode = nodeList[i];
if (titleNode.getElementsByTagName("title")[0].childNodes[0].nodeValue.toLowerCase() == name) {
html += "<div style='width:450px;'>";
html += "<p>"+titleNode.getElementsByTagName("title")[0].childNodes[0].nodeValue+"</p>";
html += "<p>"+titleNode.getElementsByTagName("description")[0].childNodes[0].nodeValue+"</p>";
html += "<p>"+titleNode.getElementsByTagName("urltext")[0].childNodes[0].nodeValue+"</p>";
html+= "</div>";
document.getElementById("result").innerHTML=html
}
}
return false; // cancel the submit
}
</script>
</head>
<body>
<form id="oForm" name="oForm" onsubmit="return search(this)">
<input type="text" name="myname" id="txt_name" size="30" maxlength="70">
<input type="submit" value="klik"/>
</form>
<div id="result"></div>
</body>
</html>
try this:
<input type="submit" value="klik" onclick="return search()"/>
and in the search method:
function search() {
.....
return false;
}
EDIT 1:
you can also add an event for the form itself:
<form onsubmit="return false">
(http://www.w3schools.com/jsref/event_form_onsubmit.asp)
EDIT 2:
This works for me:
<form onsubmit="return false">
<input type="submit" value="Go" onclick="alert('yo');"/>
</form>