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
Related
I'm trying to use a form with a single input, that will ask for a 4-letter "secret" code (eg "a123"). The script will check if the corresponding page exists (eg: https://example.com/a123). If it exists, the page opens (in _self). If it does not, an error message is displayed.
The code below does not produce the expected result, it just refreshes the page regardless if my code is a match or not, although the url gets an appended parameter (eg: https://example.com/secret-code/?code=a123).
Functions in head:
function checkUrl(url) {
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", url);
if (request.status == 200) { return true; }
}
return false;
}
function validateCode() {
var x = document.forms["secret"]["code"].value;
if (x == "") {
document.getElementById("alertmsg").innerHTML = "Enter a code.";
}
if (checkUrl("https://www.example.com/" + x))
{
window.open("https://www.example.com/" + x,"_self");
} else {
document.getElementById("alertmsg").innerHTML = "Invalid Code. Try again.";
}
}
Form in body:
<form name="secret" onsubmit="validateCode()">
Code secret : <input type="text" name="code" size="4" maxlength="4" text-transform="uppercase"/>
<div id="alertmsg" style:"color:red;font-weight:bold"></div>
<input type="submit" value="Validate" />
</form>
I'm stumped. Thanks for helping me find the issue...
Adding another answer.
Removed form tag.
Changed the button type to button from submit.
Added onclick event on button to call validateCode() function.
Changed the way to get the secret code value x;
There was another issue with the blank data (empty string), which should be in the else case. Now handled.
function checkUrl(url) {
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", url);
request.send();
if (request.status == 200) {
return true;
}
}
return false;
}
function validateCode() {
var x = document.getElementById('code').value;
if (x == "") {
document.getElementById("alertmsg").innerHTML = "Enter a code.";
} else {
if (checkUrl("https://www.example.com/" + x)) {
window.open("https://www.example.com/" + x, "_self");
} else {
document.getElementById("alertmsg").innerHTML = "Invalid Code. Try again.";
}
}
return false;
}
Code secret : <input id="code" type="text" name="code" size="4" maxlength="4" text-transform="uppercase" />
<div id="alertmsg" style: "color:red;font-weight:bold"></div>
<input type="button" value="Validate" onclick="validateCode()" />
I have made few changes but not tested the code because having cross origin problem.
I hope it works for you.
Added return in <form name="secret" onsubmit="return validateCode()">
Added return false; in validateCode() function. As you were facing the page reload problem due to form submission.
Added request.send();, As you were just setting the to open the link, but not sending the request.
function checkUrl(url) {
var request = false;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest;
} else if (window.ActiveXObject) {
request = new ActiveXObject("Microsoft.XMLHttp");
}
if (request) {
request.open("GET", url);
request.send();
if (request.status == 200) {
return true;
}
}
return false;
}
function validateCode() {
var x = document.forms["secret"]["code"].value;
if (x == "") {
document.getElementById("alertmsg").innerHTML = "Enter a code.";
}
if (checkUrl("https://www.example.com/" + x)) {
window.open("https://www.example.com/" + x, "_self");
} else {
document.getElementById("alertmsg").innerHTML = "Invalid Code. Try again.";
}
return false;
}
<form name="secret" onsubmit="return validateCode()">
Code secret : <input type="text" name="code" size="4" maxlength="4" text-transform="uppercase" />
<div id="alertmsg" style: "color:red;font-weight:bold"></div>
<input type="submit" value="Validate" />
</form>
I am using a JavaScript & Ajax to make a php call to return data from my database. The call returns the data as it should, but when the page fully loads the <div> tags value is cleared.
What do I need to change in my syntax so that the div tag retains the value echo from the php file? I checked the Console and it is only showing page load info and nothing related to this issue (at least not that I saw).
<form id="form1" method="post">
<div id="results"> </div>
<div style="padding-top: 10px;"><input type="submit" value="Submit" onclick="MakeQuery()" /></div>
<script type="text/javascript">
var xhttp;
function MakeQuery()
{
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function(){ if (xhttp.readyState == 4 && xhttp.status==200)
{ document.getElementById("results").innerHTML = xhttp.responseText; } }
xhttp.open("GET", "SQLQuery.php", true);
xhttp.send();
}
</script>
</form>
I think you need to prevent the actual form submit before using AJAX:
var xhttp;
function MakeQuery(event) {
event.preventDefault(); // Cancel form submit, use AJAX
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("results").innerHTML = xhttp.responseText;
}
}
xhttp.open("GET", "SQLQuery.php", true);
xhttp.send();
}
I have an old js code working fine for ajax requests WITHOUT JQuery:
function makeGetRequestTar(key) {
http.open('GET', key, true);
//assign a handler for the response
http.onreadystatechange = processResponseTar;
//actually send the request to the server
http.send(null);
}
function processResponseTar() {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('content').innerHTML = response;
}
}
But now i want to:
Trigger the ajax request when submitting an html form
Pass the 'content' in document.getElementById('content').innerHTML as a variable.
Continue WITHOUT JQuery
So this is my js code now:
function makeGetRequestTar(fileTarget, htmlTarget) {
http.open('GET', fileTarget, true);
//assign a handler for the response
http.onreadystatechange = processResponseTar(htmlTarget);
//actually send the request to the server
http.send(null);
}
function processResponseTar(htmlTarget) {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById(htmlTarget).innerHTML = response;
}
}
And here the html:
<div id="description-form">
<form enctype="multipart/form-data" id="xxx" action="receiver.php" method="post" target="my-iframe">
<textarea class="proposal" name="description" rows="10" cols="60"></textarea>
<br>
<input class="submitbutton" type="submit" onclick="return makeGetRequestTar('doc/description.txt','description-preview')" value=" Save text " />
<br>
<iframe name="my-iframe" style="display:none"></iframe>
</form>
</div>
<div id="description-preview" style="float:left">
<?php include("doc/description.txt")?>
</div>
This code does not throw any error on the console. And the form is posted correctly via php.
But the ajax request is not working, why does it not work if there are no errors showing?
Your old code
http.onreadystatechange = processResponseTar;
assigns the callback function processResponseTar to the onreadystatechange event property.
The new code
http.onreadystatechange = processResponse(htmlTarget);
calls your callback (note the (..)). You can't add custom parameters to that callback. One way to make htmlTarget accessible to your callback is this:
function makeGetRequestTar(fileTarget, htmlTarget) {
http.open('GET', fileTarget, true);
//assign a handler for the response
http.onreadystatechange = function() {
processResponseTar(htmlTarget);
};
//actually send the request to the server
http.send(null);
}
The problem is that you are executing the function processReponse here:
http.onreadystatechange = processResponse(htmlTarget);
and assigning the RESULT of that function (which in this case is undefined) to http.onreadystatechange.
Now, when the readystate changes, XMLHttpRequest attempts to call onreadystatechange which is now undefined, so nothing happens.
Try this:
function processResponseTar(htmlTarget) {
return function () {
if(http.readyState == 4){
var response = http.responseText;
document.getElementById(htmlTarget).innerHTML = response;
}
}
}
Now, you are still assigning the result of the function to http.onreadystatechange, but this time it is a callable function instead of undefined.
First of all your http is undefined, you need to define that. And second, you're calling processResponse function but function name is processResponseTar.
Edited:
<script>
var http;
function makeGetRequestTar(fileTarget, htmlTarget) {
if(window.XMLHttpRequest){
http=new XMLHttpRequest(); // code for IE7+, Firefox, Chrome, Opera, Safari
}else{
http=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
http.open('GET', fileTarget, true);
//assign a handler for the response
http.onreadystatechange = processResponseTar(htmlTarget);
//actually send the request to the server
http.send(null);
}
function processResponseTar(htmlTarget) {
return function () {
if(http.readyState == 4 && http.status==200){
var response = http.responseText;
document.getElementById(htmlTarget).innerHTML = response;
}
}
}
</script>
I need to send a mail with jsp, but the page itself mustn't reload. The whole implementation is working fine when reloading on the POST-event, but adjusting the code to work with ajax breaks it. It seems that the jsp-Code within the index.jsp is not executed, when the ajax event is triggerd.
I am gonna show some snippets:
index.jsp
<%
String result = "=(";
String to = request.getParameter("rec_mail");
if(to != null) {
String from = request.getParameter("sendermail");
String host = "mailserver";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session mailSession = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Feedback");
message.setText(request.getParameter("feedbackinput"));
Transport.send(message);
result = "Sucess!";
}catch (MessagingException e) {
e.printStackTrace();
result = "failed!";
}
}
out.println(request.getParameter("sendermail"));
out.println(result);
%>
<input id="bsend" class="fbutton" type="submit" name="send" value="Send" onclick="loadContent()" style="float:right; width:18%; height:35%;" >
ajax.js
var xmlhttp
function loadContent() {
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support Ajax!");
return;
}
var url="./index.jsp";
xmlhttp.open("post",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=getOutput;
}
function getOutput()
{
if (xmlhttp.readyState==4)
{
alert("Message sent!");
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
(just showing the relevant parts, everywhere)
I get the alert-message, but no mail is sent ... I hope it is clear, what I am trying to do..
Thank you!
Best regards
Don't you also need to set a header for a HTTP Post
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
also, not sure if it will make a difference but I would make "post" to "POST".
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.