form validation with ajax and jsp doesn't work - java

i am trying to develop a username validation with jsp and ajax but an error apperar like this
POST ://localhost:8080/web_application/deneme.jsp
Show error : 405 (Method Not Allowed)
this is my jsp page what is wrong here
<html>
<body>
<form name="form" id="form">
<input type="text" name="username" id="username">
<br>
<input
type="submit" name="register" value="Sign up">
</form>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script
src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#form").validate({
rules : {
username : {
required:true,
remote : {
url : "deneme.jsp",
async : false,
type : "post",
data : {
username : function() {
return $("#username").val()
}
}
}
}
},
messages : {
username : {
required:"Require Field" ,remote:"already exist"
}
}
});
});
</script>
</body>
</html>

Instead of:
<script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>
http is missing in your javascript file link location.
use the following:
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.13.0/jquery.validate.min.js"></script>

Related

eventpreventDefault() not working I need to show the results on same page

I have added the java script file in the html for a form and it is connected to the java file I want to show data on same page after submit i.e index.html but after the submission it takes me to the register page.
html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="submit" />
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#register").bind('submit',(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, { name: $('#name').val(), email: $('#email').val(),pass: $('#pass').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</form>
</body>
</html>
The forms needs an id in order to be called with the query selector #register.
<form method="post" action="register" id="register">

how to pass radiobutton value using ajax from one jsp to another jsp

(document).ready(function() {
$("input[type='radio']").click(function() {
var radioVal = $("input[name='price']:checked").val();
});
}
I need to pass radioVal value to another jsp
Please Take the help of Following Example.
page1.jsp
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () {
var radioVal;
$("input[type='radio']").click(function() {
radioVal = $("[name=radio]:checked").val();
alert(radioVal);
$.post("page2.jsp", {"processId": radioVal })
});
});
</script>
<input type="radio" name="radio" value="first"/> 1 <br/>
<input type="radio" name="radio" value="second"/> 2 <br/>
page2.jsp
<%
System.out.println(request.getParameter("processId"));
%>

Building Restful Web Service using Spark Java for Library Management System

I am new with Spark Java. I have made a Library Management System with get and post methods written in Java. I have made an HTML form that takes information of user and creates users which gets stored in a ArrayList of objects in Java. When I call get method to return the list of user objects created via ajax, nothing gets returned. Success nor error gives any output.
But when I simply put the url : http://localhost:4567/users
I get the following output:
[{"id":1,"firstName":"Bhavya","lastName":"Chauhan","age":"22","gender":"F","phone":"1234567890"},
{"id":2,"firstName":"Rashi","lastName":"Chauhan","age":"20","gender":"F","phone":"1233455677"}]
I have attached my html and Spark java code. Thanks in advance!
<!DOCTYPE html>
<html>
<head>
<title>Text Input Control</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<meta charset="utf-8"/>
</head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script type="text/javascript"></script>
<script>
$(function () {
$("#userGet").click(function(){
alert("Here");
$.ajax({
type: 'GET',
url: 'http://localhost:4567/users',
crossDomain: true,
data: '',
dataType: 'jsonp',
async:false,
success: function(responseData) {
//$("#divid").html(+responseData);
alert("hi");
},
error: function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});
});
});
</script>
<body>
<h2>Library Management System </h2>
<button>Get Stuff</button>
<form>
<h3>Manage Users </h3>
<input type=button onClick="location='CreateUser.html'" value='Create User'>
<br><br>
<input type=submit id="userGet" value='Get All Users'>
<br><br>
<input type=button onClick="location='UpdateUser.html'" value='Update User'>
<br><br>
</form>
<form action="http://localhost:4567/books" method="GET">
<h3>Manage Books </h3>
<input type=submit value='Get All Books'>
<br><br>
<input type=button onClick="location='FindBookByName.html'" value='Find Book By Name'>
<br><br>
<input type=button onClick="location='AddBook.html'" value='Add Book'>
<br><br>
<input type=button onClick="location='CheckOutBook.html'" value='Check Out Book'>
<br><br>
</form>
<div id="divid"></div>
</body>
</html>
Here is the Java:
import static spark.Spark.*;
public class UserController extends JsonUtil
{
public UserController(final UserService userService)
{
System.out.println("in user controller");
get("/users", (req, res) -> userService.getAllUsers(), json());
get("/books", (req, res) -> userService.getAllBooks(), json());
post("/users", (req, res) -> userService.createUser(req.body()), json());
post("/users/:id", (req, res) -> userService.updateUser(req.body()),json());
post("/books", (req, res) -> userService.addBook(req.body()), json());
post("/books/:name", (req, res) -> userService.findBookByName(req.body()),json());
post("/checkedOut", (req, res) -> userService.checkOutBook(req.body()), json());
}
}

post comments using jsp, servlet and ajax

I am trying to create a comment section using jsp, servlet and ajax. The problem I am facing is that each comment replaces it's previous one instead of showing next to it.
Highly appreciate any kind of help.
<script type="text/javascript" src="js/jquery-1.11.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#submitBtn').click(function() {
var cmt = $('#cmt').val();
$.ajax({
type : 'POST',
data : {
cmt : cmt,
action : 'EnterMsg'
},
url : 'SubmitComment',
success : function(result) {
$('#view2').text(result);
}
});
});
});
</script>
</head>
<body>
<fieldset>
<legend>Enter Message</legend>
<form>
Ques.<input type="text" id="cmt"> <input type="button"
value="Send" id="submitBtn"><br> <span id="post1"></span>
</form>
</fieldset>
<fieldset>
<legend>View Message</legend>
<form>
<div id='view2'></div>
<br>
</form>
</fieldset>
Try
var html='';
$.ajax({
dataType: "json",
url: "SubmitComment",
error: function () {
alert('error occured');
},
success: function (result) {
for(var key in result) {
var value = result[key];
html+='<div>'+key+':'+value+'</div>'
}
$("#view2").append(html);
}
});
Instead of
success : function(result) {
$('#view2').text(result);
}
Because of you get multiple comments from the ajax respose and you have to iterate each one of them and append to your div tag

The request was rejected because no multipart boundary was found

I am using a Form in a LightBox which contains some input element.
<form name="imageUploadForm" action="uploadImage.do" method="post" enctype="multipart/form-data">
<input type="text" id="id" name="id" style="display: none;" value="">
<div id="fileUploaderDiv">
<input type='file' name="file0" id ="file0" />
</div>
<input type="submit" value="Submit">
</form>
when i am submitting the form than the form redirect to it's action location. I just want to submit form without redirecting user, so user stay on lightbox without loosing his data.
I have tried jquery ajax call for this
var data = new FormData();
var $inputs = $('#imageUploadForm :input');
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
data.append(this.name, $(this).val());
});
$.ajax({
url: 'uploadImage.do',
data: data,
cache: false,
contentType: 'multipart/form-data',
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
But getting error at server side in my FileUploader servlet.
The request was rejected because no multipart boundary was found
can anybody tell me what am i missing in this ?
You need to prevent the default action of submitting the form:
$('form[name="imageUploadForm"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'uploadImage.do',
data: data,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
});
I believe you should set the contentType option to false when using the FormData class, forcing jQuery not to add a Content-Type header, otherwise the boundary string will be missing, and that's probably the reason for your server error.
You must also leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
Here is the simplest form of a form submit using jquery Ajax. I have not tested this but it should work :-)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test form</title>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#sbmt').click(function(){
var text1 = $('#text1').val();
var text2 = $('#text2').val();
/// validation of inputs
///then
$.ajax(
{
url :'submit.php',
type : 'post',
data : {'text1' : text1, 'text2' : text2 },
success: function(data){
alert("form submitted . response is :"+ data);
}
}
).fail(function(){alert("Failed!!");});
});
});
</script>
</head>
<body>
<form id="myform">
<input type="text" id="text1" />
<input type="text" id="text2" />
<input type="button" id="sbmt" value="submit"/>
</form>
</body>
</html>

Categories

Resources