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
Related
Here I'm trying to get the webpage and its contents and trying to modify the inner values and trying to post using ajax.
1.First I'm placing a url in first text box.
2.Then after clicking GET button, the html codes will be shown in 2nd text box..
3.After editing the codes, I'm trying to do post.
I tried to do this on an insecure web page(http) to train myself.. but didn't work.
const proxyurl = "https://cors-anywhere.herokuapp.com/";
var url ="";
var both;
function rstSrv()
{
let request = new XMLHttpRequest();
url = document.getElementById('getURL').value;
both = proxyurl+url;
console.log("Cons1:::"+request);
setTimeout(function()
{
if(request.status==200)
{
console.log("Cons2::"+(request.response));
var list=request.response;
document.getElementById('getInnerHtml').value=list;
console.log(list);
document.getElementById('get').innerHTML=list;
}
else
{
//console.log(`error ${request.status} ${request.statusText}`)
var list=(`error ${request.status} ${request.statusText}`)
document.getElementById('get').innerHTML=list;
}
},2000);
request.open("GET",both, true);
request.send();
}
function postVal()
{
var pstFile=document.getElementById('getPostInnerHtml').value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
document.getElementById("get2").innerHTML = this.responseText;
}
};
xhttp.open("POST", both, true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(pstFile);
alert("done");
}
<div style='length:100%;width:100%;overflow: auto'>
<div> Insert URL </div>
<input type="text" id="getURL" style=':50%;width:20%;overflow: auto'><br>
<button onclick="rstSrv()"> GET </button>
<div type="text" id="get" style='length:40%;width:100%'></div><br>
<div> Copy InnerHTML Values </div>
<input type="text" id="getInnerHtml" style=':50%;width:20%;overflow: auto'><br><br><br>
<div> Paste InnerHTML Values </div>
<input type="text" id="getPostInnerHtml" style=':50%;width:20%;overflow: auto'><br>
<button onclick="postVal()"> POST </button><br>
<div type="text" id="get2" style='length:40%;width:100%'></div><br>
</div>
I cant get what I did wrong. Can some one help me to sort it out.. Thanks in advance..
I am trying to auto-fill the form I entered from the site with javascript subdomains, but there is no problem like this.
When I Enter Date My URL:
www.example.com/example
But it works like this:
https://sub.example.com/example?from_date=21%2F02%2F2021&to_date=26%2F02%2F2021&num_adults=1&num_children=1&check_availabilities=
So when I enter a date in the subdomain, there is no parameter in the URL address. Is there any way I can pass this without parameters?
My Script and Form
function loadXMLDoc() {
var url = "http://example.com";
var parameters = "foo=bar&bar=baz"; // Construct you form values like field=value&field2=value2&...
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var response = xmlhttp.responseText;
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}
<div class="booknow-wrapper flexbox">
<div class="title" style="font-size: 26px; font-weight:600;"><span></span> </div>
<div class="col-auto">
<div class="booknow-card">
<div class="booknow-input">
<input type="date" name="from_date" id="arrival" value="from_picker" placeholder="Giriş Tarihi" required autocomplete="off">
</div>
</div>
</div>
<div class="col-auto">
<div class="booknow-card">
<div class="booknow-input">
<input type="date" name="to_date" id="departure" value="to_picker" placeholder="Çıkış Tarihi" required autocomplete="off">
</div>
</div>
</div>
And My Console Fetch
"referrer": "https://sub.exampla.com/booking",
"referrerPolicy": "strict-origin-when-cross-origin",
"body": -
"from_date=15%2F02%2F2021&to_date=28%2F02%2F2021&num_adults=1&num_children=1&check_availabilities=",
"method": "POST",
As long as you are in the same domain and you want to propagate some data you filled in a page in your sub-domain, you can save the data in a browser storage, such as localStorage or sessionStorage:
// register changes
window.localStorage.setItem(name, value);
window.sessionStorage.setItem(name, value);
// retrieving data
window.localStorage.getItem(name)
window.sessionStorage.getItem(name)
You can see following code in the snippet, but it will not work since it is sandboxed and localStorage is not allowed. You can run a test on the same code on JSFiddle. I write the snippet here just for reference.
// select your elements
let btnInput = document.getElementById('storage_example_btn');
let btn = document.getElementById('save_btn');
let chgInput = document.getElementById('storage_example_change');
let shwRes = document.getElementById('show_results');
let results = document.getElementById('results');
// when click on "Save Data" button
btn.addEventListener('click', () => {
// save input data to storage
sessionStorage.setItem('__SO_EXAMPLE_1__', btnInput.value);
});
// when the "onChange" input changes
chgInput.addEventListener('change', () => {
// save input data to storage
sessionStorage.setItem('__SO_EXAMPLE_2__', chgInput.value);
});
// when click on "Show Storage" button
shwRes.addEventListener('click', () => {
// get input data from storage
let res1 = sessionStorage.getItem('__SO_EXAMPLE_1__')
let res2 = sessionStorage.getItem('__SO_EXAMPLE_2__')
// show it in the result div
results.innerHTML = 'Session Storage<br/>Data from "Save Data" Input: ' +
res1 + '<br/>Data from "onChange" Input: ' + res2
});
Register data with a button:
<input id="storage_example_btn" type="date"/>
<button id="save_btn">Save Data</button><br/>
Register data <code>onChange</code>:
<input id="storage_example_change" type="date" />
<br/><br/>
<button id="show_results">Show Storage</button>
<div id="results"></div>
As localStorage implements the same interface of sessionStorage you can choose which one to use, depending on your application. Check from docs the differences.
I am working on a project to convert an old Irish dictionary that uses non-standardised spelling. The objective is to send the non-standardised text to an API that will convert it to standardised spelling.
The user should only have to click a button and the text will be sent behind the scenes to the API. The standardised spelling will return in two seconds and be seen on the webpage.
It sounds easy but is surprisingly difficult. The code for the API is here
The instructions for setting it up is
Here is code, both HTML and JavaScript, for running something similar:
window.addEventListener("load", function () {
var form = document.getElementById("IGform");
form.addEventListener("submit", function (event) {
event.preventDefault();
var XHR = new XMLHttpRequest();
XHR.onreadystatechange = function(event) {
if (XHR.readyState == XMLHttpRequest.DONE) {
if (XHR.status == 200) {
processPairs(JSON.parse(event.target.responseText));
}
else {
var div=document.getElementById("output");
div.innerHTML=XHR.status.toString()+': '+XHR.statusText;
}
}
};
XHR.open("POST", "https://cadhan.com/api/intergaelic/3.0");
XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
XHR.setRequestHeader('Accept','application/json');
var payload = '';
var radios = document.getElementsByName('foinse');
for (var i=0; i<radios.length; i++) {
if (radios[i].checked) {
payload = 'foinse='+radios[i].value+'&teacs=';
break;
}
}
payload += encodeURIComponent(document.getElementById('sourcetext').value);
XHR.send(payload);
var div=document.getElementById("output");
div.innerHTML='<em>Translating...</em>'
});
});
function processPairs(arr) {
var div=document.getElementById("output");
var suppress = true;
div.innerHTML='';
for(var i=0; i<arr.length; i++) {
t=arr[i][1];
if (t=="\\n") {
div.innerHTML+='<br/>';
suppress = true;
}
else {
if (suppress==false && !t.match(/^[.,\/;”:!?%})]$/)) {
div.innerHTML+=" ";
}
suppress = (t.match(/^[“\/$(\[#{]$/)!==null);
div.innerHTML+=t;
}
}
}
<form id="IGform">
<textarea rows="10" cols="40" id="sourcetext" name="teacs" wrap="virtual"></textarea>
<br/><br/>
<input type="submit" value="Submit"></input>
<input type="reset" value="Clear"></input>
<br/><br/>
Source language:<br/>
<input type="radio" name="foinse" value="gd" checked>Scottish Gaelic</input><br/>
<input type="radio" name="foinse" value="gv">Manx Gaelic</input><br/>
<input type="radio" name="foinse" value="ga">Pre-Standard Irish</input><br/>
</form>
<hr/>
<div id="output"></div>
What I am trying to create instead of a form is a text that is already formatted in HTML. The user can click a button and the JavaScript will send the text to the API and then the standardised spelling will be provided pretty quickly thereafter.
I hope that it is easy to understand. Any help with this matter would really appreciated.
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 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>