Hey, you programmers have been extremely helpful to me in the past, so I thought I'd ask my question here, again. It's probably a simple fix, but I'm new to JavaScript and Ajax.
What I have working is Ajax that writes to a a responseText stating, "LOCATION NOT FOUND" if it is not found when a text field loses focus. What I'd like to have done is to prevent the form from submitting if this responseText is present. I know how to prevent the form from submitting if a hidden field has the value LOCATION NOT FOUND, so I was thinking that having JavaScript populate the hidden field with the responseText might be the easiest solution? Not sure if that will work or how to go about doing it.
Here's my current JS:
<script type="text/javascript">
<!--
function newXMLHttpRequest()
{
var xmlreq = false;
if (window.XMLHttpRequest)
{
xmlreq = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2)
{
alert("Error: Unable to create an XMLHttpRequest.");
}
}
return xmlreq;
}
function getLocation(locationrouting)
{
var getLocation= newXMLHttpRequest(); // sending request
getLocation.open("GET", "/PP?PAGE=GETLOCATIONNAME&ROUTINGNUM=" + locationrouting, false);
getLocation.send(null); // getting location
var dv = document.getElementById("location_div");
if (getlocation.responseText === 'LOCATION NOT FOUND')
{
dv.style.color = "red";
}
else
{
dv.style.color = "black";
}
dv.innerHTML = getLocation.responseText;
}
//-->
</script>
Here is the applicable part of the form:
<form name="locationform" id="locationform" action="/PP?PAGE=POSTADDLOCATION" method="post">
<tr>
<td class="ajax_msg">
<div id="location_div">/div>
</td>
</tr>
<tr>
<td>
<div class="column1" id="locationrouting_div">
<p class="label_top">
*Routing Number</p>
<p class="field_top">
<input type="text" id="locationrouting" name="locationrouting" size="28" maxlength="9" onblur="getLocation(this.value);" /></p>
...
Thanks in advance!
As an option you can create javascript variable var isSubmitAllowed = true;, set this variable to false when location is not found and check this variable to prevent form submitting.
Something like:
<script type="text/javascript">
<!--
var isSubmitAllowed = true;
function newXMLHttpRequest()
{
var xmlreq = false;
if (window.XMLHttpRequest)
{
xmlreq = new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
try
{
xmlreq = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e2)
{
alert("Error: Unable to create an XMLHttpRequest.");
}
}
return xmlreq;
}
function getLocation(locationrouting)
{
var getLocation= newXMLHttpRequest(); // sending request
getLocation.open("GET", "/PP?PAGE=GETLOCATIONNAME&ROUTINGNUM=" + locationrouting, false);
getLocation.send(null); // getting location
var dv = document.getElementById("location_div");
if (getlocation.responseText === 'LOCATION NOT FOUND')
{
dv.style.color = "red";
isSubmitAllowed = false;
}
else
{
dv.style.color = "black";
isSubmitAllowed = true;
}
dv.innerHTML = getLocation.responseText;
}
//-->
</script>
Then in Form tag you can add onSubmit event handler that will return isSubmitAllowed value:
<form name="locationform" id="locationform" action="/PP?PAGE=POSTADDLOCATION" method="post" onSubmit="return isSubmitAllowed">
If you don't want the form to submit if the location isn't found, the easiest way would probably be just query the server before submitting. This be a lot easier to implement and to use than checking the status of a query that may or may not have happened previously via its side effects. :D
Related
I am trying working off of https://wiki.apache.org/solr/SolJSON tutorial. I have put my url for solr in the code, copied from solr admin query result to make sure the query should return something.
I try typing in "title:Asian" into text box (that field/search term combo returned results in the admin console query) but when the button is hit, textbox just clears and nothing in output spot.
I used the dev tools from [F12] key of browser to check console and see there was no errors given there, such as for syntax, so not due to that.
Perhaps I am understanding how the url for query works or should be here? If I leave out local host part as shown I just get error for not specifying local full path.
Does anyone see anything wrong here, or have any ideas/tips of what more to do to try and solve the issue?
[ If I must do/add anything else to make good/better post here, please do explain so I can fix :) ]
<html>
<head>
<title>Solr Ajax Example</title>
<meta charset="UTF-8">
<script language="Javascript">
// derived from http://www.degraeve.com/reference/simple-ajax-example.php
function xmlhttpPost(strURL)
{
var xmlHttpReq = false;
var self = this;
if (window.XMLHttpRequest) { // Mozilla/Safari
self.xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) { // IE
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);
}
};
var params = getstandardargs().concat(getquerystring());
var strData = params.join('&');
self.xmlHttpReq.send(strData);
//document.getElementById("raw").innerHTML = strData;
return false;
}
function getstandardargs() {
var params = [
'wt=json'
, 'indent=on'
, 'hl=true'
];
return params;
}
function getquerystring() {
var form = document.forms['f1'];
var query = form.query.value;
qstr = 'q=' + escape(query);
return qstr;
}
// this function does all the work of parsing the solr response and updating the page.
function updatepage(str)
{
document.getElementById("raw").innerHTML = str;
var rsp = eval("("+str+")"); // use eval to parse Solr's JSON response
var html = "<br>numFound=" + rsp.response.numFound;
var first = rsp.response.docs[0];
html += "<br>product name=" + first.name;
var hl = rsp.highlighting[first.id];
if (hl.name != null) { html += "<br>name highlighted: " + hl.name[0]; }
if (hl.features != null) { html += "<br>features highligted: " + hl.features[0]; }
document.getElementById("result").innerHTML = html;
}
</script>
</head>
<body>
<form name="f1" onsubmit='xmlhttpPost("http://localhost:8983/solr/myCore/select?")'>
<p>query: <input name="query" type="text">
<input value="Go" type="submit"></p>
<div id="result"></div>
<p/><pre>Raw JSON String/output: <div id="raw"></div></pre>
</form>
</body>
</html>
I have form as follows, it require to sent an action to my java Servlet to do an update to the database.
How do I submit the form without the page get reloaded here?
Currently with action="myServlet" it keep direct me to a new page. And if I remove the action to myServlet, the input is not added to my database.
<form name="detailsForm" method="post" action="myServlet"
onsubmit="return submitFormAjax()">
name: <input type="text" name="name" id="name"/> <br/>
<input type="submit" name="add" value="Add" />
</form>
In the view of my Java servlet, request.getParameter will look for the name and proceed to add it into my db.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if (request.getParameter("add") != null) {
try {
Table.insert(name);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
In my JavaScript part, I have a submitFormAjax function
function submitFormAjax()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
alert(xmlhttp.responseText); // Here is the response
}
var id = document.getElementById("name").innerHTML;
xmlhttp.open("POST","/myServlet",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=" + name);
}
A similar question was asked here
Submit form without reloading page
Basically, do "return false" after invoking the function. Something like this should work:
<form name="detailsForm"
method="post"
action="myServlet"
onsubmit="submitFormAjax();
return false;"
>
This is how I used to implement Ajax in JS without JQuery. As am a PHP and JS guy I cant possibly help you with Java Servlet side but yes heres my little help from JS side. This given example is a working example.See if it helps you.
// HTML side
<form name="detailsForm" method="post" onsubmit="OnSubmit(e)">
// THE JS
function _(x){
return document.getElementById(x);
}
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/json");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function OnSubmit(e) // call this function on submit
{
e.preventDefault();
var username = _("name").value;
if (username == "")
{
alert("Fill out the form first");
}
else
{
var all = {"username":username};
all = JSON.stringify(all);
var url = "Myservlet";
var ajax = ajaxObj("POST", url);
ajax.onreadystatechange = function()
{
if(ajaxReturn(ajax) == true)
{
// The output text sent from your Java side in response
alert( ajax.responseText );
}
}
//ajax.send("user="+username+");
ajax.send(all);
}
}
Thanks
Change the code in form
onsubmit="submitFormAjax(event)"
Change your JS code
function submitFormAjax(e)
{
e.preventDefault();
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
}
......
................
...............
return false; //at last line
I have to make a chat with JSP, AJAX and Java and I have a problem: when I try to use my variable to store value of a input text, this variable is null.
If I add 'action' property to the form, the variable 'textParam' will have the value of the input text, but, if I do that I have to redirect with action to a page and I don't what that.
I need to process something bigger in the JSP page and then to reload in the HTML page (which is a JSP page) (the reload part is not on actual probem).
How I can make to populate 'textParam' with the input text value when I press the button?
PS: I need to make it with pure javascript, not with some libraries :)
The JSP which have to process is:
String textParam = request.getParameter("chatMessage");
System.out.println("textParam = " + textParam);
My form it look like that:
<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
<input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" />
<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" />
</form>
The .js file it's this:
var request = getXmlHttpRequestObject();
var response = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function sendChatText() {
if(document.getElementById('chatMessage').value == '') {
alert("You have not entered a message");
return;
}
if (request.readyState == 4 || request.readyState == 0) {
request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('chatMessage').value;
param += '&chat=1';
request.send(param);
document.getElementById('chatMessage').value = '';
}
}
function handleSendChat() {
clearInterval(mTimer);
getChatText();
}
function blockSubmit() {
sendChatText();
return false;
}
The problem is here:
String textParam = request.getParameter("chatMessage");
I was trying to get 'chatMessage' parameter, which it was only the name of the input. The solve is to get 'message' param which it was defined and requested in js:
String textParam = request.getParameter("message");
I have the following script, a few lines up from the bottom I have a window.location.href which posts the reults from my form though the address bar. This is very messy and I would like to use POST instead of GET, any ideas anyone ?
<script language="javascript">
function OnChangedUsername()
{
if(document.signup.newuserid.value == "")
{
document.signup.btnCheckAvailability.disabled = true;
}
else
{
document.signup.btnCheckAvailability.disabled = false;
}
}
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq() {
http.open('get', 'password_check.asp?emailaddress=<%Response.Write(emailaddress)%>&check=<%Response.Write(check)%>&password_check='+document.signup.newuserid.value);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
var update = new Array();
if(response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById("username_chk").innerHTML = update[0];
if(document.getElementById("username_chk").innerHTML == "Ok") {
window.location.href='detailsupdate.asp?username=<%Response.Write(sUsername)%>&check=<%Response.Write(check)%>&EmailAddress='+document.signup.EmailAddress.value+'&Address='+document.signup.Address.value+'&Address1='+document.signup.Address1.value+'&Address2='+document.signup.Address2.value+'&City='+document.signup.City.value+'&PostalCode='+document.signup.PostalCode.value+'&Country='+document.signup.Country.value+'&WorkPhone='+document.signup.WorkPhone.value+'&HomePhone='+document.signup.HomePhone.value+'&MobilePhone='+document.signup.MobilePhone.value+'&FaxNumber='+document.signup.FaxNumber.value+'&AlternativePhone='+document.signup.AlternativePhone.value+'&OO='+document.signup.OO.checked+'&Workshop='+document.signup.Workshop.checked+'&Raised='+document.signup.Raised.checked+'&Ground='+document.signup.Ground.checked+'&pd='+document.signup.newuserid.value+'&Tram='+document.signup.Tram.checked;
}
}
}
}
</script>
The only way to make a POST request with the response rendered directly into the browser window is to use a form (which you generate with DOM) and submit it (which you can likewise do through DOM).
The alternative is to use XMLHttpRequest (or some other Ajax technique) and render the response with DOM.
There is no need to pass form data as GET data. You can specify the method as POST.
<form action="script.asp" method="post">
...
<input type="submit" value="submit">
</form>
You also should not be using window.location.href. This is very ugly. When you submit the form (click the submit button) it will POST your form data to script.asp.
Another way to submit your form is to submit it via DOM. document.forms[0].submit();
I'm new to javascript/ajax and a bit stuck right now.
The assignment is to use only javascript/ajax.
I'm supposed to make a login-form, and when typing in the right password it will display a "secret message". Currently this message is an alert-box.
This is in the script for validating the form input:
var riktigPassord = 'password';
var passord = window.document.passordSkjema.passord.value;
if (passord == riktigPassord ) {
alert("Dette er en hemmelig beskjed");
window.document.passordSkjema.passord.focus();
return true;
}
else {
alert("Innlogging mislyktes. Passord er feil!");
window.document.passordSkjema.passord.focus();
return false;
}
}//slutt på funksjonen her
And this is the code for the form:
<form name="passordSkjema" action="#" method="post"
onSubmit="return validerPassord();">
Passord: <input type="text" name="passord"><br>
<input type="submit" name="knapp">
</form>
I'm supposed to get the password from a txt-file. (still using only javascript)
and in my case, the txt-filename is "password.txt".
I've never done this before, but I think I know how to make a XHR-object... xD
// New XMLHttpRequest-object
function newXHRobjekt() {
try {
XHRobjekt = new XMLHttpRequest(); // Firefox, Opera, ...
} catch(err1) {
try {
XHRobjekt = new ActiveXObject("Microsoft.XMLHTTP"); // Noen IE
} catch(err2) {
try {
XHRobjekt = new ActiveXObject("Msxml2.XMLHTTP"); // Noen IE
} catch(err3) {
XHRobjekt = false;
}
}
}
return XHRobjekt;
}
So.. My question is. How do I use a XHR-object to get use the functions above to check the password-input against password.txt. the file only contains the password (for instance only "12345"). and also I would like to know how to get the "secret message" from another txt-file.
I'm aware that this isn't secure at all, but it's a part of understanding javascript/Ajax, in my classes.
Thanks!
add the following code to the onload event of the body.
var passwordLoaded = false;
var password = "";
var secretMessageLoaded = false;
var secretMessage = "";
var xhr = newXHRobjekt();
xhr.open("GET", "password.txt");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
password = xhr.responseText;
passwordLoaded = true;
}
}
xhr.send(null);
xhr = newXHRobjekt();
xhr.open("GET", "secret_message.txt");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
secretMessage = xhr.responseText;
secretMessageLoaded = true;
}
}
xhr.send(null);
If both passwordLoaded and secretMessageLoaded are set to true you can use the variables password and secretMessage.
Like many of the Javascript APIs XHR object too have an async interface. So you will need to define callback functions to handle the responses:
xmlhttp.open("POST", "http://example.com",true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
alert(xmlhttp.responseText)
}
}
xmlhttp.send('my request data');
Search for example on the net. I found a post, a bit old but seem to have good examples.