Hi I am currently doing a web application where my Java code will constantly fetch data from a database and update its own static variable. I can confirm that the variable is being updated constantly when I output it in the console, however when I want to use this variable inside my Javascript function (which is inside my .jsp code), it always takes the initial value and never gets updated despite being inside a SetInterval function.
The following is the Javascript segment where I access the Java static variable.
function moveMarker(map,marker){
setInterval( function(){
document.write(<%=DbManager.latitude%>);
},5000);
}
The DbManager.latitude variable is always in it's default value despite being changed consistently when the web app is running. I look forward to any answers I can get to fix this issue, or perhaps alternatives to what I'm trying to achieve.
Better you can goahead with AJAX for this.
<script type="text/javascript">
$(document).ready(function() {
setInterval(ajaxCall, 5000); // 5 MS
});
function ajaxCall() {
$.ajax({
type: "POST",
url: "/getUpdate/" ,
success: function(result) {
document.write(result);
}
}
});
</script>
Call your servlet/controller from AJAX and get the updated value
#Controller
#RequestMapping(value = "clause")
public class ClauseController {
#RequestMapping(value="getUpdate")
#ResponseBody
public String selectClause(ModelMap model) {
DbManager dbManager = DAO.getDbManager;
return "dbManager.latitude";
}
}
Related
I would like to pass the action name and controller name to the #Url.action call within a Javascript function as variables. Is there a method to achieve this?
function list_onSelectionChanged(e) {
var strActionName = "Map";
var strControllerName = "PMO";
$("#content").load("#Url.Action(strActionName,strControllerName)");
}
You can't pass them from client-side code in this way because the server-side code has already run at that point. Specify them directly in the server-side operation:
function list_onSelectionChanged(e) {
$("#content").load("#Url.Action("Map", "PMO")");
}
Note that it looks like the syntax will fail because of nested double-quotes. However, keep in mind that the Razor parser identifies the server-side code separately from the client-side code. So this is the entire server-side operation:
Url.Action("Map", "PMO")
And the result of that operation is emitted to the client-side code:
$("#content").load("result_of_server_side_operation");
I was able to modify the script as follows:
function list_onSelectionChanged(e) {
var url = e.addedItems[0].path;
$.get(url, function (data) {
$("#content").html(data);
});
}
Even simpler:
$("#content").load(url);
This allows a variable to be passed for the url.
SOLVED: I should have added more detail. Even though the External Interface was set up the NetConnection/NetStream objects were not connected to the server. As a result, I couldn't make any calls thru. A very important detail I left out, apologies.
I know that it's proper to have Flash call back to JavaScript when External Interface is ready so I make the call. The JS method gets called correctly but I am unable to then trigger a successful call back to the Flash file. I have to manually set a 1-second timeout to get it to work and I don't understand why. If the External Interface is ready then I should be able to call back to Flash right away, right?
By the way, I'm using SWFObject.embedSWF() to place the Flash file on the page. I've given the file an id and name attributes.
Here's my flash code:
private function init():void // onCreationComplete handler
{
this.setupExternalInterface();
}
private function setupExternalInterface():void
{
if (ExternalInterface.available)
{
ExternalInterface.call("swfIsReady");
ExternalInterface.addCallback("call", makeACall);
}
}
And here's the JSP page:
function swfIsReady(){
setTimeout(flexCall,1000);
}
function flexCall(){
var theApp = getFlexApp(attributes.name);
theApp.call();
}
function getFlexApp(appName)
{
if (navigator.appName.indexOf ("Microsoft") !=-1)
{
return window[appName];
}
else
{
return document[appName];
}
}
This is the only way it works. I thought I could just remove the timeout and call flexCall() directly.
I think you have two little problems in your code :
The first problem is using the call() method which is used in JavaScript to invoke a function.
Try this (I'm not sure that's working but to more see the problem) :
swf_obj.call.call();
but the solution is simply to use another name of your callback function :
swf_obj.make_call();
The second one, is calling ExternalInterface.addCallback() after ExternalInterface.call() which you can just inverse their order to get it working.
So your code can be like this for example :
ActionScript :
private function init(event:FlexEvent):void
{
setupExternalInterface();
}
private function setupExternalInterface():void
{
if (ExternalInterface.available)
{
ExternalInterface.addCallback("make_call", makeACall);
ExternalInterface.call("swfIsReady");
}
}
JavaScript :
function swfIsReady()
{
var swf_obj= swfobject.getObjectById(attributes.name);
if (swf_obj) {
swf_obj.make_call();
}
}
Hope that can help.
I'm using Play! v2 and I added a JavaScript method on my page that tries to retrieve data from the server. The client sends 2 information, a deal and a boolean (withDebug).
My routes file:
GET /:deal/tailLog controllers.MyController.tailLog(deal: String, withDebug: Boolean)
I also tried that, without success:
GET /:deal/tailLog?withDebug=:withDebug controllers.MyController.tailLog(deal: String, withDebug: Boolean)
MyController class contains the following methods:
public static Result tailLog(String deal, Boolean withDebug) {
...
}
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(Routes.javascriptRouter("jsRoutes",
...,
controllers.routes.javascript.MyController.tailLog()
));
}
And finally, the JavaScript call is:
function tailLog() {
var withDebug = $("#logs-debug").is(':checked');
jsRoutes.controllers.MyController.tailLog('mydeal', withDebug).ajax({
...
});
}
When this method is called, my application is calling the URL http://localhost:9000/mydeal/tailLog?withDebug=false, which is the URL pattern I want, but fails with a 404 error message.
Note that before I added the withDebug parameter, everything was working fine.
What am I doing wrong?
Thanks.
In Play 2.0.4, you must use 0/1 to bind boolean parameters (and not false/true)
A little update in your javascript should fix this error:
var withDebug = $("#logs-debug").is(':checked') ? 1 : 0;
I am new to AJAX and currently learning to use it with Spring MVC. I am facing issues on the same.
Before proceeding to the actual real time requirement that I am working on, I am testing out the whole AJAX+Spring MVC+jquery combination with something really basic to get my understanding right.
I am having a search box+'submit' button on a page. I am sending a hard coded text to the Spring controller on submit using $.get. Then I am sending another text from that controller back to the callback function and trying to display the returned text in the callback function using an 'alert' box. This doesn't seem to work.
I see that the call back function is being called(since the 'alert' inside the callback function is being fired) so I am kind of assuming that control is being transferred to the controller and back to the callback method but I am not able to figure out why the text that is returned from the controller is not showing up on the alert box in the call back method. Not sure what I am missing here to capture the return value in the call back method.
Your response and help on this is really appreciated.
Thanks.
HTML for text box and submit button:
<div class = "searchcontactform">
<form id = "searchcontactform" name="searchcontactform" method="GET">
<input type = 'text' size='25' name = "searchlastname" id = "searchlastname" value='Enter Last Name to Search'/>
<input type = "submit" value="Find">
</form>
</div>
JavaScript that triggers on submit of the above form:
<script type="text/javascript" src="${pageContext.request.contextPath}/resources/scripts/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function( ) {
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search", {textsent : 'Hello Controller'},callback);
function callback(textreceived){
alert('In Callback. Text Received is: '+textreceived);
};
});
});
Controller:
#RequestMapping(value = "/search", method = RequestMethod.GET)
public #ResponseBody String searchcontact(#RequestParam(value="textsent") String textsent){
return textsent;
}
Jackson Dependency in POM.xml:
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.7.1</version>
</dependency>
Annotation driven in servlet-context.xml and root-context.xml:
<!-- Enables the Spring MVC #Controller programming model -->
<annotation-driven />
first of all, put return false at the end of submit event handler
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search",
{
textsent : 'Hello Controller'
},
function(textreceived){
alert('In Callback. Text Received is: '+textreceived);
});
return false;
});
if this does not work try using Google Chrome you could debug your javascript application, put a breakpoint inside the callback and at the $.get line
I believe the issue is that you are returning type String and for some reason Spring/Jackson doesn't like when converting to a response. To fix the issue what you should do is the following:
#RequestMapping(value = "/search", method = RequestMethod.GET)
public #ResponseBody List<String> searchcontact(#RequestParam(value="textsent") String textsent){
return Arrays.asList( new String[] { textsent } );
}
It's not ideal and is quite annoying. I haven't really looked into why this happens though as the workaround was fine for me at the time.
UPDATE: Apologies I'm wrong here, you are not assuming the return is going to be JSON at all so making the controller change will have no impact.
Try passing the data returned to the callback as a parameter:
$(document).ready(function( ) {
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search", {textsent : 'Hello Controller'},
function(data){
callback(data);
});
function callback(textreceived){
alert('In Callback. Text Received is: '+textreceived);
};
});
});
You could also setup your callback function as an anonymous function to tidy things up.
$(document).ready(function( ) {
$('#searchcontactform').submit(function(){
$.get("ContactList-JPA/search", {textsent : 'Hello Controller'},
function(data){
alert('In Callback. Text Received is: '+data);
});
});
});
I am making an AJAX calling using JQuery. I get back a JSON object containing HTML and Javascript. Within the javascript, there is a function Initialize(). This returned javascript from the AJAX call should replace the initial definition of Initialize() which was there before the AJAX call was made. So basically, I'm trying to dynamically change the code of the javascript function to code I get back from an AJAX call. Help? Thanks in advance.
I think you might be looking for something like this:
init = function() { alert("init"); };
hash = { "newInit" : function() { alert("newInit"); }};
init(); // alerts "init"
init = hash.newInit;
init(); // alerts "newInit"