Add compiler to java pages - java

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.
}

Related

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

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.

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.

ajax success function is printing [object Object] instead of plain text. Why?

jQuery code:
function ajaxsubmit(){
$.ajax({
url: "/update",
type: "POST",
dataType: "html"
}).success(function(data) {
$('#result').html(data);
});
}
and my Java function:
public static Result ajaxupdate() {
String done = "very good";
return ok("very good").as("text/plain");
}
the alert is giving [object Object], instead of plain text "very good". why?
you want to use:
alert(JSON.stringify(data));
so you JavaScript will look like:
function ajaxsubmit(){
$.ajax({
url: "/update",
type: "POST",
}).complete(function(data) {
alert(JSON.stringify(data));
});
}
Your Java code looks like it is wrapping your string into an object before it sends it back to the client, JSON.stringify() will show you the structure of the object that is being returned and from there you can work out what property of the returned object contains your return variable (Probably something like data.data or data.return)
add dataType: "text" and change complete() with success()
function ajaxsubmit(){
$.ajax({
url: "/update",
type: "POST",
dataType: "html"
}).success(function(data) {
$('#result').html(data);
});
}
The jQuery documentation clearly answers your question. From http://api.jquery.com/jQuery.ajax/
complete(jqXHR, textStatus)
<...>
two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string
You can find more about jqXHR in documentation.
If you want to use the response string, consider opting for .success method. You may have to explicitly provide .contentType

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