How to save data from Ext.FormPanel to server? - java

I have a store and a FormPanel. I want to send data from the FormPanel to a server:
var store_form=null;
store_form = new Ext.data.Store({
url: url_servlet+"kadastr_zemform.jsp",
reader: new Ext.data.XmlReader({
totalProperty: "results",
record: "contact",
fields: [
]}),
});
});
store_form.load();
Panel
var podform = new Ext.FormPanel({
labelAlign: 'left',
id: 'tab_6',
frame:true,
title: 'Договоры подряда',
bodyStyle:'padding:5px 5px 0',
width: 600,
reader: new Ext.data.XmlReader({}),
listeners: {
'activate' : function(pod_form,records,options) {
console.log("store:"+store_form);
this.loaded = true;
//alert("loaded");
//console.log(store.getAt(0));
var record = store_form.getAt(0);
podform.getForm().loadRecord(record);
}
},
fields[]
});
podform.addButton({
text: 'Submit',
//disabled:true,
handler: function(){
podform.getForm().submit({url:url_servlet+'submit.jsp', waitMsg:'Saving Data...', submitEmptyText: false});
}
});
In firebug I can see that nothing is sent to the server. What am I doing wrong?
Another question: what can I do on the server side to get this data?
UPDATE
I forgot to add XMLReader to form. But nothing has changed.
UPDATE2
Now parameters are sent to the server:
But I am getting an error:
SyntaxError: syntax error
...ayer=a;this.activate()}else{this.layer=a}},setTargets:function(b){this.targets=[...

Related

Shield UI: Insert row based on other row

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

Use ajax success return formatted data to populate easyUI form

I am trying to use backend returned data to populate textboxes in the form. If I replace the "result" var with full raw
data(eg.{
name:'myname',
email:'mymail#gmail.com',
subject:'subject',
message:'message',
language:'en'
}
it works... So it make wonder whether the returned data is not formatted properly or what?
$.ajax({
type: "post",
cache: false,
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
url: "<%=path%>/storeRace",
data:{
type:'query', venue:'<%=race.getVenue()%>', date:'<%=race.getDate().toString()%>', race_num:'<%=race.getRaceNum()%>'
},
success:function(result){
if(result=="none"){
}
else{
alert(result);
$('#raceForm').form('clear');
$('#raceForm').form('load', result);
}
},
error:function(result){
$.messager.alert('Error',result,'error');
}
});

How to parse parameters that sent jquery table

I writing a simple Spring MVC web application that use JQuery DataTable on the client-side. DataTable using server-side processing mode. The DataTable make request with parameters(in my case):
draw:1
columns[0][data]:name
columns[0][name]:
columns[0][searchable]:true
columns[0][orderable]:true
columns[0][search][value]:
columns[0][search][regex]:false
columns[1][data]:type
columns[1][name]:
columns[1][searchable]:true
columns[1][orderable]:true
columns[1][search][value]:
columns[1][search][regex]:false
columns[2][data]:action
columns[2][name]:
columns[2][searchable]:true
columns[2][orderable]:true
columns[2][search][value]:
columns[2][search][regex]:false
order[0][column]:0
order[0][dir]:asc
start:0
length:10
search[value]:
search[regex]:false
I don't know how can i parse parameters like columns[i][data], columns[i][name], columns[i][searchable], etc. The reason is why, because I don't know how many table columns I will have. How to solve this problem?
This is my Spring controller:
#RequestMapping(value = "/getImageWrappers", method = RequestMethod.POST)
public String getImageWrappers(#RequestParam Integer draw,
#RequestParam Integer start,
#RequestParam Integer length,
#RequestParam(value = "search[value]") String searchText){
}
and DataTable configuration:
$('#imageWrapperTable').DataTable({
columns:[
{"data" : "name"},
{"data" : "type"},
{"data" : "action"}
],
"processing": true,
serverSide: true,
ajax: {
url: '/getImageWrappers.json',
type: 'POST'
}
});
I just figure it out by adding this code
$('#imageWrapperTable').DataTable({
columns:[
{"data" : "name"},
{"data" : "type"},
{"data" : "action"}
],
"processing": true,
serverSide: true,
ajax: {
url: '/getImageWrappers.json',
type: 'POST',
datatype: 'json',
data: function(d){
//add your custom param here
d.name = "zxbing";
//this will put all query strings to a json object string
return JSON.stringify(d);
}
}
});
In this way, you just need to transfer only a query string to JSON object on the server side.
In a json array I would do something like this with jquery:
function displayData(x) {
x.success(function(data) {
$.each(data.columns, function(i, paramenter) {
$.each(parameter, function(a, b) {
$('#somediv').append('column'+parameter+' -> data: '+b+' ');
});
});
}),
x.error(function(data) {
//error message
})
}//end displayData
So you can loop through your array, but you gotta play around with it, I haven't tested it but in general that is the idea. Hope it helps.

Backbone.js Collection not updating

I am new to backbone.js
I am adding rows dynamical in table(HTML), but when I print table data on save button it display empty data, my code is as follows
(function($){
Backbone.sync = function(method, model, success, error){
success();
}
var Person = Backbone.Model.extend({
defaults: {
srNo:1,
name: ''
}
});
var ListPerson = Backbone.Collection.extend({
model: Person
});
var ItemView = Backbone.View.extend({
tagName: 'tr', // name of tag to be created
events: {
'click span#spanDelete': 'remove'
},
initialize: function(){
_.bindAll(this, 'render', 'unrender', 'remove');
this.model.bind('add', this.render);
this.model.bind('remove', this.unrender);
},
render: function(){
$(this.el).append("<td>"+this.model.get('srNo')+"</td><td><input type='text' id='txt1' value="+this.model.get('name')+"></td><td><span class='delete' id='spanDelete' style='cursor:pointer; color:red; font-family:sans-serif;'>[delete]</span></td>");
return this;
},
unrender: function(){
$(this.el).remove();
},
remove: function(){
this.model.destroy();
}
});
var ListView = Backbone.View.extend({
el: $('body'), // attaches `this.el` to an existing element.
initialize: function(){
_.bindAll(this, 'render', 'addItem', 'appendItem');
this.collection = new ListPerson();
this.collection.bind('add', this.appendItem);
this.counter = 0;
this.render();
},
events: {
'click button#btnAdd': 'addItem',
'click button#btnSave': 'saveData'
},
render: function(){
var self = this;
$(this.el).append("<button id='btnAdd'>Add list item</button>");
$(this.el).append("<table border=1 id='dtl1'></table>");
$(this.el).append("<button id='btnSave'>Save</button>");
_(this.collection.models).each(function(person){
self.appendItem(person);
}, this);
},
addItem: function(){
this.counter++;
var person = new Person();
person.set({
srNo: this.counter // modify item defaults
});
this.collection.add(person);
},
appendItem: function(item){
var itemView = new ItemView({
model: item
});
$('table', this.el).append(itemView.render().el);
},
saveData: function(){
var obj=this.collection.toJSON();
var str_json = JSON.stringify(obj);
alert(str_json);
}
});
var listView = new ListView();
})(jQuery);
Name is not display in output
From what you have posted, I do not see you setting name attribute of your Person model anywhere. Within your addItem method, I see you setting the srNo attribute but nothing is done to the name as far as I can see here.
Relevant part of your code below,
var person = new Person();
person.set({
srNo: this.counter // modify item defaults
});
So you need set your name attribute like you are setting the srNo attribute
I got one tricky solution for this, i trap change event of inputtext in event block of ItemView(In above example) as events: {'click span#spanDelete': 'remove','change input#name':'textChange' }, and in textChange method i write following code textChange: function(e){
this.model.set('name',$(e.currentTarget).val());
}When i print collection value in alert i got all names inserted in inputtext.

JavaScript - how to display error message from backend system based on Spring MVC

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);
}
});

Categories