Please bear with me as I am new to jQuery, and JEE and am not a programmer :-)
I have followed a number of tutorials on how to dynamically populate a dropdown box; however I can not get it to work.
I want to select a State and populate the Region drop down based on that selection (each State is made up of Regions).
My issue is with the call to the java and return of values.
So far I have (mashed up from a number of tutorials) the following:
HTML
<div class="row">
<div class="col-md-6">
<div class="form-select-group">
<label for="selectState">Select State:</label>
<select class="form-control" id="selectState">
<option value="" disabled selected>Select your State</option>
<option>ACT</option>
<option>NSW</option>
<option>NT</option>
<option>QLD</option>
<option>SA</option>
<option>TAS</option>
<option>VIC</option>
<option>WA</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-select-group">
<label for="selectRegion">Select Region:</label>
<select class="form-control" id="selectRegion">
<option>Please select your State first</option>
</select>
</div>
</div>
</div>
jQUERY
$(document).ready(function(){
$('#selectState').on('change', function() {
//do something here
//alert($("#accountName").val());
$.ajax({
type: "POST",
url: "RegionView",
cache: false,
data: $(selectState).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(response) {
// Clear options
$("#selectRegion").find("option").remove();
// Loop through JSON response
$.each(response, function (index, value) {
$('#selectRegion').append($('<option>', { value: value.name }, '</option>'));
})
});
});
});
JAVA
package client;
import java.io.IOException;
/**
* The purpose of this View is to return a list of Regions associated with a selected State.
*/
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import server.MySQLConnection;
#WebServlet("/RegionView")
public class RegionView extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String state = request.getParameter("selectState"); // From bootstrap
response.getWriter().write("Here " + state);
MySQLConnection.getConnection();
List<String> listRegions = MySQLConnection.listGroupRegions(state);
if (listRegions == null || listRegions.isEmpty()) {
response.getWriter().write("Please select a State");
}else{
response.getWriter().write("State found");
request.setAttribute("selectRegion", listRegions);
}
}
}
This code answers my question as it allows me to dynamically populate a dropdown box with Jquery and Java:
Java:
#WebServlet("/RegionView")
public class RegionView extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String state = request.getParameter("selectState"); // From bootstrap
MySQLConnection.getConnection();
List<String> listRegions = MySQLConnection.listGroupRegions(state);
if (listRegions == null || listRegions.isEmpty()) {
response.getWriter().write("Please select a State");
}else{
String json = new Gson().toJson(listRegions);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
}
JSON:
$(document).ready(function(){
$('#selectState').on('change', function() {
//do something here
//alert($("#accountName").val());
$.ajax({
type: "POST",
url: "RegionView",
cache: false,
data: $(selectState).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(responseJson) {
dataType: "json",
// Clear options
$("#selectRegion").find("option").remove();
// Loop through JSON response
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($("#selectRegion"));
});
});
});
});
Related
I have Form in JSP which have two input boxes along with submit and clear button like this
<form name="loginForm" method="GET" action="Ajaxexample" id="loginForm">
<table>
<tr>
<td>From Date</td><td><input type="text" name="n1" value=""/></td>
</tr>
<tr>
<td>End Date</td><td><input type="text" name="n2" value=""/></td>
</tr>
<tr></tr>
<tr>
<td><input type="submit" name="validpro_insert" value="Insert"></td>
<td><input type="reset" name="validpro_clear" value="Clear"></td>
</tr>
</table>
</form>
As I have called the servlet using get method in form tag which is used to get data from database via JDBC API and to handle the response I have use ajax like this
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
processRequest(request, response);
System.out.println("In get");
PrintWriter out = response.getWriter();
String responseStr = "";
responseStr = addUser(request); // Return either error/success
System.out.println("Reponse:" + responseStr);
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
response.getWriter().write(responseStr);
out.print(responseStr);
As I have to write some code to get data from DB in servlet and return that response to ajax which handle success and error on the same jsp like this
<script type="text/javascript" src="js/jq.js"></script>
<script type="text/javascript">
var form = $('#loginForm');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
error: function (theRequest,textStatus, errorThrown) {
// Success = false;
alert (theRequest.responseText);
alert(errorThrown);
alert('No graph found');//doesnt goes here
},
success: function (data) {
var result=data;
alert(result);
}
});
return false;
});
</script>
But the problem is that I am not getting any value from servlet in ajax to handle success or error
I think I am facing this problem due to servlet doget() method code.. if there is any other problem plz let me know. Any help should be appreciated
with these changes in my code, it runs successfully
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter())
String responseSend = "";
String from = request.getParameter("n1");
String to = request.getParameter("n2");
if ((from == null) || (from.equals(""))) {
System.out.println("From null");
responseSend = "error";
}
else if ((to == null) || (to.equals(""))) {
System.out.println("End null");
responseSend = "error";
}
else{
//jdbc code
System.out.println("got it");
int n1 = Integer.parseInt(request.getParameter("n1"));
int n2 = Integer.parseInt(request.getParameter("n2"));
responseSend = "code";
}
out.print(responseSend);
}
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("In get");
processRequest(request, response);
}
As I have added a new method processrequest() with request and response parameters which will return the text/HTML to our Ajax code on the same jsp.Firstly I am confused with success/error in ajax code but now I have found that
error: function (theRequest,textStatus, errorThrown) {
alert (theRequest.responseText);
alert(errorThrown);
},
success: function (data) {
var result=data;
alert(result);
}
The error will be called when it doesn't found servlet at given URL and success will be called when it successfully call the servlet with given type and servlet URL.
I have pasted my code here that work well
Try changing your parameter
Your JSP Page
<script src="http://code.jquery.com/jquery-1.10.2.js"
type="text/javascript"></script>
<form id="form">
Enter Your Name: <input type="text" id="userName" />
</form>
<br>
<br>
<strong>Ajax Response</strong>:
<div id="ajaxGetUserServletResponse"></div>
here is your ajax
$(document).ready(function() {
$('#form').submit(function() {
$.ajax({
url : 'GetUserServlet',
data : {
userName : $('#userName').val()
},
success : function(responseText) {
$('#ajaxGetUserServletResponse').text(responseText);
}
});
});
});
your servlet file
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName").trim();
if(userName == null || "".equals(userName)){
userName = "Guest";
}
String greetings = "Hello " + userName;
response.setContentType("text/plain");
response.getWriter().write(greetings);
}
}
This post is related to Dynamically populate a dropdown box with Jquery and Java
Which I have solved and posted the answer to. I now have another issue. This is my first project using json, java and html so a bit of a learning curve.
I use the same code to extract some lists (a list of Regions, a list of Districts); however, a different result/format is returned for the District list. The Region list is correct and returns:
Which I now successfully use to populate a drop down list. I then select one of the values and use very similar code to retune a list of Districts within the Region selected. This returns:
Note the square brackets and quotes.
The code I use is:
HTML:
<div class="col-md-2">
<div class="form-select-group">
<label for="selectRegion">Select Region:</label>
<select class="form-control" id="selectRegion" name="selectRegion">
<option value="" disabled selected>Select your State first</option>
</select>
</div>
</div>
<div class="col-md-2">
<div class="form-select-group">
<label for="selectDistrict">Select District:</label>
<select class="form-control" id="selectDistrict" name="selectDistrict">
<option value="" disabled selected>Select your State first</option>
</select>
</div>
</div>
JSON:
$(document).ready(function(){
$('#selectState').on('change', function() {
$.ajax({
type: "POST",
url: "RegionView",
cache: false,
data: $(selectState).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(responseJson) {
dataType: "json",
// Clear options
$("#selectRegion").find("option").remove();
$('#selectRegion').append($('<option value="" disabled selected>Select your Region</option>'));
$("#selectDistrict").find("option").remove();
$('#selectDistrict').append($('<option value="" disabled selected>Select your Region first</option>'));
$("#selectGroup").find("option").remove();
$("#selectSection").find("option").remove();
$("#selectSubSection").find("option").remove();
// Loop through JSON response to populate the Region drop down
$.each(responseJson, function(key, value) {
$('<option>').text(value).appendTo($("#selectRegion"));
});
});
});
$('#selectRegion').on('change', function() {
$.ajax({
type: "POST",
url: "DistrictView",
cache: false,
data: $(selectRegion).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(responseJson2) {
dataType: "json",
// Clear options
$("#selectDistrict").find("option").remove();
$('#selectDistrict').append($('<option value="" disabled selected>Select your District</option>'));
$("#selectGroup").find("option").remove();
$('#selectGroup').append($('<option value="" disabled selected>Select your District first</option>'));
$("#selectSection").find("option").remove();
$("#selectSubSection").find("option").remove();
// Loop through JSON response to populate the District drop down
alert("Here1");
$.each(responseJson2, function(key, value) {
alert("Here2");
$('<option>').text(value).appendTo($("#selectDistrict"));
});
});
});
$('#selectDistrict').on('change', function() {
$.ajax({
type: "POST",
url: "GroupView",
cache: false,
data: $(selectDistrict).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(responseJson) {
dataType: "json",
// Clear options
$("#selectGroup").find("option").remove();
$('#selectGroup').append($('<option value="" disabled selected>Select your Group</option>'));
$("#selectSection").find("option").remove();
$('#selectSection').append($('<option value="" disabled selected>Select your Group first</option>'));
$("#selectSubSection").find("option").remove();
// Loop through JSON response to populate the Group drop down
$.each(responseJson, function(key, value) {
$('<option>').text(value).appendTo($("#selectGroup"));
});
});
});
});
Java for Region (reads a selected State and returns a list of Regions which are populated into the drop down list):
#WebServlet("/RegionView")
public class RegionView extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String state = request.getParameter("selectState"); // From bootstrap
MySQLConnection.getConnection();
List<String> listRegions = MySQLConnection.listGroupRegions(state);
if (listRegions == null || listRegions.isEmpty()) {
response.getWriter().write("No Regions in this State.");
}else{
String json = new Gson().toJson(listRegions);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
}
I then select a Region and pass it to this java which returns a list of Districts. The Districts are found however the format returned is not correct and so the next drop down is not populated with this list:
#WebServlet("/DistrictView")
public class DistrictView extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String[] region = request.getParameterValues("selectRegion"); // From bootstrap
String region0 = region[0];
MySQLConnection.getConnection();
List<String> listDistricts = MySQLConnection.listGroupDistricts(region0);
if (listDistricts == null || listDistricts.isEmpty()) {
response.getWriter().write("No Districts in this Region.");
}else{
String json = new Gson().toJson(listDistricts);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
}
I want to return this list to the json and populate the drop down list so I can select a District and return a list of Groups in that District. However; even though I am converting to json it returns the value in square brackets and quotes.
This line is missing from your districts code response.setContentType("application/json");
I'm very new to FullCalendar and I seriously don't know how to adapt it according to my project requirements. Chose it because my Lecturer wants me to. I am aware that fullcalendar is drag and drop function. What i'm trying to do is have an add button for each cell in my fullcalendar page then when I click add it will go to another jsp page (Add Events). Then I have date inputs (java.sql.Date) so this dates must match to full calendar date.I'm So sure that it's some logic here in index.jsp that needs to be done like if and else statement. If mysql date match to fullcalendar date,you display in that cell. Now what it's doing is print out date in every cell from database.And I just need to display the Title. Refer to the pictures attached :)
RetrieveServlet: Retrieve from AddEventsServlet (for adding events)
ackage servlet;
import java.io.IOException;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import database.DBAO;
import model.AddEvents;
/**
* Servlet implementation class RetrieveServlet
*/
#WebServlet("/RetrieveServlet")
public class RetrieveServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RetrieveServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
doPost(request,response); //dispatcher sents deget request, since ur code is in dopost, u will need to all it.
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try
{
DBAO myDatabase = new DBAO();
ArrayList <AddEvents> myEventList = myDatabase.getAddEvents();
System.out.println(myEventList.size());
request.setAttribute("EventList",myEventList);
request.getRequestDispatcher("index.jsp").forward(request, response);
}catch(Exception ex)
{
System.out.println("Error Accessing Database:" +ex.getMessage());
}
}
}
AddEventsServlet:
package servlet;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.ListIterator;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import database.DBAO;
import model.AddEvents;
/**
* Servlet implementation class AddEventsServlet
*/
#WebServlet("/AddEventsServlet")
public class AddEventsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public AddEventsServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
AddEvents myEvent = new AddEvents();
//create an object based on the Java class customers
//DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
//Assignment of data
myEvent.setTitle(request.getParameter("Title"));
myEvent.setEventDesc(request.getParameter("EventDesc"));
myEvent.setStartTime(request.getParameter("StartTime"));
myEvent.setEndTime(request.getParameter("EndTime"));
myEvent.setBudget(Double.valueOf(request.getParameter("Budget")));
myEvent.setStartDate(java.sql.Date.valueOf(request.getParameter("StartDate")));
myEvent.setEndDate(java.sql.Date.valueOf(request.getParameter("EndDate")));
myEvent.setEnvironment(request.getParameter("Environment"));
System.out.println(request.getParameter("Title"));
System.out.println(request.getParameter("EventDesc"));
System.out.println(request.getParameter("StartTime"));
System.out.println(request.getParameter("EndTime"));
System.out.println(request.getParameter("Budget"));
System.out.println(request.getParameter("StartDate"));
System.out.println(request.getParameter("EndDate"));
System.out.println(request.getParameter("Environment"));
System.out.println("Title="+myEvent.getTitle());
System.out.println("EventDesc="+myEvent.getEventDesc());
System.out.println("StartTime="+myEvent.getStartTime());
System.out.println("EndTime="+myEvent.getEndTime());
System.out.println("Budget="+myEvent.getBudget());
System.out.println("StartDate="+myEvent.getStartDate());
System.out.println("EndDate="+myEvent.getEndDate());
System.out.println("Environment="+myEvent.getEnvironment());
try
{
DBAO myDatabase = new DBAO();
ArrayList <AddEvents> myEventList = myDatabase.getAddEvents(); //not needed
//AddEvents myEventDetails =myDatabase.isEvent(myEvent,title, eventDesc, StartTime, EndTime, Budget); //not needed
HttpSession myRequest = request.getSession(true); //not needed
request.setAttribute("EventList",myEventList); //not needed
System.out.println(myEventList.size()); //not needed
// you comment out the method that insert data to database
myDatabase.AddEvents(myEvent);
// the dispatcher can go to RetrieveServlet and let it handle the retrieve
//myDatabase.delete(myEvent,title,eventDesc,StartTime,EndTime,Budget,StartDate,EndDate);
//name of delete database
request.getRequestDispatcher("index.jsp").forward(request, response);
}catch(Exception ex)
{
System.out.println("Error Accessing Database:" +ex);
}
}
}
index.jsp: Displaying the full calendar
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<%#page import="model.AddEvents,java.util.ArrayList,java.util.ListIterator" %>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src= "https://code.jquery.com/jquery-3.2.1.min.js">
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var events_array = [
{
title: 'Test1',
start: new Date(2012, 8, 20),
tip: 'Personal tip 1'},
{
title: 'Test2',
start: new Date(2012, 8, 21),
tip: 'Personal tip 2'}
];
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
dayClick: function(date, jsEvent, view) {
alert('Clicked on: ' + date.format());
alert('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
alert('Current view: ' + view.name);
// change the day's background color just for fun
$(this).css('background-color', 'red');
},
selectable: true,
events: events_array,
eventRender: function(event, element) {
element.attr('title', event.tip);
}},
$('#datepicker').datepicker({
inline: true,
onSelect: function(dateText, inst) {
var d = new Date(dateText);
$('#fullcalendar').fullCalendar('gotoDate', d);
}
}));
function changeDate() {
var StartDate = $('#datepicker').val();
$('#calendar').fullCalendar('gotoDate', startDate);
}
});
</script>
<title>Calendar</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" type="text/css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.css" type="text/css" rel="stylesheet" />
</head>
<body>
<a class= "add_event_label" href="https://www.w3schools.com/tags/tryit.asp?filename=tryhtml_textarea"></a>
<div class="container">
<div class="row">
<div class="col-xs-12">
<h1>Calendar</h1>
<div id="bootstrapModalFullCalendar"></div>
</div>
</div>
</div>
<!-- this is the pop up window when you press the button -->
<div id="fullCalModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span> <span class="sr-only">close</span></button>
<h4 id="modalTitle" class="modal-title"></h4>
</div>
<div id="modalBody" class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<a class="btn btn-primary" id="eventUrl" target="_blank">Event Page</a>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/fullcalendar/2.6.1/fullcalendar.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script>
$(document).ready(function() {
$('#bootstrapModalFullCalendar').fullCalendar({
header: {
left: '',
center: 'prev title next',
right: ''
},
//action after calendar loaded
eventAfterAllRender: function(view){
if(view.name == 'month')
{
//loop all .fc-day elements
$('.fc-day').each(function(){
//jQuery styling
$(this).css({ 'font-weight': 'bold', 'font-size': '100%'});
$(this).css('position','relative');
//add elements to each .fc-day, you can modify the content in append() with your own html button code
$(this).append('<a class="add_event_label" onclick="changeDate()" href ="AddEvent.jsp" style="position:absolute;bottom:0;left:0;right:0;display:block;font-size:12px;color:blue;cursor:pointer;">(+)</a>' );
<%!ArrayList<AddEvents> myEventList; //have to declear in a declaration tag for access in the page %>
<% myEventList = (ArrayList<AddEvents>) request.getAttribute("EventList");
if(myEventList.size() == 0)
{
%>
<h2>No events</h2>
<%
}
else
{
%>
<%
ListIterator<AddEvents> li = myEventList.listIterator();
while(li.hasNext())
{
AddEvents myEvent = new AddEvents();
myEvent= (AddEvents)li.next();
%>
//This part it should add data according to date, now it's just adding all the data of title.
$(this).append('<p><font size="1">Title:</font></p><p><font size="1"><%= myEvent.getTitle() %></font></p></p>');
<%}
%>
<%
}
%>
});
}
},
eventClick: function(event, jsEvent, view) {
//$(".fc-day-number").prepend("(+) ");
$('#modalTitle').html(event.title);
$('#modalBody').html(event.description);
$('#eventUrl').attr('href',event.url);
$('#fullCalModal').modal();
return false;
}
})
})
</script>
</body>
</html>
I've been trying for a day to know how to solve this, I really tried to search an answer but i guess i couldn't or i didn't understand.
Here are the steps from my problem:
1.- I will do a for , so i have to process each record one by one using ajax (i saw that using async :false will let me process one by one and not all at the same time, i mean it is like a fifo, am i right? cause i need that,because i'm using httpsession some vars need to be changed one by one, thats why i'm trying to process each record one by one, although in my example i don't show this)
2.- if my validation is 1 i will call next ajax but if it is number 2 i have to ask the user to put somethig and then continue with another ajax and then this ajax will call the other ajax as number 1 (here is one of my problem because when i show the modal, the modal is displayed but it continues in the loop so i need to stop my ajax untill the user put something and when he clicks "Save changes" it must continue with the loop, although as i said this is not happening (i tried to use a while(true) but i didn't had a chance my browser stops the script), my program shows the modal and continue looping no matter what)
3.-If user see the modal and click close, well i won't continue with my ajax but i will continue with my loop or my for, because i need to process all things.
This is an example of the modal:
And now, as you can see, yeah my modal showed up but my loop continue no matter what :(
So as i said i need this:
1.- i'm doing a for in order to process all my stuff, but depending of the answer sometimes i have to show the modal, so when user click in savechanges it will call another ajax and then another ajax and continue the loop, but if user click in close well i have to stop the next ajax calls and continue with my for in the next position and do it again again and again untill my for stops.
2.-in other words i have to call my ajax number 1,2,4 if my result is 1 in ajax number 2, but if my result in ajax number 2 is == 2 then i have to show modal and stop the for because it continues looping, and depending of the answe if it is save changes then i have to call ajax3 and this will call ajax4 but if it is close then i have to continue in the next loop, and again, this could happen depending of the answer.
Here are my examples code:
JSP:
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(document).ready(function(){
var positionNumber = 1;
$(".clickme").click(function(){
for(var i=0; i < 10; i++){
ajaxOne();
}
$("body").on('click', '.btn-default', function(e) {
console.log('ok we finish no more calls to servlets');
$('#myModal').modal('hide') ;
console.log('BUT LETS CONTINUE WITH THE FOR.... WE HAVE TO CHECK ALL THE ITEMS')
});
$("body").on('click', '.btn-primary', function(e) {
console.log('ok lets call now ajax three');
ajaxThree();
});
});
function ajaxOne(){
$.ajax({
type: "POST",
url: "/Test/one",
//contentType : "text/xml",
async :false ,
beforeSend: function () {
console.log('CALLING POSITION: '+positionNumber);
console.log('Call Servlet one')
},
success: function(data,status,xhr){
console.log(data)
},
error: function(xhr, status, error){
alert("Error!" + xhr.status);
},
complete: function(){
positionNumber++;
console.log('finish Call Servlet one')
ajaxTwo();
}
});
}
function ajaxTwo(){
var text;
$.ajax({
type: "POST",
url: "/Test/two",
//contentType : "text/xml",
async :false ,
beforeSend: function () {
console.log('Call Servlet two')
},
success: function(data,status,xhr){
console.log(data);
text = data;
},
error: function(xhr, status, error){
alert("Error!" + xhr.status);
},
complete: function(){
console.log('finish Call Servlet two')
if(parseInt(text)==2){
$('#myModal').modal('show') ; // I have to show the modal, and stop all processing,
// if he select save changes I will call ajax 3 and then four, if he select cancel then
// I have to continue with my loop again...
// Here I need a little help :'( thank you so much
}else{
ajaxFour();
}
}
});
}
function ajaxThree(){
$.ajax({
type: "POST",
url: "/Test/three",
//contentType : "text/xml",
async :false ,
beforeSend: function () {
console.log('Call Servlet three')
},
success: function(data,status,xhr){
console.log(data);
},
error: function(xhr, status, error){
alert("Error!" + xhr.status);
},
complete: function(){
console.log('finish Call Servlet three')
ajaxFour();
}
});
}
function ajaxFour(){
$.ajax({
type: "POST",
url: "/Test/four",
//contentType : "text/xml",
async :false ,
beforeSend: function () {
console.log('Call Servlet four')
},
success: function(data,status,xhr){
console.log(data);
},
error: function(xhr, status, error){
alert("Error!" + xhr.status);
},
complete: function(){
console.log('finish Call Servlet four')
}
});
}
});
</script>
</head>
<body>
<div class="clickme">click me </div>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" >Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</body>
</html>
Servlet one
package com.dot.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServeletOne
*/
#WebServlet(name = "one", urlPatterns = { "/one" })
public class ServeletOne extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ServeletOne() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Yep i did a post");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("one");
}
}
Servlet two
package com.dot.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServeletOne
*/
#WebServlet(name = "two", urlPatterns = { "/two" })
public class ServeletOne2 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ServeletOne2() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Yep i did a post");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int tmp = (int) ( Math.random() * 2 + 1);
System.out.println(tmp);
out.println(tmp);
}
}
Servlet three
package com.dot.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServeletOne
*/
#WebServlet(name = "three", urlPatterns = { "/three" })
public class ServeletOne3 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ServeletOne3() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Yep i did a post");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("three");
}
}
servlet four
package com.dot.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ServeletOne
*/
#WebServlet(name = "four", urlPatterns = { "/four" })
public class ServeletOne4 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ServeletOne4() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Yep i did a post");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("four");
}
}
In order to solve my error I used some flags
var positionNumber = 0;
var flagPressedButton = false;
and in my for i used other way
for(i; i < 10;){
ajaxOne();
i++;
if(continuar == false) break;
and when my modal shows up if everything is ok i simulate a click again
$(".clickme").click();
Here is all my js code
<script>
$(document).ready(function(){
var continuar = true;
var positionNumber = 0;
var flagPressedButton = false;
var i=0;
$(".clickme").click(function(event){
for(i; i < 10;){
ajaxOne();
i++;
if(continuar == false) break;
}
$("body").on('click', '.btn-default', function(e) {
console.log('ok we finish no more calls to servlets');
$('#myModal').modal('hide') ;
console.log('BUT LETS CONTINUE WITH THE FOR.... WE HAVE TO CHECK ALL THE ITEMS')
$(".clickme").click();
});
$("body").on('click', '.btn-primary', function(e) {
console.log('ok lets call now ajax three');
ajaxThree();
$(".clickme").click();
});
});
function ajaxOne(){
$.ajax({
type: "POST",
url: "/Test/one",
//contentType : "text/xml",
async :false ,
beforeSend: function () {
continuar =true;
positionNumber++;
console.log('CALLING POSITION: '+positionNumber);
console.log('Call Servlet one')
},
success: function(data,status,xhr){
console.log('complete: ', JSON.parse(data));
var statusCode = JSON.parse(data).responseCode;
console.log('satusCode: ', statusCode);
if (statusCode) {
ajaxTwo(statusCode);
}
},
error: function(xhr, status, error){
alert("Error!" + xhr.status);
}
});
}
function ajaxTwo(){
var text;
$.ajax({
type: "POST",
url: "/Test/two",
//contentType : "text/xml",
async :false ,
beforeSend: function () {
console.log('Call Servlet two')
},
success: function(data,status,xhr){
console.log(data);
text = data;
},
error: function(xhr, status, error){
alert("Error!" + xhr.status);
},
complete: function(){
console.log('finish Call Servlet two')
if(parseInt(text)==2){
console.error('LLAMARE A LA MODAL');
$('#myModal').modal('show') ;
continuar = false;
}else{
ajaxFour();
}
}
});
}
function ajaxThree(){
$.ajax({
type: "POST",
url: "/Test/three",
//contentType : "text/xml",
async :false ,
beforeSend: function () {
console.log('Call Servlet three')
},
success: function(data,status,xhr){
console.log(data);
},
error: function(xhr, status, error){
alert("Error!" + xhr.status);
},
complete: function(){
console.log('finish Call Servlet three')
console.error('CERRARE A LA MODALA Y CONTINUARE');
$('#myModal').modal('hide') ;
ajaxFour();
continuar = true;
}
});
}
function ajaxFour(){
$.ajax({
type: "POST",
url: "/Test/four",
//contentType : "text/xml",
async :false ,
beforeSend: function () {
console.log('Call Servlet four')
},
success: function(data,status,xhr){
console.log(data);
},
error: function(xhr, status, error){
alert("Error!" + xhr.status);
},
complete: function(){
console.log('finish Call Servlet four')
}
});
}
});
</script>
As i Said, i neded to show a modal and then continue, well i solve it in this way and now it's working fine for me =) and do not forget use async :false , in order to make a petition by petition
I am able to get the form data using the buffer handler, but it is a void function and I cannot return the form data values. Have about 4-7 forms total, I don't want to end up writing the same handler over and over because the default function is void.
html:
<!DOCTYPE html>
<html>
<head><title>Login Page</title></head>
<body>
activate user
<br/>
log in
<br/>
<form id='login' action='/login' method='post'>
<fieldset >
<legend>Login</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='username' >UserName: </label>
<input type='text' name='username' id='username' maxlength="50"/>
<label for='password' >Password: </label>
<input type='password' name='password' id='password' maxlength="50"/>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>
</body>
</html>
java:
import org.jboss.netty.handler.codec.http.QueryStringDecoder;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.deploy.Verticle;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
* User: yao
* Date: 1/17/13
* Time: 2:22 PM
*/
public class Main extends Verticle
{
#Override
public void start() throws Exception
{
System.out.println("starting the vertx stuff");
final String host = "localhost";
final String port = "8181";
Vertx vertx = Vertx.newVertx();
HttpServer httpServer = vertx.createHttpServer();
...
httpServer.requestHandler(new Handler<HttpServerRequest>()
{
public void handle(HttpServerRequest req)
{
String path = req.path;
/* start mapping of page urls*/
// redirect user to the login page
if (path.equals("/"))
{
req.response.sendFile(dir + "html/loginPage.html");
}
...
/* end mapping of page urls*/
/* start mapping of form urls */
// login
else if (path.equals(login))
{
mainLogin();
getFormData(req);
}
...
/* end mapping of form urls */
/* all other pages */
else
{
req.response.end("404 - page no exist");
}
}
});
System.out.println("vertx listening to: " + host + " " + port);
httpServer.listen(Integer.valueOf(port), host);
}
...
private void getFormData(final HttpServerRequest req)
{
req.bodyHandler(new Handler<Buffer>()
{
#Override
public void handle(Buffer buff)
{
String contentType = req.headers().get("Content-Type");
if ("application/x-www-form-urlencoded".equals(contentType))
{
QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
Map<String, List<String>> params = qsd.getParameters();
System.out.println(params);
}
}
});
}
}
Nowadays BodyHandler is provided by vertx, using it isExpectMultipart will be set to true and you will be able to read form attributes as
request.getFormAttribute("username");//to read input named username.
just add this line before your actual handler:
router.route().handler(BodyHandler.create());
For java this worked perfectly:
request.expectMultiPart(true);
request.endHandler(req->{
String text = request.formAttributes().get("bigtext");
//got it here
//do something ...
});
what i did in the end is basically this:
do the ajax call using post, the data from the form needs to be serialized.
$.ajax
({
type: "POST",
url: "/login",
data: $('#frm_login').serialize(),
success: function(data)
...
in the backend, vertx receives this data as a buffer. rest is to parse the buffer by splitting by "&" and "=".
Map<String, String> params = new HashMap<String, String>();
String[] paramSplits = buffer.toString().split("&");
String[] valueSplits;
if (paramSplits.length > 1)
{
for (String param : paramSplits)
{
valueSplits = param.split("=");
if (valueSplits.length > 1)
{
// add this check to handle empty phone number fields
params.put(decode(valueSplits[0]), decode(valueSplits[1]));
}
}
}
hope this will help others!
This can be done using the formAttributes on the http request. Here is an example in scala
req.expectMultiPart(true) //Will expect a form
req.endHandler({
req.formAttributes() //This is used to access form attributes
//some code with attributes
})
Reference: http://vertx.io/core_manual_java.html#handling-multipart-form-attributes