How to submit an option and text input form with AngularJS - java

I'm new to setting up forms and I need to be able to submit two separate values to a Java backend on a different server. One of the values is a predefined one which should come from a select and the other from a text input field.
On the front end the user will select an option from the dropdown and input text in the textbox and then hit the submit button to send it off to the backend.
I am having trouble with the setup of this and was looking for some pointers. I have some code which paints an idea of what I've been trying to do.
<div class="col-xs-3">
<label>Search Criteria:</label>
<select class="form-control" tabindex="20">
<option value="0" disabled selected>Select your criteria</option>
<option value="1">Project Reference</option>
<option value="2">Service Owner</option>
<option value="3">Service Name</option>
<option value="4">Service Abbreviation</option>
<option value="5">Domain Abbreviation</option>
<option value="6">Domain Name</option>
</select>
</div>
<div class="col-xs-3">
<label>Search Terms:</label>
<form name="options" class="form-inline">
<div class="form-group">
<input type="text" tabindex="21" class="form-control" placeholder="Search for..." ng-model="mytext" required>
<button type="submit" tabindex="22" style="color: #ffffff;
background-color: #007381;" class="btn btn-default" ng-disabled="options.$invalid"><b>Go </b><b></b><span class="glyphicon glyphicon-chevron-right"></span></button>
</div>
</form>
</div>

You would need to make multiple $http service calls. You could do it inside a controller like this:
.controller('YourController', function($http) {
var controller = this;
this.saveCriteria = function(criteria) {
$http({method: 'POST', url: '/backend_url_handle_criteria', data: criteria})
.success(function(data) {
//do something with data
}
};
this.saveTerm = function(term) {
$http({method: 'POST', url: '/backend_url_handle_term', data: term})
.success(function(data) {
//do something with data
}
};
this.send = function(formdata){
this.saveCriteria(formdata.criteria);
this.saveTerm(formdata.term);
};
});
In your html you declare your form something like this
<form name="yourForm" ng-controller="YourController as yourCtrl" ng-submit="yourCtrl.send(formdata)">

Related

How to trigger Spring boot form submission by clicking on an li element?

I have a side bar for my user profile page which has two items for 1) Updating the information and 2) showing the reviews that the user has already written.
The first item works perfectly (as it includes a form and has a submit button). But for the second one, I have no idea. The goal is that when I click on My Reviews, a method from the controller class is called, the reviews of the user are extracted from the database and the results are shown on the right side of the page.
As I don't have a submit button or a form for the second item, I don't know how I can implement it.
Here is my code:
<div class="module-inner">
<div class="side-bar">
<nav class="side-menu">
<div class="col-xs-3">
<ul class="nav nav-pills nav-stacked">
<li class="active"><a data-toggle="pill" href="#profile">Profile</li>
<li class="active"><a data-toggle="pill" href="#review">My
Reviews</a></li>
</ul>
</div>
</nav>
</div>
<div class="content-panel">
<div class="col-xs-9">
<div class="tab-content">
<div id="profile" class="tab-pane fade">
<form class="form-horizontal" th:action="#{/edit_profile}"> <fieldset class="fieldset">
<h3 class="fieldset-title">Personal Info</h3>
<div class="form-group">
<label class="col-md-2 col-sm-3 col-xs-12 control-label">User
Name</label>
<div class="col-md-10 col-sm-9 col-xs-12">
<input type="text" class="form-control"
th:disabled="${currentUser.email}"
th:value="${currentUser.email}">
</div>
</div>
<div class="form-group">
<label class="col-md-2 col-sm-3 col-xs-12 control-label">First
Name</label>
<div class="col-md-10 col-sm-9 col-xs-12">
<input name="firstname" type="text" class="form-control"
th:value="${currentUser.firstname}">
</div>
</div>
<div class="form-group">
<label class="col-md-2 col-sm-3 col-xs-12 control-label">Last
Name</label>
<div class="col-md-10 col-sm-9 col-xs-12">
<input name="lastname" type="text" class="form-control"
th:value="${currentUser.lastname}">
</div>
</div>
</fieldset>
<hr>
<div class="form-group">
<div
class="col-md-10 col-sm-9 col-xs-12 col-md-push-2 col-sm-push-3 col-xs-push-0">
<input class="btn btn-primary" type="submit"
value="Update Profile">
</div>
</div>
</form>
</div>
<div id="review" class="tab-pane fade">
<h3>Menu 2</h3>
<p>You have no reviews yet.</p>
</div>
</div>
</div>
</div>
</div>
Here is my controller:
#RequestMapping(value = "/findUserReviews", method = RequestMethod.GET)
public ModelAndView findUserReviews() {
ModelAndView modelAndView = new ModelAndView();
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
User user = userService.findUserByEmail(auth.getName());
..
modelAndView.addObject("reviews", reviewRepository.findUserRevies());
modelAndView.setViewName("profile");
return modelAndView;
}
I use the following technologies: Spring boot, Hibernate and Thymeleaf.
Any help would be appreciated.
Final update: The provided code in the accepted answer works, provided that I don't return a ModelAndView but a List<Review>.
With Ajax calls you can call the controller endpoints using javascript. One ajax call looks like this :
function getReviews() {
$.ajax({
type: "GET",
url: "/users/findUserReviews", //example
dataType: "JSON",
success: function (data) {
//do something with this JSON
fillReviews(data);
}
});
}
Now you can use this function as an on-click event for your button. And the fillReviews() is a function that gets the element with id="review" from the jsp page and create the list tree with the fetched data.
function fillReviews(data) {
var reviewDiv= document.getElementById('review');
var reviewList = document.createElement('ul');
for ( var i=0 ; i < data.length; i++)
{
var reviewListItem = createListItem(data[i]);
reviewList.appendChild(reviewListItem);
}
reviewDiv.appendChild(reviewList);
}
And createListItem(data[i]) could look like this:
function createListItem(data)
{
var listItem = document.createElement('li');
listItem.innerHTML = data["reviewName"]; // for example ..
return listItem;
}
And now all you have to do is to call getReviews() here :
<button onclick="getReviews()"/>
EDIT : The "data" from the ajax call is a JSON. So the "/users/findUserReviews" should return a List<Review> for example. And there is no need to change your original "/findUserReviews" endpoint. This was only an example, you can create a new endpoint in your controller which returns a list.

How to submit form without reload page

I have form action with textarea and submit button
<form method="post" action="/analyze">
<div class="form-group">
<label for="text">Input text:</label>
<textarea class="w-100" name="text" id="text" cols="30" rows="10"></textarea>
</div>
<div class="form-group d-flex justify-content-center">
<input type="submit" class="btn__submit btn btn-dark my-auto" value="Обработать">
</div>
</form>
<div class="row">
<div class="col">
<p th:text="#{nertext}"></p>
</div>
</div>
When I click submit button, i want to get processed text from server in Spring Boot and paste in tag p in div col.
Java Controller
#RequestMapping(value = "/analyze", method = RequestMethod.POST)
public String analyzeText(#RequestParam String text, Model model) {
System.out.print(classifier.classifyToString(text, "tsv", false));
String asd = classifier.classifyToString(text, "tsv", false);
model.addAttribute("nertext", asd);
return "/analyze";
}
How can i do submit without reload page
Use the Fetch API (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch) and the onsubmit event listener (https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onsubmit) to submit the form with JavaScript without reloading the page:
let form = document.getElementById("the-form");
form.onsubmit = function (e) {
e.preventDefault();
fetch(form.action, {
method: "post",
body: new FormData(form)
}).then(response => {
// do something with the response...
});
}
The e.preventDefault() makes sure that the page is not reloaded when you click the submit button. This assumes your form has the id the-form, like this:
<form id="the-form" method="post" action="/analyze"> ... </form>

java.lang.IllegalStateException: Neither BindingResult nor plain target object in ajax call

java.lang.IllegalStateException: Neither BindingResult nor plain target object in ajax call
I am using Thymeleaf and Spring MVC and I am having some problems with a dynamic form.
I have a form with a selector, and when this changed, I do an Ajax call, which should show another selector and a field.
I have these objects:
public class SaleMini{
private int businessId;
private int sellerId;
private int productId;
private int amount;
private int row;
private String date;
private List<SaleItem> item;
//getters and setters
}
public class SaleItem{
private int productId;
private int amount;
private boolean gift;
private List<Integer> components;
private List<Composition> compositionList;
//getters and setters
}
My html code is:
<form id="sales" action="#" th:action="#{/sales/add}" method="post">
<div class="row">
<div class="form-group col-md-6">
<label class="label-control" th:text="#{label.equipment}"></label>
<select th:field="${sales.businessId}" class="form-control" onchange="submitData()"> <!--- Equipment List --->
<option th:each="e : ${equipmentList}" th:value="${e.id}" th:text="${e.name}"></option>
</select>
</div>
<div class="form-group col-md-6">
<label class="label-control" th:text="#{label.seller}"></label>
<select th:field="${sales.sellerId}" class="form-control">
<option th:each="s : ${sellerList}" th:value="${s.id}" th:text="${s.name + ' ' + s.surname}"></option>
</select>
</div>
</div>
<div id="product-panel" class="row" >
<div th:fragment="resultsList">
<div th:each="i,rowStat : ${itemList}">
<p th:text="${i.productId}"></p>
<select class="form-control products_select" th:field="${i.productId}" th:onchange="${'javascript:callComposed(' + rowStat.index + ')'}" >
<option value="0" >Select Product</option>
<option th:each="p : ${productList}" th:value="${p.id}" th:text="${p.name}" th:attr="data-compound=${p.compound},data-generic=${p.genericId}"></option>
</select>
</div>
<a class="btn btn-action" id="btn-add" onclick="submitData()" style="margin-top: 25px !important;"><span class="fa fa-plus fa-btn"></span></a> <!--I should add as many product as I wanted-->
</div>
</div>
<div class="row">
<div class="form-btn">
<input type="submit" th:value="#{label.save.sale}" class="btn btn-custom"/>
</div>
</div>
</form>
When the Equipment List is change, I do an ajax call
function submitData(){
$.ajax({
'url': 'sales/addRow',
'type': 'POST',
'data': $('#sales').serialize(),
'success': function(result){
$("#product-panel" ).html( result );
},
});
}
The function I call on the controller is:
#RequestMapping(value = "/addRow", method = RequestMethod.POST)
public String addRow(#Valid SaleMini sale, BindingResult bindingResult,ModelMap model) {
List<SaleItem> siList = new ArrayList<SaleItem>();
if(sale!=null && sale.getBusinessId()!=0)
{
SaleItem si = new SaleItem();
si.setAmount(1);
siList.add(si);
}
model.addAttribute("itemList", siList);
return folder+"/add :: resultsList";
}
The problem is when I call to submitData().
I can do the call to the controller well (submitData() and then addRow), and it works, but when I get the data I have and error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'i' available as request attribute
I get data after the call, but I can't access to the data with th:field
In the html part this works (th:text):
<p th:text="${i.productId}"></p>
But this not (th:field), and I don't know why:
<select class="form-control products_select" th:field="${i.productId}" th:onchange="${'javascript:callComposed(' + rowStat.index + ')'}" >
</select>
Thank you in advance
Hi I think you are missing a couple of details in your form. With this th:object="sale" you say what will be the modelAttribute of your form, and to make reference to any attribute of that object just use *{attribute.path}
<form id="sales" action="#" th:action="#{/sales/add}" method="post" th:object="sale">
And to make reference to attributes of your sale object use:
<select th:field="*{businessId}" class="form-control" onchange="submitData()"> <!--- Equipment List --->
<option th:each="e : ${equipmentList}" th:value="${e.id}" th:text="${e.name}"></option>
</select>

how to get data from label or span and transfer it to a div, an other span or a label

this is my form with div :
<form action="" method="post">
<label name="meal" value="meal">
Soupe
</label>
<table border="0">
<tr>
<td><span id="prix" name="price" >price</span></td>
<td><input type="number" id="nbr" name="quantity" min="1" max="5"value="1">
<label>Number of persons</label>
</td>
<td><input type="button" id="somebutton" value="order"
onclick="getdata('somebutton','empty-basket-wrapper')" />
</td>
</tr>
<tr>
<td colspan="3">description of the meal ....</td>
</tr>
</table>
</form>
<div class="order">
<div class="panier">
<span class="Ib"></span>
<span class="oh">my shopping cart</span>
</div>
<div id="empty-basket-wrapper">
empty
</div>
</div>
I would like when I click on the button, the datas to be transferred from the the label or span like soupe and price and be displayed in the div id ="empty-basket-wrapper".
I guess my problem is how to get data from label or span and transfer it to div or an other span or label
this is my AJAX :
var _xhr;
var _target;
function getdata(sourceId,targetId){
_xhr= new XMLHttpRequest();
_xhr.onreadystatechange=callback;
_xhr.open("POST", url, true);
_xhr.send();
var px=document.getElementById("prix").name;
function callback() {
_target = document.getElementById(targetId);
_target.innerHTML=px//_xhr.responseText;
}
}
Thanks for your help !
You should consider using jQuery, then it would be like:
$(document).ready(function() {
$("#somebutton").click(function(e) {
e.preventDefault();
var form = $(e.target).closest("form");
var target = $(form).attr("action");
$.post(target, form.serialize(), function(result) {
// your POST Target could give you HTML for the cart contents
$("#empty-basket-wrapper").html(result);
// your AJAX endpoint could also give you a JSON, then you could use mustache to render.
});
});
});
If you just want to popup the values in the cart and not POST back to your server you don't need no AJAX ... not sure if you mean that. If so, it would be simpler:
$(document).ready(function() {
$("#somebutton").click(function(e) {
e.preventDefault();
var form = $(e.target).closest("form");
// for sure you should investigate something more sophisticated, see mustache
$("#empty-basket-wrapper").html(form.serialize());
});
});

How to save event data into an xml file from dhtmlxscheduler

I need to save event data to an xml file.I need to do this using a java code.i am using html5.
So from the javascript i need to call this java code and need to save event text,date and other details to an xml file.And whenever the data is needed it should be displayed back in the dhtmlx scheduler.How can i do this?
function init() {
scheduler.config.xml_date="%Y-%m-%d %H:%i";
scheduler.config.prevent_cache = true;
scheduler.init('scheduler_here',new Date(2010,0,20),"month");
scheduler.load("data/data.xml");
}
function show() {
alert(scheduler.toXML());
}
function save() {
var form = document.forms[0];
form.action = "./data/xml_writer.php";
form.elements.data.value = scheduler.toXML();
form.submit();
}
function download() {
var form = document.forms[0];
form.action = "./data/xml_download.php";
form.elements.data.value = scheduler.toXML();
form.submit();
}
xml_writer.php
<?php
file_put_contents("./data.xml",$_POST["data"]);
header("Location:./dummy.html");
?>
<?php
if(empty($_POST['data'])) {
echo "why";
exit;
}
xml_download
$filename = "data.xml";
header("Cache-Control: ");
header("Content-type: text/plain");
header('Content-Disposition: attachment; filename="'.$filename.'"');
echo $_POST['data'];
?>
html code
<form action="./php/xml_writer.php" method="post" target="hidden_frame" accept-charset="utf-8">
<input type="hidden" name="data" value="" id="data">
</form>
<iframe src='about:blank' frameborder="0" style="width:0px; height:0px;" id="hidden_frame" name="hidden_frame"></iframe>
<div id="scheduler_here" class="dhx_cal_container" style='width:100%; height:100%;'>
<div class="dhx_cal_navline">
<div class="dhx_cal_prev_button"> </div>
<div class="dhx_cal_next_button"> </div>
<div class="dhx_cal_today_button"></div>
<div class="dhx_cal_date"></div>
<input type="button" name="download" value="Download" onclick="download()" style="right:500px;" />
<input type="button" name="show" value="Show" onclick="show()" style="right:400px;" />
<input type="button" name="save" value="Save" onclick="save()" style="right:300px;" />
<div class="dhx_cal_tab" name="day_tab" style="right:204px;"></div>
<div class="dhx_cal_tab" name="week_tab" style="right:140px;"></div>
<div class="dhx_cal_tab" name="month_tab" style="right:76px;"></div>
</div>
<div class="dhx_cal_header">
</div>
<div class="dhx_cal_data">
</div>
This much code i have.But code for saving to an xml file is in php.I need java code instead of php.

Categories

Resources