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.
Related
I am using Shield UI for my Java application.
I created a custom insert window with "command" as follows:
toolbar: [
{
buttons: [
//{ commandName: "insert", caption: "Agregar Solicitud" }
{ cls: "insertButton", caption: "Agregar Solicitud", click: insertRecord }
],
position: "top"
},
Code for insertRecord:
function insertRecord(index) {
//alert(JSON.stringify(index));
index = 0;
var grid = $("#grid").swidget(),
item = grid.dataItem(index);
initializeWindowWidgets();
editedRowIndex = index;
$("#solId").swidget().value(item.solId);
$("#atmid").swidget().value(item.atmid);
$("#fechaAbastecimiento").swidget().value(item.fechaAbastecimiento);
$("#cargar").swidget().checked(item.cargar);
$("#emergencia").swidget().checked(item.emergencia);
$("#solId").swidget().enabled(true);
$("#atmid").swidget().enabled(true);
$("#fechaAbastecimiento").swidget().enabled(true);
$("#cargar").swidget().enabled(true);
$("#emergencia").swidget().enabled(true);
$("#save").swidget().enabled(true);
$("#window").swidget().visible(true);
//$("#window").swidget().center();
}
function initializeWindowWidgets() {
$("#window").shieldWindow({
position: { left: 500, top: 200 },
width: 320,
height: 360,
title: "Insertar abastecimiento",
modal: true,
visible: false
});
$("#solId").shieldNumericTextBox({
});
$("#atmid").shieldTextBox({
});
$("#fechaAbastecimiento").shieldDatePicker({
});
$("#cargar").shieldCheckBox({
});
$("#emergencia").shieldCheckBox({
});
$("#save").shieldButton({
events: {
click: function (e) {
var grid = $("#grid").swidget(),
editedItem = grid.dataSource.edit(3).data;
editedItem.solId = $("#solId").swidget().value();
editedItem.atmid = $("#atmid").swidget().value();
grid.saveChanges();
$("#window").swidget().close();
}
}
});
Also I can get the row data when I select a row using:
selectionChanged: function (e) {
var selected = e.target.contentTable.find(".sui-selected");
if (selected.length > 0) {
message.innerHTML = selected.get(0).innerHTML;
}
else {
message.innerHTML = "";
}
}
Finally I know how to call a service for example:
$("#grid").shieldGrid({
dataSource: {
events: {
error: function (event) {
if (event.errorType == "transport") {
// transport error is an ajax error; event holds the xhr object
alert(JSON.stringify(event));
alert("transport error: " + event.error.statusText);
// reload the data source if the operation that failed was save
if (event.operation == "save") {
this.read();
}
}
else {
// other data source error - validation, etc
alert(event.errorType + " error: " + event.error);
}
},
},
remote: {
read: {
type: "POST",
url: "abastecimientos/get",
contentType: "application/json",
dataType: "json"
},
modify: {
create: function (items, success, error) {
var newItem = items[0];
$.ajax({
type: "POST",
I need to do these tasks:
Select a row in my grid.
Press insert button.
Shown my custom window with the row's data.
Modify the data showed.
Press a save button and call a remote service in order to insert new row.
I know how to do these tasks separately but tasks 3 and 5 are not clear to me.
I google all internet but I can't figure out how to do it.
Please I would appreciate any suggestion.
Juan
Did you check the following Shield UI demos?
3. Shown my custom window with the row's data
5. Press a save button and call a remote service in order to insert new row
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();
});
i would like to add a compiler to my jsp pages where the user can enter his code and compile it. Any idea whats the method to add a compiler to jsp pages?
Heh. I tried to put in where I got this approach from, but the spam filter prevented it. I can't vouch for whether the urls below are open for anyone to use, but this is one way to do it:
function submitForm(){
jQuery.support.cors = true;
$('#wait').show();
if ($.browser.webkit || $.browser.mozilla) {
var url = "http://www.compileonline.com/compile_new.php";
}else{
var url = "col_proxy.php";
}
$.ajax({
type: "POST",
cache: false,
crossDomain: true,
url: url,
target: "view",
data: $("#ff").serialize(),
success:function(data)
{
$('#view').contents().find("html").html(data);
$('#wait').hide();
return false;
},
error:function (data, status, error) {
alert(error);
return false;
}
});
return false; // avoid to execute the actual submit of the form.
}
I'm still new with jsTree, JavaScript and jQuery functions.
My problem is that I need to refresh the header so when I click certain nodes in jstree the header will be refreshed.
The jstree is located in applet.jsp and the function for refreshing the header is located in header.jsp.
How can I call the refresh method for refreshing inside jstree?
This is my jstree in applet.jsp:
var selected_folder = "folder_${user.defaultFolder}";
$(document).ready(function() {
jQuery("#folder_tree").jstree({
"xml_data" : {
"ajax" : {
"url" : "<%=request.getContextPath()%>" + "/ListFolder.action"
},
"xsl" : "nest"
},
"ui" : {
"initially_select" : [ "#folder_${user.defaultFolder}" ]
},
"types" : {
"types" : {
"leaf" : {
"icon" : {
"image" : "<%=request.getContextPath()%>/images/icons/leaf.jpg"
}
},
"share" : {
"icon" : {
"image" : "<%=request.getContextPath()%>/images/icons/share.jpg"
}
}
}
},
"themes" : {
"theme" : "msam"
},
"plugins" : [ "themes", "xml_data", "ui", "types" ]
});
jQuery("#folder_tree").bind('loaded.jstree', function() {
jQuery("#folder_tree").jstree('open_all');
});
jQuery("#folder_tree").bind("select_node.jstree", function(e, data) {
var haveContent = data.rslt.obj.attr("haveContent");
if (haveContent === 'false') {
return;
}
var id = data.rslt.obj.attr("id");
id = id.substring("folder_".length);
parent.content.location.href = "<%=request.getContextPath()%>"
+ "/home/Folder.action?folderID="
+ id;
//alert(data.inst.get_text(data.rslt.obj)); // NODE TEXT
$.ajax({
url : "<%=request.getContextPath()%>" + "/WebContent/home/header.jsp",
data :{folderId,id},
cache:false,
success : function(data){
setupTree(data); //put your logic to set tree inside a method called setupTree or whatever you want to call it.
}
});
});
jQuery("#folder_tree").bind("refresh.jstree", function (event, data) {
jQuery("#folder_tree").jstree("select_node", selected_folder);
});
});
var tree_select_node = function(id) {
selected_folder = "#folder_" + id;
jQuery("#folder_tree").jstree("deselect_all");
jQuery("#folder_tree").jstree("refresh");
}
And this is the method/function for refreshing the header in header.jsp:
function selectHeaderLink(selectedLinkID) {
var linkIDArray = new Array('homeLink', 'newFolderLink', 'settingsLink', 'reportsLink');
resetHeaderLinks(linkIDArray, 'tab_link');
if(linkIDArray.length > 0) {
for(var i=0;i<linkIDArray.length;i++) {
if(linkIDArray[i] == selectedLinkID) {
var myLink = document.getElementById(linkIDArray[i]);
var row = myLink.parentNode;
row.style.height = "28";
row.style.backgroundImage = 'url(../images/bg-topmenu.jpg)' ;
myLink.style.color = "white";
break;
} //--end: if-for-if
} //--end: for-if
} //--end: if
}
function windowOnload(){
selectHeaderLink('homeLink');
}
I already tried using an ajax request but I'm still confused where to put this ajax request.
Sorry for my bad English. I hope someone will help me with this problem.
i already find the answer
jQuery("#folder_tree").bind("select_node.jstree", function(e, data) {
var haveContent = data.rslt.obj.attr("haveContent");
if (haveContent === 'false') {
return;
}
selectHeaderLink('homeLink');
var id = data.rslt.obj.attr("id");
id = id.substring("folder_".length);
parent.content.location.href = "<%=request.getContextPath()%>"
+ "/home/Folder.action?folderID="
+ id;
//alert(data.inst.get_text(data.rslt.obj)); // NODE TEXT
});
i just put the function into the jquery n then remove the function to centralize js file..and its work..
I have a web application with HTML / jQuery which ic connected with AJAX / JSON to a backend system with Java EE / Spring MVC.
In the frontend, a Person can be created by fill in the form fields and then it is submitted and this jQuery code executed:
var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {
alert("Person with ID "+data.person.id+"' added successfully");
});
In the best case, the Person is created and I'll get a Person object and I can access the values with data.person.*.
Now I want to validate the data which is sent to the backend system and in a case of an error, I want to display in the first step an alert error message.
I did this in the backend system:
#RequestMapping(value="add/", method=RequestMethod.POST)
public #ResponseBody Map<String, ? extends Object> addPerson(#RequestBody Person p, HttpServletResponse response) {
Set<ConstraintViolation<Person>> failures = validator.validate(p);
if (!failures.isEmpty()) {
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return validationMessages(failures);
} else {
Person person = this.personService.addPerson(p);
return Collections.singletonMap("person", new SerialPerson(person.getId(), person.getName(), ...));
}
}
// internal helpers
private Map<String, String> validationMessages(Set<ConstraintViolation<Person>> failures) {
Map<String, String> failureMessages = new HashMap<String, String>();
for (ConstraintViolation<Person> failure : failures) {
failureMessages.put(failure.getPropertyPath().toString(), failure.getMessage());
System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage());
}
return failureMessages;
}
My Person object is annotated, and I get the System.out.println(failure.getPropertyPath().toString()+" - "+failure.getMessage()); on the console, that for example, "name - must be between 1-30 chars"
But how can create an alert message in jQuery in the frontend system?
Thank you in advance for your help & Best Regards.
Update: Link to the Spring MVC AJAX example, where I found the validationMessages method. But there is also no solution how to get the error message.
SOLUTION:
I have to call:
jQuery.ajax({
'type': 'POST',
'url': "add/",
'contentType': 'application/json',
'data': JSON.stringify(person),
'dataType': 'json',
'success': function(data) {alert("success");},
'error': function(xhr) {alert(xhr.responseText);}
});
You can do something like this:
var person = $(this).serializeObject();
$.postJSON("add/", person, function(data) {
if(data.person) {
alert("Person with ID "+data.person.id+"' added successfully");
}
else {
var errors = "";
for(var key in data) if(data.hasOwnProperty(key)) {
errors += data[key] + "\n";
}
alert(errors);
}
});
You shouldn't need to send back a bad request either. Is this what you want?
UPDATE
You can use the code shown in Spring Source, but you'd have to use jQuery.ajax
jQuery.ajax({
type: 'POST',
url: "add/",
data: person,
dataType: "json",
success: function(data) {
alert("Person with ID "+data.person.id+"' added successfully");
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
var errorJSON = JSON.parse(XMLHttpRequest.responseText); //if this is JSON otherwise just alerting XMLHttpRequest.responseText will do
var errors = "";
for(var key in errorJSON) if(errorJSON.hasOwnProperty(key)) {
errors += errorJSON[key] + "\n";
}
alert(errors);
}
});