Form ajax data on jsp example - javascript

I would like to form data parameter correctly inside ajax call.
<script type="text/javascript">
$(document).ready(function() {
$('#call').click(function ()
{
$.ajax({
type: "post",
url: "books", //this is my servlet
data: <<< my data here >>>
});
});
});
</script>
This is part of my jsp:
<form action="books" method="post">
<table width="70%" border="1">
<%
List<Book> books = (List<Book>) request.getAttribute("books");
for (int i = 0; i < books.size(); i++) {
%>
<tr>
<td>
<input type="checkbox" name="book<%=i%>"
value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
</td>
</tr>
<%
}
%>
</table>
<select name="user_name">
<%
List<User> users = (List<User>) request.getAttribute("users");
for (int i = 0; i < users.size(); i++) {
%>
<option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
<%
}
%>
</select>
<input type="submit" name="submit" value="Purchase">
<input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
</form>
I would like to pass everything that normally passes by form above.
Could you please show me around ajax technology by this example?

Give an instance id to the form and use with the serialize() method
$('#form').submit(function ()
{
$.ajax({
type: "post",
url: "books", //this is my servlet
data: $(this).serialize()
});
});
<form id="form" action="books" method="post">
<table width="70%" border="1">
<%
List<Book> books = (List<Book>) request.getAttribute("books");
for (int i = 0; i < books.size(); i++) {
%>
<tr>
<td>
<input type="checkbox" name="book<%=i%>"
value="<%= books.get(i).getBook_id()%>"> <%= books.get(i).getName() %>
</td>
</tr>
<%
}
%>
</table>
<select name="user_name">
<%
List<User> users = (List<User>) request.getAttribute("users");
for (int i = 0; i < users.size(); i++) {
%>
<option value="<%=users.get(i).getName()%>"><%=users.get(i).getName()%></option>
<%
}
%>
</select>
<input type="submit" name="submit" value="Purchase">
<input type="button" value="Call Servlet" name="Call Servlet" id="call"/>
</form>

Related

cannot read properties of undefined(reading"name")

I trying to make a survey website and I have been stuck on this bug for hours. I have a from that has 5 inputs and it takes name, question and 4 options as text and submits them. when clicking on submit button the server recieves a post method with the action /all after getting /all the server should render all.ejs. below is my index.js file:
router.post('/all', function (req, res) {
const newsurvey=new survey({
"name":req.body.name,
"question":req.body.question,
"option1":req.body.option1,
"option2": req.body.option2,
"option3":req.body.option3,
"option4": req.body.option4,
})
survey.create(newsurvey)
console.log(newsurvey)
console.log(req.body.name)
res.render('all', { title: 'All Surveys', survey});
});
// initializing a new survey object
router.get('/addsurvey', function (req, res, next) {
survey.find((err, list)=>{
const newsurvey = new survey({
"name":"",
"question":"",
"option1":"",
"option2":"",
"option3":"",
"option4":""
}
)}
,res.render('surdetails', { title: 'Details', survey})
);
});
router.get('/all', function (req, res) {
survey.find((err, list)=>{
if (err){
return console.error(err);
}else{
res.render('all', { title: 'All Surveys', survey: survey });
}
})
});
and below is my all.ejs file which returns cannot read properties of undefined(reading"name"):
<tbody>
<!-- Template Row -->
<% for (let count = 0; count < survey.length; count++) { %>
<tr>
<td><%= survey[count].name %></td>
<td class="text-center"><%= survey[count].name %></td>
<td class="text-center"><%= survey[count].question %></td>
<td class="text-center">
<input type="radio" id="option1" name="option1" value="<%= survey[count].option1 %>">
<label for="option1"><%= survey[count].option1 %></label><br>
<input type="radio" id="option2" name="option2" value="<%= survey[count].option2 %>">
<label for="option2"><%= survey[count].option2 %></label><br>
<input type="radio" id="option3" name="option3" value="<%= survey[count].option3 %>">
<label for="option3"><%= survey[count].option3 %></label><br><br>
</td>
<td class="text-center">
<i class="fa fa-trash-o"></i> Delete
</td>
</tr>
<% } %>
</tbody>

Transferring data from the js script to the controller

In the view (Index.cshtml) I have a button, when I click on that, the script that in the selectedItems writes the data is triggered. how are selectedItems transferred to the controller?
Button:
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
JS:
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
}
Controller (Users):
[HttpPost]
public async Task<ActionResult> Delete(string[] selectedUsers)
{
...
return RedirectToAction("Index");
}
I tried to use ajax, but something does not work out:
function SelectedCheckbox()
{
$.ajax({
url: "/Users",
contentType: "application/json",
method: "POST",
data: { parameters: parameters },
success: function (data) {
var data = new Array();
$("input[id='check']:checked").each(function () { data.push($(this).val()); });
alert(data.result);
},
error: function (data) { alert(data.responseText); }
})
}
#model IEnumerable<Task1.Models.User>
#{
ViewBag.Title = "Список пользователей";
}
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<div class="btn-toolbar nl container col-md-12" role="toolbar" aria-label="Menu">
<form method="post" asp-action="Delete">
<button type="submit" onclick="SelectedCheckbox()" name="delete" id="delete" class="btn-group col-md-2 col-md-offset-0">Remove</button>
</form>
<form method="post" asp-controller="Account" asp-action="LogOff">
<button type="submit" class="col-md-2 col-md-offset-3 " role="group" aria-label="LogOff" />LogOff</button>
</form>
</div>
<form asp-action="Delete">
<div class="nl">
<table class="table table-striped table-bordered ">
<tbody class="table-responsive ">
<tr><th><input type="checkbox" class="all" data-id="d1" title="Выбрать все"></th><th>Login</th><th>Date of registration</th><th>Date Last Login</th><th>Block disabled</th></tr>
#foreach (var user in Model)
{
<tr>
<td>
<input type="checkbox" name="selectedUsers"
id="#user.Id" value="#user.Id"
class="styled">
</td>
<td>#user.UserName</td>
<td>#user.DateOfRegistration</td>
<td>#user.DateLastLogin</td>
<td>#user.LockoutEnabled</td>
</tr>
}
</tbody>
</table>
</div>
</form>
<script type="text/javascript">
function SelectedCheckbox() {
var selectedItems = new Array();
$("input[id='check']:checked").each(function () { selectedItems.push($(this).val()); });
alert(selectedItems);
return (selectedItems);
}
</script>
I need to pass the value of the selected Item from the script in the method of removing the controller

Cannot get data from form with query selector

I can't get the data from the input of the form, it seems like the only function of the submit button is to refresh the page.
const Form = document.querySelector('.broadcast-form')
Form.addEventListener('submit', (e) => {
e.preventDefault()
const cliente = Form.querySelector('#clienti').options[clienti.selectedIndex].text
console.log(cliente)
})
<form class="container broadcast-form">
<select multiple class="form-control" id="clienti" style="height: 150px" onchange="selectCustomer()">
<!--
<% for(var i=0; i<clienti.length; i++) {%>
<option><%= clienti[i]["Cliente"] + " CL: " + codiceLisa[i]["Codice_Lisa"] %></option>
<% } %>
-->
<option>Foo CL: ABC</option>
<option>Bar CL: DEF</option>
<option>Baz CL: GHI</option>
</select>
<input type="submit" class="btn btn-primary btn-lg" value="Genera XML" />
</form>
When you look at the JavaScript console of your browser, you'll see that it complains about not being able to read a property of undefined. This is caused by clienti not being defined in your JavaScript code, in the clienti.selectedIndex part. Defining it seems to resolve your issue.
As a bonus: you may want to consider using selectedOptions to find all selected options in the select, given that it has the multiple attribute. The selectedIndex will only give you the first one.
function selectCustomer() {
/* defined only to prevent errors when changing the value of the select */
}
const form = document.querySelector('.broadcast-form');
form.addEventListener('submit', (e) => {
e.preventDefault()
let clienti = form.querySelector('#clienti'),
cliente = (clienti.selectedIndex < 0 ? null : clienti.options[clienti.selectedIndex].text);
console.log(cliente);
// bonus:
for (let clienteEl of clienti.selectedOptions) {
console.log(`bonus: ${clienteEl.text}`);
}
})
<form class="container broadcast-form">
<select multiple class="form-control" id="clienti" style="height: 150px" onchange="selectCustomer()">
<!--
<% for(var i=0; i<clienti.length; i++) {%>
<option><%= clienti[i]["Cliente"] + " CL: " + codiceLisa[i]["Codice_Lisa"] %></option>
<% } %>
-->
<option>Foo CL: ABC</option>
<option>Bar CL: DEF</option>
<option>Baz CL: GHI</option>
</select>
<input type="submit" class="btn btn-primary btn-lg" value="Genera XML" />
</form>

Request variable from forEach loop jQuery

I am trying to make a multiple choice questionnaire in node. I have a forEach loop printing the form for the questions and answer fields. Problem is that I can not get the correct variable in my jQuery file where I am doing the comparison.
Using a forEach loop in an EJS and checking it in a jQuery file.
jQuery File:
$(document).ready(function(){
$('.bcheck').click(function(){
var on = 1;
var ans = $(this).attr('realanswer');
var theirAns = $("input[placeholder=Answer]").val();
console.log(ans);
if(ans == theirAns){
//DO SOMETHING
}
});
});
The value for var theirAns = $("input[placeholder=Answer]").val(); stays the first element in the iteration. Could I use the this function to get value of something that is not an element of the item I am clicking?
HTML for the EJS file:
<% topic.questions.forEach(function(question){ %>
<% if(question.difficulty == 10){ %>
<form action="/lesson/<%= lesson._id %>/topic/<%= topic._id %>/course/<%= question._id %>/quest?_method=PUT" method="POST">
<div class="quest_info questionf">
<%= question.question %>?
<div class="text_input">
<input type="hidden" name="res[_id]" value="<%= question._id %>">
<input type="hidden" name="realAnswer" value="<%= question.answer %>">
<input id="correct" type="hidden" name="res[correct]" value="<%= false %>">
<% if(question.question_type == "multiple"){ %>
<% var ran = ranNumber(0, 3) %>
<% var n = 0; %>
<% question.wrong_answers.forEach(function(wAns){ %>
<div class="bw btn btn-success" value="<%= wAns %>"> <%= wAns %> </div>
<% if(ran == n){ %>
<div class="ba btn btn-success "><%= question.answer %></div>
<% }; %>
<% n += 1; %>
<% }); %>
<input type="hidden" name="res[answer]" value="<%= question.answer %>" placeholder="Answer">
<% }else{%>
<input type="text" name="res[answer]" placeholder="Answer" >
</input>
</div>
<% }; %>
<div class="text_input">
<div class="bcheck btn btn-primary pull-right" realanswer="<%= question.answer %>" >Check Answer</div>
</div>
<% x += 1 %>
<div class="text_input">
</div>
</div>
<% }; %>
<% }); %>
You're trying to use $("input[placeholder=Answer]").val() - it will return the first value indeed.
If you want to check every element matching a selector $("input[placeholder=Answer]").each() will help. Here is an example based on your code snippet.
$(document).ready(function() {
$('.bcheck').click(function() {
var ans = $(this).data('realanswer');
$("input[placeholder=Answer]").each(function() {
var theirAns = Number($(this).val());
if (ans === theirAns) {
console.log('Nice');
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="bcheck" data-realanswer="42">check</button>
<input placeholder="Answer" type="text">
<input placeholder="Answer" type="text">
<input placeholder="Answer" type="text">

how to refresh more than one div using jquery

I have a jsp page on which when i click on any image the image is changed to another.Now what i want that the effect of one user changes must be reflect to all the users at the same time who access this website without refreshing the entire page
Here is my code...............
<html>
<title>Java Web Starter Application</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link rel="stylesheet" href="style.css" />
<head>
<title>Manage Objects</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
loadbulbData();
});
//bulbstatus
function loadbulbData() {
$('#main').load('index.jsp', function()
{
//alert('inside refresh method');
reloadData = window.setTimeout(loadbulbData, 20000)
});
}
</script>
</head>
<body>
<%! public static int bulbStatus = 0;
public static int tubeStatus=0;
public static int fanStatus=0;
public static int acStatus=0;
%>
<%
%>
<%
if(request.getParameter("BULB.x")!=null)
{
if(bulbStatus==0)
bulbStatus=1;
else
bulbStatus=0;
}
if(request.getParameter("BULBON.x")!=null)
{
if(bulbStatus==1)
bulbStatus=0;
else
bulbStatus=1;
}
if(request.getParameter("TUBEOFF.x")!=null)
{
if(tubeStatus==0)
tubeStatus=1;
else
tubeStatus=0;
}
if(request.getParameter("TUBEON.x")!=null)
{
if(tubeStatus==1)
tubeStatus=0;
else
tubeStatus=1;
}
if(request.getParameter("FanOff.x")!=null)
{
if(fanStatus==0)
fanStatus=1;
else
fanStatus=0;
}
if(request.getParameter("FanOn.x")!=null)
{
if(fanStatus==1)
fanStatus=0;
else
fanStatus=1;
}
if(request.getParameter("AcOff.x")!=null)
{
if(acStatus==0)
acStatus=1;
else
acStatus=0;
}
if(request.getParameter("AcOn.x")!=null)
{
if(acStatus==1)
acStatus=0;
else
acStatus=1;
}
%>
<%
if(bulbStatus==0)
{
%>
<p><font color="white"><center><b>Manage Objects</center></b></p>
<div id="main" name="alldivisions">
<div id="NW" name="bulboffdiv">
<form name="bulbForm" method="post" id="bulbonformid">
<input type="image" src="images/pic_bulboff.png" align="center" id="imagebulb" name="BULB" value="bulb"></input>
<p><font color="RED"><b> BULB OFF</b></p>
</form>
</div>
<%
}
else
{
%>
<p><font color="white"><center><b>Manage Objects</center></b></p>
<form name="bulbon" method="post">
<div id="NW" name="bulbondiv">
<input type="image" src="images/pic_bulbon.png" align="center" id="imagebulb" name="BULBON" value="bulb"></input>
<p><font color="Green"><b> BULB ON</b></p>
</div>
</form>
<%
}
if(tubeStatus==0)
{
%>
<form name="lampOffForm" method="post">
<div id="NE" name="lampoffdiv">
<input type="image" src= "images/lampoff.png" align="center" name="TUBEOFF" value="tube" id="lampoff"></input>
<p><font color="RED"><b> LAMP OFF</b></p>
</div>
</form>
<% }
else
{
%>
<form name="lampOnForm" method="post">
<div id="NE" name="lampondiv">
<input type="image" src= "images/lampon.png" align="center" name="TUBEON" value="tube" id="lampon"></input>
<p><font color="Green"><b> LAMP ON</b></p>
</div>
</form>
<%
}
if(fanStatus==0)
{
%>
<form name="fanOffForm" method="post">
<div id="SW" name="fanoffdiv">
<input type="image" src="images/Fanoff.png" align="center" id="image3" name="FanOff" value="ac"></input>
<p><font color="RED"><b> FAN OFF</b></p>
</div>
</form>
<%
}
else
{
%>
<form name="FanOnForm" method="post">
<div id="SW" name="fanondiv">
<input type="image" src="images/Fanon.png" align="center" id="image3" name="FanOn" value="ac"></input>
<p><font color="Green"><b> FAN ON</b></p>
</div>
</form>
<%
}
if(acStatus==0)
{
%>
<form name="Acoffform" method="Post">
<div id="SE" name="acoffdiv">
<input type="image" src="images/ACoff.png" align="center" id="image4" name="AcOff" value="fan"></input>
<p><font color="RED"><b> AC OFF</b></p>
</div>
</form>
<%
}
else
{
%>
<form name="AcOnForm" method="Post">
<div id="SE" name="acondiv">
<input type="image" src="images/ACon.png" align="center" id="image4" name="AcOn" value="fan"></input>
<p><font color="Green"><b> AC ON</b></p>
</div>
</form>
<%
}
%>
</div>
</body>
</html>
Thanks in advance......
You'll need to implement some kind of server polling - this article gives a good example http://techoctave.com/c7/posts/60-simple-long-polling-example-with-javascript-and-jquery/ using jquery - and it might point you in the right direction. (this is essentially demonstrating a Server Push method)
I think you just need to call a function for refreshed data without refreshing. If that's true. Then you can use jquery ajax to fetch updated data and poll it after some amount of time
For ex:
setTimeout(function(){
$.ajax({
url: "demo_test.txt", //url for fetching refreshed data
success: function(result){
// write your refresh image code here
}
});
}, 5000); //specify the time interval after which you need to refresh the data(this is 5 secs)
Hey i solve the problem just adding the following in my jquery code
$('#main').load('index.jsp', function() #main)

Categories