e p e p - 5 months ago 18
Javascript Question

AJAX call from a popup modal

Trying to call an AJAX request from a modal popup.

function exportReport(){
$.ajax({
url : 'exportReport',
data : {
from : fromDate,
to : toDate
},
success : function(responseText) {
alert("Success");
}
});
}


Servlet:

@WebServlet("/exportReport")
public class GenerateReportServlet extends HttpServlet {

}


main.jsp:

<%@ page language="java" session="false" 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>

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<head>
....................
<div class="modal fade" id="myModal" role="dialog">
<button type="button" class="btn btn-primary btn-sm" data-dismiss="modal" onclick="exportReport()">Export</button>
</div>
....................
</html>


main.jsp is inside
webapps\views
. This export button is in a popup modal div. Click on Export is calling,

http://localhost:8080/myApp/views/exportReport?from=1465972200000&to=1465107600000
and is HTTP Status 404. It should come like
http://localhost:8080/myApp/exportReport?from=1465972200000&to=1465107600000
. How that
/views/
is coming in the url.

Answer

You should be more specific when setting the url, else it will be appended to the current url.

Use url : '/myApp/exportReport' instead in the AJAX call.

The leading slash indicates that the url is absolute.

Omitting the leading slash makes the url relative to the current url.