jQuery Select2 and Struts 2 JSON plugin - java

I'm trying to populate with Struts2 JSON and Select2 a select. Server is returning a JSON like this:
{"orphanets":[{"idDiagOrphanet":11509,"nomDiagOrphanet":"FACOMATOSIS CESIOFLAMMEA"},{"idDiagOrphanet":21782,"nomDiagOrphanet":"AUTOINFLAMMATION"}]}
How can I format/parse the result to make it work? I know it expects id and text fields, but cant get it working:
$("#selCodOrphanet").select2({
quietMillis: 300,
placeholder: "Buscar diag. Orphanet...",
minimumInputLength: 4,
ajax: {
url: '../json/getOrphanets',
dataType: 'json',
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data.orphanets };
},
id: function(item) {
return item.idDiagOrphanet;
},
formatResult: function(item) {
return "<div class='select2-user-result'>" + item.nomDiagOrphanet + "</div>";
}
}
});

I tried a bit searching but didn't found id: function(item) {
Anyways, here's a quick-fix
Consider the response as a normal string
replace idDiagOrphanet with id and nomDiagOrphanet with text and then return this string instead of return { results: data.orphanets };
Here's another way :
Modifying a JSON object by creating a New Field using existing Elements
var ornts= data.orphanets;
var new_obj ;
for(var i=0; i<data.orphanets.length; i++){
var person = persons[i];
new_obj.push({
id: ornts.idDiagOrphanet,
text: ornts.nomDiagOrphanet,
});
}
return new_obj;

Try
$("#selCodOrphanet").select2({
placeholder: "Buscar diag. Orphanet...",
minimumInputLength: 4,
ajax: {
url: '<s:url namespace="/json" action="getOrphanets"/>',
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data.orphanets };
},
id: function(item) {
return item.idDiagOrphanet;
},
formatResult: function(item) {
return "<div class='select2-user-result'>" + item.nomDiagOrphanet + "</div>";
}
escapeMarkup: function (m) { return m; }
}
});
Added the qualified URL mapping to getOrphanets action with namespace /json. Corresponding configuration should be made. Don't escape markup since you are displaying HTML in results.

Related

React setState not working, getting error

I get the following error when trying to use setState:
Uncaught TypeError: Cannot read property 'setState' of null
I don't know where I am going wrong, could someone point me in the right direction please.
Here's my code:
export default React.createClass({
getInitialState: function () {
return {
name: '',
address: '',
phone: '',
email: '',
}
},
componentWillMount(){
this.getUserDetails();
},
getUserDetails: function(){
var personID = 'ABC123';
if(personID.length > 0){
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', function(snap) {
this.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
}
},
render() {
return ( ... );
}
});
Like people have been saying above, if you just edit this to an arrow function it will change the context of this from Firebase to the outer scope - which is the component.
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', (snap) => {
this.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
This is happening because the context of this is not the component anymore. You need this of the component. Check how I grab this of the component.
export default React.createClass({
getInitialState: function () {
return {
name: '',
address: '',
phone: '',
email: '',
}
},
componentWillMount(){
this.getUserDetails();
},
getUserDetails: function(){
var that = this
var personID = 'ABC123';
if(personID.length > 0){
new Firebase('https://xxxxxxxxxx.firebaseio.com/users/' + personID).on('value', function(snap) {
that.setState({
name: snap.val().Name + " " +snap.val().Surname
});
});
}
},
render() {
return ( ... );
}
});

java object to json object to javascript object

I am trying to implement the jQuery autocomplete custom data and display. Right now I'm using just the regular autocomplete. My problem is converting the json array of json objects to an array of javascript objects. Could someone please point me in the right direction. Here is what I currently have for the standard autocomplete.
javascript:
$('input[type=radio][name=transaction]').change(function(){
console.log($('input[type=radio][name=transaction]:checked').val());
$.ajax({
type: "post",
async: false,
url: "/autocomplete",
contenttype: "application/json; charset=utf-8",
datatype: "json",
data: "transaction="+$('input[type=radio][name=transaction]:checked').val(),
success: function (data)
{
if($('input[type=radio][name=transaction]:checked').val() == "sell")
{
theSymbols = JSON.parse(data);
}
else
{
theSymbols = data;
}
},
error: function (bad)
{
alert("Autocomplete failed.");
}
});
if($('input[type=radio][name=transaction]:checked').val() == "sell")
{
$("#symbol").autocomplete(
{
minLength: 0,
source: theSymbols,
focus: function(event, ui) {
$("#symbol").val(ui.item.value);
return false;
},
select: function(event, ui)
{
$("#symbol").val( ui.item.value);
$("#sharesOwn").html( ui.item.shares);
$("#sharesText").show();
return false;
}
})
.autocomplete("instance")._renderItem = function(ul, item)
{
return $("<li>")
.append("<a>" + item.label + "<br><span class='acFormat'>" + item.desc + "</span></a>")
.appendTo(ul);
};
}
else
{
$("#symbol").autocomplete({source: theSymbols});
}
java:
ArrayList<String> symbols = new ArrayList<String>();
ArrayList<Position> positionList = new ArrayList<Position>();
positionList = PositionDB.getPositions(user.getPortfolioID(), "O");
for (Position p : positionList)
{
String data = "";
data = "{";
data += "value: " + p.getSymbol();
data += ", label: " + p.getSymbol();
data += ", desc: " + p.getCompName();
data += ", shares: " + p.getShares();
data += "}";
symbols.add(data);
}
Gson gson = new Gson();
JsonElement syms = gson.toJsonTree(symbols, new TypeToken<List<String>>() {}.getType());
response.setContentType("application/json; charset=UTF-8");
JsonArray jArray = syms.getAsJsonArray();
PrintWriter out = response.getWriter();
System.out.println(jArray);
out.print(jArray);
out.flush();
Stock object has symbol, company name and price.
I'm having problems creating the JSON array or objects to pass to my javascript. Right now it outputs as if it were a js array of objects but keys are showing up in the textbox, along with the values so the autocomplete must be seeing it as a string, which means that I can't build it as a string in java so I need a different way. Ideas?
Thank you.

Making an AJAX POST on websocket message is causing timeout exceptions

So I have a program that basically allows two users two chat back and forth and do other things via websocket with javascript and java server endpoints. When one of the users presses a button I have a listener that fires off a message to the other user which invokes a function. During this function I want to be able to call an AJAX POST with JQuery to update my database but this is causing a java.util.concurrent.TimeoutException. Any idea why this occurs? I imagine it has something to do with the fact that the websocket connection doesn't stay open long enough for the ajax call to go through.
So I've done the research and I've seen that websocket and AJAX are not exactly something that should be mixed (I think). However I can't seem to figure out an alternative even to update my database. There is a lot of code for this so I will try and only post the important parts.
Here is the part of the code for when the button is pressed (it is an agree button so both users must have pressed it hence the '**' and '--' characters).
fAgree.addEventListener("click", function() {
// selects this button
if (aStr == "**" && (yStr == "**" || oStr == "**")) {
if (fStr == "--") {
fStr = "*-";
//redirect to another page
} else if (fStr == "-*") {
fStr = "**";
if(secondTransaction == false) {
var firstCoordUpload = document.getElementById("yourPos").innerHTML;
var secondCoordUpload = document.getElementById("othersPos").innerHTML;
var firstLatUpload = parseFloat(firstCoordUpload.split(",")[0]);
var firstLonUpload = parseFloat(firstCoordUpload.split(",")[1]);
$.ajax({
url: "../../309/T11/setSaleData/" + getURLParameter("saleID") + "/" + firstLatUpload + "/" + firstLonUpload + "/" + firstCoordUpload + "/" + secondCoordUpload + "/" + secondSeller,
type: "POST",
headers: {
"Authorization" : getCredentials(),
},
success: function (result) {
window.location.href = '../../frontEnd/profilePage/index.html?username='+ getUsername();
console.log(result);
},
error: function (dc, status, err) {
console.log(err);
console.log(status);
}
});
}
}
agreeBut.socket.send("a,f");
htmlChange(fStr, fStar);
}
});
Here is the part of the code that is called at the end of the code above (the agreeBut.socket.send()).
agreeBut.socket.onmessage = function(message) {
// check [0]: a for agree buttons,
// m for map,
// l of location buttons,
// t for trade
var mess = message.data.split(",");
if (mess[0] == "a") {
// second a shows the agree button was pressed, changes aStr
// accordingly and displays
if (mess[1] == "a") {
if (aStr == "--") {
aStr = "-*";
} else if (aStr == "*-") {
aStr = "**";
}
htmlChange(aStr, aStar);
// shows the final agree button has been pressed, changes fStr
// accordingly and displays
} else if (mess[1] == "f") {
if (fStr == "--") {
fStr = "-*";
//redirect
} else if (fStr == "*-") {
fStr = "**";
alert("on this");
if(secondTransaction == true) {
alert("doing it");
var firstCoordUpload = document.getElementById("yourPos").innerHTML;
var secondCoordUpload = document.getElementById("othersPos").innerHTML;
var firstLatUpload = parseFloat(firstCoordUpload.split(",")[0]);
var firstLonUpload = parseFloat(firstCoordUpload.split(",")[1]);
$.ajax({
url: "../../309/T11/setSaleData/" + getURLParameter("saleID") + "/" + firstLatUpload + "/" + firstLonUpload + "/" + firstCoordUpload + "/" + secondCoordUpload + "/" + secondSeller,
type: "POST",
headers: {
"Authorization" : getCredentials(),
},
success: function (result) {
console.log(result);
alert("Got it");
window.location.href = '../../frontEnd/profilePage/index.html?username='+ getUsername();
},
error: function (dc, status, err) {
console.log(err);
console.log(status);
}
});
}
//window.location.href = '../../frontEnd/profilePage/index.html?username='+ getUsername();
}
htmlChange(fStr, fStar);
}
}
};
It turns out I was getting this problem because of the timeout that was set on my java ServerEndpoint. In the class I used the setMaxIdleTimeout(0) function on the session variable to have no idle timeout. This seemed to solve my problem (however I feel like this is really just a workaround for poor websocket and ajax implementation on my end).

How to Edit and delete jQuery data table each rows

How to edit and delete jQuery data table each rows.I am using jQuery dataTables.js Library.
Is there any function to do that..i am new for the dataTables.js
use code like below
$(document).ready(function() {
/* Init DataTables */
var oTable = $('#example').dataTable();
/* Apply the jEditable handlers to the table */
$('td', oTable.fnGetNodes()).editable( '../examples_support/editable_ajax.php', {
"callback": function( sValue, y ) {
var aPos = oTable.fnGetPosition( this );
oTable.fnUpdate( sValue, aPos[0], aPos[1] );
},
"submitdata": function ( value, settings ) {
return {
"row_id": this.parentNode.getAttribute('id'),
"column": oTable.fnGetPosition( this )[2]
};
},
"height": "14px"
} );
} );
reference editable jquery datatable

How to access elements of JSON array in javascript?

I'm currently creating an ArrayList in Java, then running the .toJson function from Google-gson on it:
public String statusesToJson(ArrayList<String> statuses){
Gson gson = new Gson();
return gson.toJson(statuses);
}
Which results in the JSON:
[ "u", "u", "u", "u" ]
Then in JSP I'm passing it into JavaScript:
<script language="JavaScript" type="text/javascript">CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', '<%=model.arrayListToJson(model.getStatuses()) %>');</script>
Then in the JavaScript I'm parsing it to a JSON array:
CheckStatus.statuses = JSON.parse(statuses);
alert(CheckStatus.statuses);
This then results in the following output:
u, u, u, u
The problem is that the following doesn't work and causes my page to not load:
alert(CheckStatus.statuses[0]);
What's wrong with this?
EDIT:
Loaded Function:
loaded : function(guid, context, statuses) {
CheckStatus.guid = guid;
CheckStatus.context = context;
CheckStatus.statuses = JSON.parse(statuses);
alert(CheckStatus.statuses[0]);
if(CheckStatus.init == null){
submitForm('checkStatusForm', CheckStatus.guid);
CheckStatus.init = true;
}
setupForm('checkStatusForm', function(){CheckStatus.validStatus();});
//CheckStatus.setImages();
applyCSS3('Check_Status');
}
Valid Status Function:
validStatus : function(){
CheckStatus.params = $('#checkStatusForm').serializeObject();
if(document.getElementById('regionID').value != "" && document.getElementById('regionAction').value != ""){
submitForm('checkStatusForm', CheckStatus.guid);
}else{
error("Cannot Commit", "You must select an action before attempting to commit.");
}
},
Setup Form Function:
/**
* Sets up the form to submit when the user presses enter inside an input
* element. Also calls the callback when the form is submitted, does not
* actually submit the form.
*
* #param id The id of the form.
* #param callback The callback to call.
* #return Nothing.
*/
function setupForm(id, callback) {
$('#' + id + ' input').keydown(function(e) {
if (e.keyCode === 13) {
$(this).parents('form').submit();
e.preventDefault();
}
});
$('#' + id).submit(function(e) {
e.preventDefault();
callback();
});
}
Submit Form Function:
/**
* Serializes and submits a form.
*
* #param id
* The id of the form to submit.
* #param guid
* The guid of the page the form is on to pass to the server.
* #return nothing.
*/
function submitForm(id, guid) {
var subTabId = $('#' + id).closest('#tabs > div > div').attr(
'id'), tabId = $('#' + id).closest('#tabs > div')
.attr('id'), data = $('#' + id).serializeArray();
data.push( {
name : "framework-guid",
value : guid
});
$.ajax( {
type : 'POST',
cache : 'false',
url : '/pasdash-web/' + tr("_", "", tabId.toLowerCase()) + '/' + tr("_", "", subTabId)
+ '.jsp',
data : data,
success : function(html) {
$('#' + subTabId).html(html);
resourceChanged(tabId, subTabId,
$('#' + id + ' input[name="framework_command"]')[0].value,
guid);
},
error : function(jqXHR, textStatus, errorThrown) {
error('Ajax Error', textStatus);
}
});
return false;
}
You don't need to wrap your JSON with strings, that will just force you to have to reparse it. I would try removing those quotes and not calling JSON.parse
loaded : function(guid, context, statuses) {
CheckStatus.guid = guid;
CheckStatus.context = context;
// Here's the change
CheckStatus.statuses = statuses;
alert(CheckStatus.statuses[0]);
And change your HTML to be
<script type="text/javascript">
CheckStatus.loaded('<%=model.getPageId() %>',
'<%=request.getContextPath() %>',
// the following line should output something like
// ["a", "b"]
// which is perfectly valid JavaScript
<%=model.arrayListToJson(model.getStatuses()) %>);
</script>
You should be able to write:
CheckStatus.loaded('<%=model.getPageId() %>', '<%=request.getContextPath() %>', <%=model.arrayListToJson(model.getStatuses()) %>);
without the quotes around the last argument. Then, that "loaded()" function will get the object directly and there'll be no need to call "JSON.parse()".
Check the type of the result of JSON.parse (). Seems to me that it is a string and not an array. Maybe a pair of quotes somewhere that should not be there?

Categories

Resources