How to call two java script in onchange simultaneously? - java

I am calling two java script in onChange which are called two different action of struts.
Code follows:
<html:select property="countryid" onchange="retrieveURL('showStates.do?country=' + this.value);retrieveURL2('showStatesNotinGroup.do?country=' + this.value);">
function retrieveURL(url)
{
if(window.XMLHttpRequest)
{
// Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processStateChange;
req.open("GET", url, true);
req.send();
}
}
}
function processStateChange() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("box2View").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
function retrieveURL2(url)
{
if (window.XMLHttpRequest) {
// Non_IE broeser
req = new XMLHttpRequest();
req.onreadystatechange = processCityChange;
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) {
//IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processCityChange;
req.open("GET", url, true);
req.send();
}
}
}
function processCityChange(){
if (req.readyState == 4) { //Coplete
if (req.status == 200) { // OK responce
document.getElementById("box1View").innerHTML = req.responseText;
}else {
alert("Problem: " + req.statusText);
}
}
}
For this action mapping is:
<action path="/showStates" type="com.dss.action.ShowStatesAction" validate="false" name="stateForm">
<forward name="success" path="/showStates.jsp"/>
</action>
<action path="/showStatesNotinGroup" type="com.dss.action.ShowStatesAction" validate="false" name="stateForm">
<forward name="success" path="/showStatesNotInGroup.jsp"/>
</action>
</action-mappings>
When I run it one by one for checking it works fine, but when I call it together it's giving me an unexpected result.
I want to call first java script and check whether it's successful and then call the second one on same onChange.

You need to declare your req variable scoped to each function otherwise both functions are using the same global variable. You might also look at using a framework, such as jQuery, to do this as you'll have well-tested, browser-independent code with less effort on your part.
function retrieveURL(url)
{
var req; // <-- declare local so the scopes don't conflict
if(window.XMLHttpRequest)
{
...
}
function retrieveURL2(url)
{
var req; // <-- declare local so the scopes don't conflict
if(window.XMLHttpRequest)
{
...
}
And with jQuery
<script type="text/javascript" src=...jquery_location, local or via Google CDN
<script type="text/javascript">
$(function() {
$('#countryid').on('change', function() { // single handler for both
var $this = $(this), // cache jQuery object for later use
val = $this.val(); // cache value
$.get('showStates.do?country=' + val, function(result) {
$('#box2View').html(result);
});
$.get('showStatesNotinGroup.do?country=' + val, function(result) {
$('#box1View').html(result);
});
});
});
</script>

i found the way to do it and its work fine so i share you my way
<html:select property="countryid" onchange="retrieveURL(this.value);">
and the java script is like
function retrieveURL(url){
var newUrl = 'showStates.do?country='+url;
// do some thing
retrieveURL2(url);
}
function retrieveURL2(url){
var newUrl2 = 'showStatesNotinGroup.do?country='+url;
// do same thing
}

Related

Angular JS - How to get spring returned map value inside angular controller?

I am new to angular, can anyone tell me how to retrieve spring returned map value inside angular's controller?
Here is my code snippet:
app.js
// Service -----------------------------------------------------------------
myApp.service('FolderService', function ($log, $resource, $http) {
return {
onlineView: function(docId) {
var viwerResource = $resource('processOnlineView', {}, {
get: {method: 'POST', params: {'docId' : docId}}
});
return viwerResource.get();
}
}
})
// Controller -----------------------------------------------------------------
.controller('FolderController', function ($scope, $log, FolderService) {
//click online view
$scope.view = function(doc) {
var rtnMap = FolderService.onlineView(doc.cmObjectId);
console.log('rtnMap: ' + rtnMap );
// it shows rtnMap: [object Object]
var key = 'response';
var value = rtnMap[key];
console.log('value: ' + value );
// I want to get map value, but it shows undefined
// I except get "d:/tomcat/bin/hello.swf" here
$scope.rtnFileName = rtnMap;
}
});
my spring controller java code
#RequestMapping(value = "/processOnlineView", method = RequestMethod.POST)
public #ResponseBody Map<String, String> processOnlineView(#RequestParam(value = "docId") String docId) {
String resultDocName = "";
try {
// get File by docId
File file = queryFile(docId);
// set resultDocName value
resultDocName = file.getAbsolutePath(); // real file path, like: d:/tomcat/bin/hello.swf
} catch (Exception e) {
e.printStackTrace();
}
return Collections.singletonMap("response", resultDocName);
}
chrome log:
I can get expect value in html by using this:
rtnFileName: {{rtnFileName.response}}
html shows:
rtnFileName: d:/tomcat/bin/hello.swf
But how to get map value in angular controller directly?
Any suggestion would be appreciated.
Problem solved.
First, use $http post instead of $resource:
onlineView: function(docId) {
$http({
method: 'POST',
url: urlBase + '/processOnlineView',
params: {
docId: docId
}
})
.success(function(data, status, headers, config) {
console.log('success data: ' + data); // result: success data: [object Object]
for (key in data){
console.log('>> data key: ' + key );
console.log('>> data value: ' + data[key] );
}
var resultDocName = data['response'];
console.log('resultDocName: ' + resultDocName);
runFlexpaper(resultDocName);
})
.error(function(data, status, headers, config) {
});
}
Second, retrieve returned map inside 'success' block, because $http post is asynchronous call.
Use a service. For example:
var app = angular.module('myApp', [])
app.service('sharedProperties', function () {
var mapCoord= 'Test';
return {
getProperty: function () {
return mapCoord;
},
setProperty: function(value) {
mapCoord= value;
}
};
});
Inside your Main controller
app.controller('Main', function($scope, sharedProperties) {
$scope.mapCoord= sharedProperties.setProperty("Main");
});
Inside your Map controller
app.controller('Map', function($scope, sharedProperties) {
$scope.mapCoord= sharedProperties.getProperty();
});

Stream videos in client app using Ajax and java Restlet

Hi I want to stream videos in client app but videos are located in server app. I am using java Restlet and Jquery Ajax to connect client app to server app. Through Ajax call i am connecting to Restlet. I don't know how to send response to ajax after streaming video from server side, how ajax receives response and how to play video in browser. Can any one help me to handle this.
Here is my code
Html:
<button id="playVideo" class="btn-primary">PlayVideo</button>
<video id="videoTab" height="300" width="500" style="display: none" controls ></video>
Ajax Call to server
$('#playVideo').click(function (){
var jsonObj = {};
jsonObj.userId = "siva";
jsonObj.file = "sample.mp4";
//console.log("json obje :"+ JSON.stringify(jsonObj))
// Rest call to play videos.
$.ajax({
type : 'GET',
url : config.streamVideo,
//dataType : 'json',
data : JSON.stringify(jsonObj),
contentType : "application/json",
mimeType : "video/mp4",
processData : false,
crossDomain : true,
success : function(result) {
//console.log("login result : " + JSON.stringify(result));
if (result) {
console.log("success.....");
srcPath = "data:video/mp4;"+result;
$('#videoTab').attr('src', srcPath);
$('#videoTab').css('display', 'block');
$('#videoTab').attr('autoplay', true);
} else {
alert('failed...');
}
},
error : function(){
alert('error')
}
});
});
RestletCode:
#Get
public InputRepresentation handleRequest(Representation entity) throws IOException, ResourceException {
// Set response headers
Series<Header> responseHeaders = (Series<Header>) getResponse().getAttributes().get("org.restlet.http.headers");
if (responseHeaders == null) {
responseHeaders = new Series<Header>(Header.class);
getResponse().getAttributes().put("org.restlet.http.headers", responseHeaders);
}
responseHeaders.add(new Header("Access-Control-Allow-Origin", "*"));
logger.debug("+++++++++++++++++++Entered in play video restlet +++++++++++++++");
// Convert Rest type request to Servlet request
httpServletRequest = ServletUtils.getRequest(getRequest());
// Get Servlet context object.
sc = httpServletRequest.getServletContext();
// Get input file path.
logger.debug("------->getRealPath " + sc.getRealPath("/"));
String filePath = sc.getRealPath("/") + "WEB-INF\\data\\videos\\sample.mp4";
final File file = new File(filePath);
if (file.exists()) {
logger.debug("Requested file path : " + file.getAbsolutePath());
logger.debug("inputRepresentation :" + inputRepresentation);
fis = new FileInputStream(file);
inputRepresentation = new InputRepresentation(new InputStream() {
private boolean waited = false;
#Override
public int read() throws IOException {
waited = false;
// read the next byte of the FileInputStream, when reaching the
// end of the file, wait for 2 seconds and try again, in case
// the file was not completely created yet
while (true) {
byte[] b = new byte[1];
if (fis.read(b, 0, 1) > 0) {
return b[0] + 256;
} else {
if (waited) {
return -1;
} else {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
logger.error("Exception while streaming video : ", ex);
}
waited = true;
}
}
}
}
}, MediaType.VIDEO_MP4);
} else {
logger.debug("Requested file not found : " + filePath);
}
//logger.debug("inputRepresentation :");
return inputRepresentation;
}
Thanks in advance
After reading your comment, here is my understanding of what you should do.
I would not send json to a resource in order to get something, I would just send a simple GET request.
You need:
a resource that returns the file of a video according to its identifier. For the matter of illustration, let's say its url template is /videos/{videoid}
a web page that contains the links, and the empty video player
some javascript that set the "src" attribute video player with the url defined above: /videos/{videoid}. The way you compute the videoid is your own business.
Here is the server code:
the Restlet application, that defines the URI templates
#Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
// attaches the resource that represents a video, according to its identifier
router.attach("/videos/{videoid}", VideoServerResource.class);
// ... other instructions
return router;
}
the video server resource:
public class VideoServerResource extends ServerResource {
private File video;
#Override
protected void doInit() throws ResourceException {
String videoId = getAttribute("videoid");
// Compute path
String path = "/tmp/" + videoId + ".mp4";
video = new File(path);
// takes care of not found status responses.
setExisting(video.isFile());
}
#Get("mp4")
public File represent() {
return video;
}
}
Here is the client code. This is a sample Web page, with an empty video player. When clicking on the button, the video player is asked to play the http://example.com:9000/videos/testvideo video. In your case, the value testvideo is simply deduced from the link the user click on.
<!DOCTYPE html>
<html>
<head>
<script src="/static/jquery.js"></script>
<script>
$('#playVideo').click(function (){
srcPath = "http://127.0.0.1:9000/videos/testvideo";
$('#videoTab').attr('src', srcPath);
$('#videoTab').css('display', 'block');
$('#videoTab').attr('autoplay', true);
});
</script>
</head>
<body>
<button id="playVideo" class="btn-primary">PlayVideo</button>
<video id="videoTab" height="300" width="500" style="display: none" controls ></video>
</body>
</html>
I hope this will help you.

Jquery Ajax data not sent through multiple tabs

I am using jquery Ajax to send my parameters to backend in java and return value is of JSON type. My application has different categories which uses the same jsp. If i open a single category in one tab everything is working fine. But when i open different categories in different tabs, the last opened tab/category only sends parameters to the back end, the first opened tabs triggers the ajax call, but the parameters passed are not available in the back end. PFB the code snippet of the AJAX call made,
function addThings(things) {
$(document).ready(function() {
var parameters = {
_method : 'put'
};
for ( var i = 0; i < things.length; i++) {
if (parameters[things[i][0]] != null) {
parameters[things[i][0]] = parseInt(parameters[things[i][0]])
+ parseInt(things[i][1]);
} else {
parameters[things[i][0]] = things[i][1];
}
}
$.ajax({
type : "POST",
url : "addThings.do",
async : false,
data : parameters,
datType : "json",
failure : function(data) {
ShowFatalError();
},
success : function(response) {
var resp =$.getJSON(response);
if (resp == null) {
ShowFatalError();
} else {
if (response.exceptionsOccured) {
ShowFatalError();
}
CurrentJSON = response;
CountDisplay(CurrentJSON);
return (CurrentJSON);
}
}
});
});
return CurrentJSON;
}
The above function is triggered on a button click.
Please help me out in this.

Struts 2.0 action method called without actually invoking

Found a strange issue in Struts action,
The scenario is like below ,
When I was in employees.jsp which just shows list of employees fetched from server , when an employee div is clicked, I will create a dynamic form as "employeeDetailsForm" in a javascript method, which has a hidden input field that holds value of employee code,
And I attached an action to the form as "getEmployeeDetails", when an employee div is clicked
It will submit the action and navigates to the employeeDetails.jsp,
In employeeDetails.jsp I will show set of details of that particular employee.
for his list of achievements I have upVote feature.
so when I click on upVote, upVote action gets called using ajax in a js method.
When upVote action is success , immediately again "getEmployeeDetails" action is getting called which is a strange behaviour.
I am not able to backtrace the call stack since many system defined methods are shown,
I just cross checked whether my "employeeDetailsForm" is exist in second jsp page as well and some how the form is being submitted somewhere ?
but when I checked inspector in browser, that form element was not there at all,
I also checked by calling document.getElementById("employeeDetailsFormId") which returned null
Then from where this method is getting called ?
How to trace this issue ?
Update -
Source code for reference
in employees.jsp - JS method to submit form to fetch details
var empDetForm = document.createElement("form");
empDetForm.id=“empDetailsId”;
empDetForm.name=“employeeDetailsForm";
empDetForm.method="POST";
empDetForm.action="getEmployeeDetails";
var empCodeinput = document.createElement("input");
empCodeinput.setAttribute("type","hidden");
empCodeinput.id= empCode;
empCodeinput.name=“empCode”;
empDetForm.appendChild(empCodeinput);
empDetForm.submit();
In employeeDetails.jsp - JS method to call upvote service using ajax
var formdata = "isUpVote="+isUpVote+”&”+”selectedAchievement="+achievementId;
$.ajax({
type: 'POST',
url: ‘achievementUpVote’,
contentType: "application/x-www-form-urlencoded",
async: false,
//processData:false,
data :formdata,
mimeType:"multipart/form-data",
cache: false,
processData:false,
datatype: "json",
success: function(response) {
alert("success upvote for achievement”);
},
error: function(e) {
alert("Fail upvote");
}
});
Java struts action methods
public String getEmployeeDetails() throws JSONException {
EmployeeDetailsIntf empDetailsImplObj = new EmployeeDetailsIml();
JSONObject jsonInput = new JSONObject();
String userName = ApplicationData.getUserName();
String accessCode = ApplicationData.getAccessCode();
jsonInput.put(“empId”, getEmpId());
jsonInput.put("un", userName);
jsonInput.put("ac", accessCode);
status = empDetailsImplObj.callGetEmpDetailsService(jsonInput);
if(status == true){
return "SUCCESS";
}
return "FAIL";
}
Another action
public String achievementRating() {
String userName = ApplicationData.getUserName();
String accessCode = ApplicationData.getAccessCode();
JSONObject jsonInputData = new JSONObject();
try {
jsonInputData.put("un", userName);
jsonInputData.put("ac", accessCode);
jsonInputData.put("aid", selectedAchivement);
EmployeeDetailsIntf empDetailsImplObj = new EmployeeDetailsIml();
boolean status = empDetailsImplObj.upVoteAchievement(jsonInputData, isUpVote);
if (status) {
return "RATE_ACHIEVEMENT_SUCCESS";
}else{
return "FAIL";
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null ;
}
struts.xml
<action name=“getEmployeeDetails” class="com.action.EmployeeDetailsAction"
method="getEmployeeDetails">
<result name="SUCCESS”>../empDetails/employeeDetails.jsp</result>
<result name="FAIL">failure.jsp</result>
</action>
<action name="achievementUpVote" class="com.action.EmployeeDetailsAction"
method="achievementRating">
<result name="RATE_ACHIEVEMENT_SUCCESS" type="json"/>
<result name="FAIL" type="json"/>
<result name="FAIL">failure.jsp</result>
</action>

How to print a page content (div, form, jqgrid) using a single button click?

i.e. When I click the button from my page, the desired page content should get printed in a sheet. The main goal over here is, it should not show me with the print dialog box/print preview of the page asking for OK or CANCEL button where we can also choose for multiple prints of a particular page. Thanks in advance.
Create a print.js file by this code :
// -----------------------------------------------------------------------
(function($) {
var opt;
$.fn.jqprint = function (options) {
opt = $.extend({}, $.fn.jqprint.defaults, options);
var $element = (this instanceof jQuery) ? this : $(this);
if (opt.operaSupport && $.browser.opera)
{
var tab = window.open("","jqPrint-preview");
tab.document.open();
var doc = tab.document;
}
else
{
var $iframe = $("");
if (!opt.debug) { $iframe.css({ position: "absolute", width: "0px", height: "0px", left: "-600px", top: "-600px" }); }
$iframe.appendTo("body");
var doc = $iframe[0].contentWindow.document;
}
if (opt.importCSS)
{
if ($("link[media=print]").length > 0)
{
$("link[media=print]").each( function() {
doc.write("");
});
}
else
{
$("link").each( function() {
doc.write("");
});
}
}
if (opt.printContainer) { doc.write($element.outer()); }
else { $element.each( function() { doc.write($(this).html()); }); }
doc.close();
(opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).focus();
setTimeout( function() { (opt.operaSupport && $.browser.opera ? tab : $iframe[0].contentWindow).print(); if (tab) { tab.close(); } }, 1000);
}
$.fn.jqprint.defaults = {
debug: false,
importCSS: true,
printContainer: true,
operaSupport: true
};
// Thanks to 9__, found at http://users.livejournal.com/9__/380664.html
jQuery.fn.outer = function() {
return $($('').html(this.clone())).html();
}
})(jQuery);
And then include your print.js on an html page and see the demo of this :
<script>
jQuery(document).ready(function () {
jQuery("#printBtn").click(function(){
jQuery("#print").jqprint();
});
});
</script>
<input type="button" id="printBtn" value="Print" />
<div id="print">
This will print this content.
</div>
What is the browser you are targeting? There are some browser specific ways of doing this.
For IE :
<script language='VBScript'>
Sub Print()
OLECMDID_PRINT = 6
OLECMDEXECOPT_DONTPROMPTUSER = 2
OLECMDEXECOPT_PROMPTUSER = 1
call WB.ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_DONTPROMPTUSER,1)
End Sub
document.write "<object ID='WB' WIDTH=0 HEIGHT=0 CLASSID='CLSID:8856F961-340A-11D0-A96B-00C04FD705A2'></object>
</script>
window.print();
Ref : msdn blog

Categories