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.
Related
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 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'd like to make a popup preview of a textarea, using a PHP function inside the popup.
Let's say you type "Hello world" in the textarea, then you click "preview" and you get your text converted to "Hey you" by a PHP function in a popup (of course the function is not that simple, that's the reason why I can't adapt this in pure javascript).
Is it possible to do so ?
I know it could easily send the form to an intermediate page, but I must keep the form in background... that's why I need a quick preview on fly.
I did the following:
function PreviewMe() {
var newWin = window.open("", "_blank");
newWin.document.write("<html><body>"+document.getElementById('myText').value+"</body></html>");
newWin.document.close();
}
and
<textarea id="myText" ... />
<input type="submit" ... onclick="PreviewMe();">
Obviously it works without reformatting anything, so how to reformat this result in the popup please ?
Would it be possible (and mayber a better option) to use XMLHttpRequest ?
Thx !
Yes , you should use an XHR request to send data to a script which will return you data to be manipulated on the client side.
Thanks, it was by far easier in the end.
In case it might help others, here is what I've done.
Js function became :
function PreviewMe() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("XMLHTTPRequest not supported...");
return;
}
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById('show').innerHTML = xhr.responseText;
}
};
xhr.send("var="+document.getElementById('myText').value+"");
return;
}
Of course page.php includes my PHP function, show is the id of the div where the result is printed.
I want to replicate some functionality from Digg.com whereby when you post a new address it automatically scans the url and finds the page title.
I am programming in classic ASP and VBScript and using javascript. Anyone know a script to make this happen..?
Many thanks in advance..
Paul
This is somewhat of a rudimentary example. You should probably include some data verification.
The ASP page should be called something like getPageTitle.asp
<%
Response.Buffer = True
Dim strURL, objXMLHTTP, objXML, strContents
Dim objRegExp, strHTML, strPattern, colMatches, strTitle
strURL = Request.Form("url")
Set objXMLHTTP = Server.CreateObject ("Microsoft.XMLHTTP")
'Or if this doesn't work then try :
'Set objXMLHTTP = Server.CreateObject("MSXML2.ServerXMLHTTP")
objXMLHTTP.Open "GET", strURL, False
objXMLHTTP.Send
strContents = objXMLHTTP.ResponseText
Set objXMLHTTP = Nothing
Set objRegExp = New RegExp
strPattern = "<title>(.*?)<\/title>"
objRegExp.Pattern = strPattern
objRegExp.IgnoreCase = True
objRegExp.Global = True
Set colMatches = objRegExp.Execute(strContents)
If colMatches.Count > 0 then
strTitle = objMatches(0).Value
Else
strTitle = ""
End If
Set objRegExp = Nothing
Response.write(strTitle)
%>
This is a basic JavaScript POST implementation. You could spruce this up a bit with any JS framework you like.
var script = "http://www.example.com/getPageTitle.asp"
var page2check = "http://www.example.com/somePageToCheck.html"
function getXMLHttpRequestObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = new getXMLHttpRequestObject();
var parameters = "url="+page2check;
http.open("POST", script, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters .length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
alert(http.responseText);
}
}
http.send(parameters);
var pageTitle = http.ResponseText
I hope this helps.
Send url from clientside to serverside using javascript(ajax).
Load html page by it's url using asp on serverside.
Parse html page, extract title.
Send title to clientside.
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