I am trying to call a servlet using ajax call as below:
$.ajax({
url: 'CheckingAjax',
type: 'GET',
data: { field1: "hello", field2 : "hello2"} ,
contentType: 'application/json; charset=utf-8',
success: function (response) {
//your success code
alert("success");
},
error: function (errorThrown) {
//your error code
alert("not success :"+errorThrown);
}
});
However, it goes to error function and shows alert:
not success :Not Found
How is this caused and how can I solve it?
When you specify a relative URL (an URL not starting with scheme or /), then it will become relative to the current request URL (the URL you see in browser's address bar).
You told that your servlet is available at:
http://localhost:8080/FullcalendarProject/CheckingAjax
Imagine that the web page where your ajax script runs is opened via:
http://localhost:8080/FullcalendarProject/pages/some.jsp
And you specify the relative URL url: "CheckingAjax", then it will be interpreted as:
http://localhost:8080/FullcalendarProject/pages/CheckingAjax
But this does not exist. It will thus return a HTTP 404 "Page Not Found" error.
In order to get it to work, you basically need to specify the URL using one of below ways:
url: "http://localhost:8080/FullcalendarProject/CheckingAjax"
This is not portable. You'd need to edit it everytime you move the webapp to another domain. You can't control this from inside the webapp.
url: "/FullcalendarProject/CheckingAjax"
This is also not really portable. You'd need to edit it everytime you change the context path. You can't control this from inside the webapp.
url: "../CheckingAjax"
This is actually also not portable, although you can fully control this from inside the webapp. You'd need to edit it everytime you move around JSP into another folder, but if you're moving around JSPs you're basically already busy coding, so this could easily be done at the same time.
Best way would be to let JSP EL dynamically print the current request context path. Assuming that the JS code is enclosed in JSP file:
url: "${pageContext.request.contextPath}/CheckingAjax"
Or when it's enclosed in its own JS file (good practice!), then create either a global JS variable:
<script>var contextPath = "${pageContext.request.contextPath}";</script>
<script src="yourajax.js"></script>
With
url: contextPath + "/CheckingAjax"
or a HTML5 data attribute on the document element:
<html data-contextPath="${pageContext.request.contextPath}">
<head>
<script src="yourajax.js"></script>
With
url: $("html").data("contextPath") + "/CheckingAjax"
Related
Is there a way to send ajax requests in a Java program? I was thinking that there might be a jquery library somewhere, but I don't even know if jquery would be something that I should use. I'm trying to get the data from a certain request from a website as shown in this function:
function searchFraze(fraze, page) {
page = typeof page !== 'undefined' ? page : 1;
$.ajax({
url: 'ajax/tradeCsRight.php',
type: 'POST',
data: "search=1&type=10&fraze="+fraze+"&page="+page,
success: function(data) {
$("#itemlist").html(data);
}
});
}
Basically, I want to POST custom data in the data field above to the website (http://csgolounge.com/). Honestly, I don't even know if I should be doing what I'm doing this way, or if I should use some other method.
Also, in FireBug, I can see the contents of the tradeCsRight.php file as seen here (which is my goal, to see the html content of this): http://i.imgur.com/8ACnGbp.png
If I open the actual file in chrome, however, the page and html is blank (http://i.imgur.com/LHtKyUb.png). Can someone tell me why this is?
Here is my function. I am trying to get the data from the JSP page below. Both files are at the same location. What is my mistake?
sample.js(included in some file):
function getUnits(){
$.ajax({
url:"../js/addunits.jsp",
success: function(returndata){
alert(returndata);
}
});
}
JSP Page addunits.jsp:
<%
out.print("hi");
>%
In a HTML page, I have a select list.
On change, this function getunits will be called.
$("#select").change(function() {
getUnits();
var e = document.getElementById("select");
var SelValue = e.options[e.selectedIndex].text;
document.getElementById('crs').innerHTML = SelValue;
});
You forgot to flush a buffer.
<%
out.print("hi");
out.flush();
%>
EDIT:
It was an assumption at the first place in case if you have a success status code for the ajax call and it might be in particular scenario like yours but not in all cases because if you used that javascript included in some file, then you might make the same mistake twice. When building some URL on the page don't use a relative path in the code, especially if the page is dispatched/included from different places. Next in the absolute path you should include a context path either ${pageContext.request.contextPath} or use JSTL's <c:url> tag. You can do it for loading sample.js but not inside it because you can use the JSP stuff only on JSP page. So, you can build the URL in the JSP and pass it as parameter to js function like that
sample.js:(included in some file)
function getUnits(theUrl){
$.ajax({
url: theUrl,
success: function(returndata){
alert(returndata);
}
});
}
So, in JSP page (you should use jsp folder where you should keep JSP pages) use
<script>
...
getUnits('${pageContext.request.contextPath}/jsp/addunits.jsp');
...
</script>
I am trying to make a login page in java J2EE. Actually, I succed in making a jsp page, called login.jsp, an ActionSupport class called LoginAction. In my jsp I've created some text area, password area and submit, allowing me to send informations entered in those areas and get them in my action. This works fine.
My problem is that I don't succed in using another function than execute. In my action I have several other functions and I can't call them in my ajax function :
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
$(function() {
$('#submit').click(function() {
var login=$("#login").val();
var password=$("#password").val();
$.ajax({
type: 'POST',
url: 'login.action/test', // -> here it fails.............
data: { login: login, password: password },
success: function() {
alert('YEAH'); },
error: function() {
alert('Request failed'); }
});
});
});
</script>
What should I put in url area, if I want for example to call test function in my LoginAction class? (I've done a test.jsp page, it doesn't change anything...)
OK I found the answer. So here it is :
It's called "dynamic method invocation" (with wildcard method), and you can find the doc here :
http://struts.apache.org/release/2.0.x/docs/action-configuration.html#ActionConfiguration-WildcardMethod
It is very important to use last struts2 release to avoid critical security bugs while using wildcard method - see https://struts.apache.org/release/2.3.x/docs/s2-015.html for details.
use "function nametest()" instead of "function()"
Let's say there is a JSP which has been rendered to the client. On this Jsp, I created a link, I want this link to make a request to the server and server sends a spring from with command object in it and this spring form gets rendered on the already loaded page on client. I mean I do not want whole page to be loaded. Let's take a scenario like there is link 'update contact details' on my page. Clicking on this link makes an ajax request to the server and spring form is sent from the server such that form is populated with the contact details of the user who clicked the link of 'update contact details'. Basically I want stuff like header and footer not to be loaded unnecessarily every time.
Thanks in advance.
IF you have a link as,
<a id="screenId" href="#">
then add <div id="container"></div> somewhere you want your page, also a js function as,
$('#screenId').click(function() {
$.ajax({
type: "GET",
cache: false,
url: "yourControllerURL",
data: "",
success: function(response){
$('#container').html(response);
}
});
});
with the above ajax call, inside your controller, return your jsp with the command object. The controller code may look something like this.
#RequestMapping(value="yourControllerURL")
public String includeAnotherJSP(ModelMap model) {
model.addAttribute("commandObjectName", commandObject);
return "yourJSPMapping/jspName";
}
After your controller will send the response, you will get the required JSP inside the response and you can then load that into your <div id="container"> using above js code.
actually i'm trying to send Arabic data using jQuery ajax to Servlet
but when i try to reprint these data on the page it is displayed like
برÙجة
and this is my jQuery ajax code
jQuery.ajax({
url: "/SearchedCoursesGetter",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
dataType: "text",
data: {
'searchKey': 'حديث'
},
success: function( data ) {
document.write(data);
}));
}
});
and this is the code in java servlet
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF8");
PrintWriter out = response.getWriter();
out.print( request.getParameter("searchKey"));
any body can help me ?
Add this to the top of your JSP
<%# page pageEncoding="UTF-8" %>
This will implicitly do response.setHeader("Content-Type", "text/html;charset=UTF-8") and response.setCharacterEncoding("UTF-8") on the JSP itself. This way the browser will interpret the document (and thus also all JS on it) as UTF-8.
You also need to ensure that your JSP/JS files are saved as UTF-8. Check the editor settings and/or Save As option, depending on the editor used.
Note that the request.setCharacterEncoding("UTF-8") has only effect on POST requests, not on GET requests. For GET requests you need to configure it at servletcontainer level. In for example Tomcat, you need to add URIEncoding="UTF-8" attribute to the <Connector> in /conf/server.xml.
See also:
Unicode - How to get the characters right?