Can't set JSP value in ACE Editor (JavaScript) - javascript

So I'm using this Ace Editor: https://github.com/ajaxorg/ace-builds/, JSP and Java. I'm using this to send code from ace editor to Java:
editor.session.on('change', function(e) {
document.myform3.userCode.value = editor.getSession().getValue();
});
<form action="/myPage" method="post" name="myform3">
<input type="hidden" name="userCode" value="">
<button type="submit" class="btn btn-default">Submit</button>
</form>
And I'm returing it in Java:
public ModelAndView checkUserCode(String userCode) {
ModelAndView model = new ModelAndView("kurs");
model.addObject("testunio", userCode);
return model;
}
And I'm setting it with this code:
editor.getSession().setValue("${testunio}");
And it doesn't work. I don't see anything, even my editor disapear. I see just "Submit" button and nothing more. But when I display it normally in html:
<html><body>
${testunio}
</body></html>
It works. And also when I do for example in Java:
public ModelAndView checkUserCode(String userCode) {
ModelAndView model = new ModelAndView("kurs");
userCode = "test test test test test";
model.addObject("testunio", userCode);
return model;
}
editor.getSession().setValue("${testunio}"); works ok. Somebody have maybe any idea what I'm doing wrong?
#edit
Maybe it will be better if I will give more my code:
<div id="editor"></div>
<form action="/myPage" method="post" name="myform3">
<input type="hidden" name="userCode" value="">
<button type="submit" class="btn btn-default">Submit</button>
</form>
<script>
var editor = ace.edit("editor");
editor.setTheme("ace/theme/monokai");
editor.getSession().setMode("ace/mode/sh");
editor.getSession().setValue("${testunio}");
editor.session.on('change', function(e) {
document.myform3.userCode.value = editor.getSession().getValue();
});
</script>

Related

Query params are not working in handlebars

Here is my code :
app.get("/editar-equipo?:id", (req, res) => {
const equipos = obtenerEquipos()
let equipoSeleccionado
for(let i = 0; i < equipos.length; i++){
if(equipos[i].numeroId === Number(req.query.id)){
equipoSeleccionado = equipos[i]
}
}
res.render("edit-team", {
layout: "header",
data: {
equipoSeleccionado
}
})
})
And my handlebars html is
<td>
<form id="editar-equipo" method="GET" action="/editar-equipo?id={{equipo.numeroId}}">
<button type="submit" class="btn btn-warning">Editar</button>
</form>
</td>
and the buttons are created well:
<form id="editar-equipo" method="GET" action="/editar-equipo?id=58">
<button type="submit" class="btn btn-warning">Editar</button>
</form>
But when i click the button it doesn't work. It loads
> http://localhost:3030/editar-equipo?
But if i manually write http://localhost:3030/editar-equipo?id=58 in the url bar it works correctly and the teams loads normally.
Any help? Is there any other parameter missing? Or something like that?
Im using express-handlebars and express
I have already test your case. Browser delete all query after question mark. So you need to put an hidden input inside your form element:
<form id="editar-equipo" method="GET" action="/editar-equipo">
<input type="hidden" name="id" value="58">
<button type="submit" class="btn btn-warning">Editar</button>
</form>

Spring thymeleaf send javascript dialog message to controller

A table shows a list of records, and each has a accept reject button.
When reject is clicked, a javascript prompt appears , to type in reject reason.
The reject reason + record ID needs to be sent over to the controller.
<script>
<!-- prompt a box to type in reject reason -->
function rejectPrompt() {
var txt;
var rejectMsg = prompt("Please enter your Reject message:", " ");
document.getElementById("rejectMsg").innerHTML = rejectMsg;
}
</script>
​
/*table to show record accept-reject button*/
<td>
<form action="#" data-th-action="#{/accountantApplication}" method="post">
<input type="hidden" name="id" th:value="${acc.id}" />
<input type="hidden" id="rejectMsg" name="rejectMsg" th:value="${acc.id}" />
<button type="submit" name="action" value="Accept">Accept</button>
<button type="submit" name="action" onclick="rejectPrompt()" value="Reject">Reject</button>
</form>
</td>
​
#PostMapping(value="/accountantApplication", params="action=Reject")
public ModelAndView Reject(#RequestParam String id,#RequestParam String rejectMsg) {
ModelAndView modelAndView = new ModelAndView();
System.out.println("rejectMsg:"+rejectMsg);
System.out.println("id:"+id);
accountantService.rejectAccountant(id);
modelAndView.setViewName("RejectAccountant");
return modelAndView;
}
Issue is , the reject message does not reach the controller . Only the correct ID is sent over. How do i send id and message across?
Or if there is a better way to implement it , do advice. Thanks so much!
Setting document.getElementById("rejectMsg").innerHTML = rejectMsg is like the HTML:
<input type="hidden" id="rejectMsg" name="rejectMsg" value="someAccId">Some rejectMsg</input>
In order to have "Some rejectMsg" sent to the server you'll have to set the value of the <input>:
document.getElementById("rejectMsg").value = rejectMsg
Note that this will override the effect th:value="${acc.id}" in the <input id="rejectMsg">

Upload a folder to server(mvc spring)

I try to upload the content of a folder to the server. But I can't do it, so I made an example where you have to select every single file.
Controller:
#Controller
public class FileUploadController {
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#ModelAttribute("uploadForm") FileUploadForm uploadForm,Model map) {}
}
and the jsp-file
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
<title> - Upload</title>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//add more file components if Add is clicked
$('#addFile').click(function() {
var fileIndex = $('#fileTable tr').children().length;
$('#fileTable').append(
'<tr><td>'+
' <input type="file" name="files['+ fileIndex +']" />'+
'</td></tr>');
});
});
</script>
</head>
<body>
<div align="center" class="jumbotron">
<h1>dd</h1>
<form:form method="post" action="save.html"
modelAttribute="uploadForm" enctype="multipart/form-data">
<p>Dateien auswählen zum uploaden</p>
<input class="btn btn-success" id="addFile" type="button" value="Datei hinzufügen" />
<table align="center" class="table table-striped" id="fileTable">
<tr>
<td><input name="files[0]" type="file" /></td>
</tr>
<tr>
<td><input name="files[1]" type="file" /></td>
</tr>
</table>
<br/><input class="btn btn-primary" type="submit" value="Upload" />
</form:form>
</div>
</body>
</html>
That works great. I found some examples where I can select multiple files at once(just adding multiple), but couldnt upload them. I got some trouble to get this working. I'm surprised its so "difficult" to do a so "easy" thing. I dont know if I have to change my Controller file or only my jsp file. I hope someone can exaplain me how this works. I'm new so please talk to me like to a little stupid kid.
Greets
Sam
Single file input on form:
If you need just simply to select multiple files and upload them, you almost did it. You just have declare field in you form model as List:
public class FileUploadForm {
private List<MultipartFile> files;
public List<MultipartFile> getFiles() {
return files;
}
public void setFiles(List<MultipartFile> files) {
this.files = files;
}
}
Now in you controller you can access this list:
#Controller
public class FileUploadController {
#RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(#ModelAttribute("uploadForm") FileUploadForm uploadForm, Model map) {
for(MultipartFile file : uploadForm.getFiles()){
try {
file.transferTo(new File(targetPath+file.getOriginalFilename()));
} catch (IOException e) {
throw new RuntimeException();
}
}
}
}
And of cause in your form you have to specify multiple attribute of file input:
<form:form method="post" action="/save" modelAttribute="uploadForm" enctype="multipart/form-data">
<input name="files" type="file" multiple=""/>
<button type="submit">Upload</button>
</form:form>
Note, that in this way you should not use array syntax, like file[], in input name.
Multiple file inputs on form.
Let's consider if you would like to load file, as it shown in your code snippets, when you add new file input for every file. First of all, remove field List<MultipartFile> files from model of form. We will get it by another way. Now the controller method will be as follows:
#RequestMapping(value = "/upload", method = RequestMethod.POST)
public String upload(#ModelAttribute("uploadForm")FileUploadModel uploadForm,
#RequestParam("files[]") List<MultipartFile> fileList, ModelMap model) throws IOException {
for(MultipartFile file : fileList){
try {
file.transferTo(new File(targetPath+file.getOriginalFilename()));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
As you see, now we declared model of form and list of files separately. Also note, that list has #RequestParam with name of form's field. And this name specified with array syntax - files[].
Now, how form should look like:
<form:form method="post" action="/save" modelAttribute="uploadForm" enctype="multipart/form-data">
<input name="files[]" type="file" multiple=""/>
<input name="files[]" type="file" multiple=""/>
<input name="files[]" type="file" multiple=""/>
<button type="submit">Upload</button>
</form:form>
In this example I added multiple file inputs statically, but you can do it dynamically with javascript, indeed. Pay attention, that you should not specify index of array item in name of input. Just files[], but not files[0] or file[1].
By the way, you can receive list of files as parameter of method in case with single file input, as well. Just remove list of files from model and declare it as parameter of controller's method.

window.close not working in firefox/chrome?

I checked on duplicate threads but did not work. I just need to close browser after I click close. but it is firing Controller [HttpPost] method instead of close the browser.
browser is closing if open the same url from another window.
view
#using (Html.BeginForm())
{
#Html.AntiForgeryToken()
#Html.ValidationSummary(true)
.....
....
<td align="right">
<input type="submit" name="btnSave" value="Save" id="btnSave" />
<input type="submit" name="btnCancel" value="Cancel" id="btnCancel" />
</td>
}
JS
<script type="text/javascript">
$(document).ready(function () {
......
$("#btnCancel").click(function (event) { window.close(); });
});
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Index(List<CustomerCommPreferences> lstcustCommPref, bool chkSolicitation)
{
}
Console warning show Scripts may not close windows that were not opened by script.
JavaScript can only close the windows it has opened. For example:
var yourWindow = window.open('http://google.com');
You could then use yourWindow.close();
The reason why you are hitting the controller is because you have two buttons which are inside a HTML form. When these buttons are clicked the form is submitted back to the server.

redirecting to controller class from popup window

I am using Spring controller, jsp as view with javascript and html as front end view. I have popup window, When I submit the button, it should redirect to controller class.
JavaScript code with html:
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
loginQB = function(){
var win = window.open('about:blank', 'popup', 'width=640,height=580,resizeable,scrollbars');
<!-- win.document.write('<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>');
win.document.write('<form:form id="qblogin" method="POST" action="/asi/mappings">');--!>
win.document.write('<br>Sign in with Intuit Account or CreateOne');
win.document.write('<br><input type="text" name="userName">');
win.document.write('<br><input type="password" name="password">');
win.document.write('<br><input type="submit" value="Submit">');
<!--win.document.write('</form>');-->
}
</script>
</head>
<body>
<form:form id="qblogin" method="POST" onsubmit="loginQB(); return false;">
<select name="quickbooks" id="qb" >
<option value="qb-1">Books Desktop</option>
</select>
<input type="submit" value="Submit">
</form:form>
</body>
</html>
Spring controller class:
#Controller
#SessionAttributes("mappingSession")
public class MappingsController {
#RequestMapping(value="/mappings", method = RequestMethod.POST)
public String dataMappings(Model model) throws Exception {
DefaultHttpClient httpClient = new DefaultHttpClient();
First of all, why don't you use Bootstrap Modal for your pop up.
http://getbootstrap.com/javascript/#modals
Secondly, when you submit, you can get the information from your form, serialize it and then pass it to the controller.
http://api.jquery.com/serialize/
I strongly recommend you to change the implementation of your popup.

Categories