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>
Related
Environment: IE7, jQuery 1.1 , Struts 1
Context: Making an ajax call to a Java method which, and the end, reloads the same jsp.
The steps are: jsp A -->request to java method-->doing some stuff-->ActionForward to jsp A, which is returned in the response.
Actually I'm doing this with a single request using location.href and it's working properly.
Now I need to handle multiple requests and conditions and the only way I thought was by using nested ajax calls with async:false, but that's not the point.
The problem is ajax does not reloads the jsp like location.href does.
This jsp is just a smaller part of the main jsp, so I'm not reloading the whole jsp. I guess I have to handle the response in some way, but how?
Call with location.href:
<script>
function myFunction(){
location.href = 'path/to/java/method=with_some_parameters';
}
</script>
Call with ajax:
<script>
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
//nested ajax
}
});
}
</script>
There is a similiar question:
Reload a page after jquery ajax call,
but it didn't help.
Another: How to manage a redirect request after a jQuery Ajax call, this looks better. I'm trying some things.
As I got the full html in the response ('data' in my case), It worked using
function myFunction(){
jQuery.ajax({
url:'path/to/java/method=with_some_parameters'
async:false,
success:function(data){
document.open();
document.write(data);
document.close();
//nested ajax
}
});
}
Source Replacing Entire Page Including Head Using Javascript
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"
I have a basic html file which is attached to a java program. This java program updates the contents of part of the HTML file whenever the page is refreshed. I want to refresh only that part of the page after each interval of time. I can place the part I would like to refresh in a div, but I am not sure how to refresh only the contents of the div. Any help would be appreciated. Thank you.
Use Ajax for this.
Build a function that will fetch the current page via ajax, but not the whole page, just the div in question from the server. The data will then (again via jQuery) be put inside the same div in question and replace old content with new one.
Relevant function:
http://api.jquery.com/load/
e.g.
$('#thisdiv').load(document.URL + ' #thisdiv');
Note, load automatically replaces content. Be sure to include a space before the id selector.
Let's assume that you have 2 divs inside of your html file.
<div id="div1">some text</div>
<div id="div2">some other text</div>
The java program itself can't update the content of the html file because the html is related to the client, meanwhile java is related to the back-end.
You can, however, communicate between the server (the back-end) and the client.
What we're talking about is AJAX, which you achieve using JavaScript, I recommend using jQuery which is a common JavaScript library.
Let's assume you want to refresh the page every constant interval, then you can use the interval function to repeat the same action every x time.
setInterval(function()
{
alert("hi");
}, 30000);
You could also do it like this:
setTimeout(foo, 30000);
Whereea foo is a function.
Instead of the alert("hi") you can perform the AJAX request, which sends a request to the server and receives some information (for example the new text) which you can use to load into the div.
A classic AJAX looks like this:
var fetch = true;
var url = 'someurl.java';
$.ajax(
{
// Post the variable fetch to url.
type : 'post',
url : url,
dataType : 'json', // expected returned data format.
data :
{
'fetch' : fetch // You might want to indicate what you're requesting.
},
success : function(data)
{
// This happens AFTER the backend has returned an JSON array (or other object type)
var res1, res2;
for(var i = 0; i < data.length; i++)
{
// Parse through the JSON array which was returned.
// A proper error handling should be added here (check if
// everything went successful or not)
res1 = data[i].res1;
res2 = data[i].res2;
// Do something with the returned data
$('#div1').html(res1);
}
},
complete : function(data)
{
// do something, not critical.
}
});
Wherea the backend is able to receive POST'ed data and is able to return a data object of information, for example (and very preferrable) JSON, there are many tutorials out there with how to do so, GSON from Google is something that I used a while back, you could take a look into it.
I'm not professional with Java POST receiving and JSON returning of that sort so I'm not going to give you an example with that but I hope this is a decent start.
You need to do that on the client side for instance with jQuery.
Let's say you want to retrieve HTML into div with ID mydiv:
<h1>My page</h1>
<div id="mydiv">
<h2>This div is updated</h2>
</div>
You can update this part of the page with jQuery as follows:
$.get('/api/mydiv', function(data) {
$('#mydiv').html(data);
});
In the server-side you need to implement handler for requests coming to /api/mydiv and return the fragment of HTML that goes inside mydiv.
See this Fiddle I made for you for a fun example using jQuery get with JSON response data: http://jsfiddle.net/t35F9/1/
Usefetch and innerHTML to load div content
let url="https://server.test-cors.org/server?id=2934825&enable=true&status=200&credentials=false&methods=GET"
async function refresh() {
btn.disabled = true;
dynamicPart.innerHTML = "Loading..."
dynamicPart.innerHTML = await(await fetch(url)).text();
setTimeout(refresh,2000);
}
<div id="staticPart">
Here is static part of page
<button id="btn" onclick="refresh()">
Click here to start refreshing every 2s
</button>
</div>
<div id="dynamicPart">Dynamic part</div>
$.ajax(), $.get(), $.post(), $.load() functions of jQuery internally send XML HTTP request.
among these the load() is only dedicated for a particular DOM Element. See jQuery Ajax Doc. A details Q.A. on these are Here .
I use the following to update data from include files in my divs, this requires jQuery, but is by far the best way I have seen and does not mess with focus. Full working code:
Include jQuery in your code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
Create the following function:
<script type="text/javascript">
function loadcontent() {
$("#test").load("test.html");
//add more lines / divs
}
</script>
Load the function after the page has loaded; and refresh:
<script type="text/javascript">
$( document ).ready(function() {
loadcontent();
});
setInterval("loadcontent();",120000);
</script>
The interval is in ms, 120000 = 2 minutes.
Use the ID you set in the function in your divs, these must be unique:
<div id="test"></div><br>
I'm trying to get value from Action using Ajax request, but I'm having problem in using struts tag in javascript to show the value.
Javascript code:
dojo.xhrPost({
url: "dashboard"
,content: myParameterscomp
, handle: function(response, ioargs) {
if (ioargs.xhr.status == 200)
{
var data = "<s:property value='#request.consumptionData'/>"
console.log(data);
}
}
,error: function (data) {
handleError(data.description);
}
});
Java code:
Map request = (Map)context.get("request");
request.put("consumptionData", 43);
I'm getting the value of data as <s:property value='#request.consumptionData'/> on console instead of 43. I'm using struts2. My javascript code is in JSP file. Could anyone please tell me how can I show the value?
You seems to be calling /dashboard page via Ajax from your homepage. And expecting it to send you request attribute consumptionData. This won't work as your JSP does not contain required data. You need to put data in JSP and then fetch the same in Ajax. Convert your response to JSON. The simplest way of doing this would be to put following like of code in your Ajax response JSP.
Dashboard.jsp
{"consumptionData": < "<s:property value='#request.consumptionData'/>"}
And in main page when you load this JSP via ajax, you can parse this JSON output and use data in Javascript.
var json = JSON.parse(response);
var data = eval(json.consumptionData);
Code in browser accepts JSON. You could serialize you request as JSON and embed in you JavaScript file. For example:
var data = <%= toJson(request.get("consumptionData")) %>
If the data is simplely Integer values, you can even directly put the value in the code:
var data = <%= request.get("consumptionData") %>
The syntax could be vary (I'm not familiar with struts tag), but the idea is the same.
I am using Dojo library. How can I replace all the content of my jsp/html content. I am trying to dynamically reload my page when a data is updated.
Here is my dojo code:
function reloadPage() {
var thisUrl = '/CBS/a/customer/' + customerId + '/profile';
dojo.xhrGet({
url: thisUrl,
load: function (data) {
document.body.innerHTML = data;
},
error: function (data, ioArgs){
document.body.innerHTML = "unknown error";
}
});
}
The server returns a complete html code including the html tags. The data variable holds all the html tags. In my code I did document.body.innerHTML = data;which is wrong because the content of body is replaced by a whole html page. It looks like ajax is working because its updated dynamically but my buttons are not working anymore. Please help.
Why do you use AJAX if you want to update the whole page? Purpose of using of AJAX - update part of content(page), not updating the whole page. If you want to update the whole page, may be it will be more appropriate to use reload?