Spring REST not returing anything - spring

Here is my rest controller:
#RestController
public class LoginController {
#Autowired
private AppInstances appInstances;
#RequestMapping(method = RequestMethod.POST, value = "/signup")
public ResponseEntity<?> signup(#RequestBody SignupForm form) throws Exception
{
ResponseEntity<?> validate = FormFieldValidator.validate(form);
if(validate.getStatusCode() != HttpStatus.OK)
return validate;
else
{
return SignupService.signup(form, appInstances);
}
}
Here is HTML form
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form method="post">
<input type="text" name="userType" value="USER"/><br>
<input type="text" name="pwd" value="123456"/><br>
<input type="text" name="rpwd" value="123456"/><br>
<input type="text" name="name" value="manish kumar"/><br>
<input type="text" name="sex" value="Male"/><br>
<input type="text" name="bizzCategory" value="Restaurant"/><br>
<button>OK</button>
</form>
<script src="jquery.js"></script>
<script>
var formData = $("form").serializeArray();
var jsonData={};
$(formData).each(function(i,o){
console.log(o.name+"==="+o.value);
jsonData[o.name] = o.value;
});
$.ajax({
url:"http://localhost:8084/mobapp/signup",
type:"POST",
contentType:"application/json",
data:JSON.stringify(jsonData)
}).done(function(d){
alert(JSON.stringify(d));
}).error(function(e){
alert(e);
});
</script>
</body>
</html>
Here is what it shows in firebug. It has no response by the way.
OPTIONS signup 200 OK localhost:8084
I a using spring security 4.0.1.

Related

Thymeleaf is trying to build a html which does not exist and which is not called anywhere

I am trying to build a spring mvc app with spring boot and thymeleaf. I am trying to create a form to insert an object into my data base (something which I already do in my app and is working) but I constantly find this error:
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "ServletContext resource [/WEB-INF/views/error.html]")
(...)
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/WEB-INF/views/error.html]
(...)
This is the problem you usually find when you are trying to reference a template which does not exist or has a different name. Here's the thing. There is no Error.html in my views' folder as you can see in the print below:
Can anyone help me understand what's going on?
EDIT with more information:
Below you can find the endpoints which are giving me trouble:
#GetMapping("{id}/add-expense")
public String expensesForm(Model model, #PathVariable Long id){
model.addAttribute("expense", new Expenses());
model.addAttribute("budgetId", id);
return "expenseForm";
}
#PostMapping("{id}/add-expense")
public String expenseSubmitted(#ModelAttribute Expenses expense, #PathVariable Long id, Model model){
Budgets budget = budgetsRepository.getById(id);
if(budget != null){
budget.addExpense(expense);
expense.setBudget(budget);
expensesRepository.saveAndFlush(expense);
}
else{
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "not all variables there");
}
model.addAttribute("expense", expense);
return "expenseResult";
}
The GET endpoint seems to be working as intended. When I load the "id/add-expense" path it displays the page "expenseForm" correctly. The problem comes when I try to submit the form in the "expenseForm" template and go to the POST for "id/add-expenses". That is when I get a 400 bad request response. I am lead to believe that the problem might be that the "expenseForm" cannot correctly populate the #ModelAttribute in the POST method but I can't say why or how to fix it. In the console, I am given the error above which tells me that Thymeleaf cannot find the template for "error.html".
expenseForm.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Expense Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Expense Creation</h3>
</div>
<form action="#" th:action="#{/budgets/{id}/add-expense(id = ${budgetId})}" th:object="${expense}" method="post">
<p>Name: <input type="text" th:field="*{expenses_name}" /></p>
<p>Amount: <input type="number" th:field="*{expenses_amount}" /></p>
<p>Date: <input type="text" th:field="*{expenses_date}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</div>
</body>
</html>
expenseResult.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Expense Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Expense Created</h3>
</div>
<p th:text="'Name: ' + ${expense.expenses_name}" />
<p th:text="'Amount: ' + ${expense.expenses_amount}" />
<p th:text="'Date: ' + ${expense.expenses_date}" />
Submit another expense
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/budgetScript.js"></script>
</div>
</body>
</html>
Class Expenses:
#Entity(name = "expenses")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Expenses {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long expenses_id;
private String expenses_name;
private Integer expenses_amount;
private Date expenses_date;
#ManyToOne
#JoinTable(
name = "budget_expenses",
joinColumns = #JoinColumn(name = "expenses_id"),
inverseJoinColumns = #JoinColumn(name = "budgets_id"))
private Budgets budget;
//Gettes setters and constructor
}
Thank you in advance.
EDIT 2 after changing the name of "expenseResult.html" to "error.html":
So I decided to follow the tip from andrewJames and I changed the name of "expenseResult.html" to "error.html". I also changed the return value in the POST method from 'return "expenseResult"' to 'return "error"' and I am no longer given the 400 bad request error on the application. Instead, I am given the "error.html" page but the fields for expense.expenses_name, expense.expenses_amount or expense.expenses_date are not shown in the page. It is just an empty page with the "Expense Creation" text. In the console I receive a new error:
org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "expense.expenses_name" (template: "error" - line 19, col 16)
(...)
Caused by: org.springframework.expression.spel.SpelEvaluationException: EL1007E: Property or field 'expenses_name' cannot be found on null
(...)
From what we can see, the application cannot retrieve the fields from null, meaning that the #ModelAttribute Expenses expense is not returning the correct values from the form page. It more or less confirms my suspicion that the problem was in the modelAttribute but I continue to not know how to correct the problem since I have tried to verify multiple times if everything was okay and I found no issue. I also don't understand why it is looking for a "error.html" file considering that I had no prior mention to such a file in my code and project.
EDIT 3 after using ModelandView intead of ModelAttribute:
Following dsp_user's suggestion. I started by hardcoding the path with "/budgets/10/add-expense" instead of using {id} and the problem remained, which makes me believe that the problem is not the path.
I started using the ModelAndView, as can be shown below, but I continued to have the same problem as before (400 bad request).
#PostMapping("{id}/add-expense")
public ModelAndView expenseSubmitted(#ModelAttribute("expenses") Expenses expenses, #PathVariable Long id, Model model){
System.out.println("here");
Budgets budget = budgetsRepository.getById(id);
if(budget != null){
budget.addExpense(expenses);
expenses.setBudget(budget);
expensesRepository.saveAndFlush(expenses);
}
else{
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "not all variables there");
}
ModelAndView modelAndView = new ModelAndView("expenseResult");
modelAndView.addObject("expense", expenses);
return modelAndView;
}
EDIT 4 to add the Budgets logic:
Budgets:
#Entity(name = "budgets")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Budgets {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long budgets_id;
private String budgets_name;
private String budgets_description;
private Integer budgets_amount;
#OneToMany(mappedBy = "budget")
#JsonIgnore
private List<Expenses> expenses;
#Transient
public float budgets_expense_sum = 0;
//Gettes setters and constructor
}
Budget Creation Endpoints:
#GetMapping("new")
public String budgetsForm(Model model){
model.addAttribute("budget", new Budgets());
return "budgetForm";
}
#PostMapping("new")
public String budgetSubmitted(#ModelAttribute Budgets budget, Model model){
budgetsRepository.saveAndFlush(budget);
model.addAttribute("budget", budget);
return "budgetResult";
BudgetForm.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Budget Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Budget Creation</h3>
</div>
<form action="#" th:action="#{/budgets/new}" th:object="${budget}" method="post">
<p>Name: <input type="text" th:field="*{budgets_name}" /></p>
<p>Description: <input type="text" th:field="*{budgets_description}" /></p>
<p>Monthly Amount: <input type="number" th:field="*{budgets_amount}" /></p>
<p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</div>
</body>
</html>
BudgetResult.html:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<title>Budget Creation</title>
</head>
<body>
<div class="container">
<div class="container">
<div th:insert="fragments/navbar.html"> </div>
<div class="jumbotron">
<div class="row">
<h3>Budget Created</h3>
</div>
<p th:text="'Name: ' + ${budget.budgets_name}" />
<p th:text="'Description: ' + ${budget.budgets_description}" />
<p th:text="'Amount: ' + ${budget.budgets_amount}" />
Submit another message
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script src="js/budgetScript.js"></script>
</div>
</body>
</html>

Spring-MVC Thymeleaf from not submitting

I'm new to spring and I've tried coding a prototype.
I've tried making a form. Whenever I press the submit-button, nothing happens.
I'm using Spring Boot 2.4.3 with Oracle OpenJDK 15.0.2. I've tried Firefox and Chrome. The js-console is empty.
This is my model (Patient.java):
public class Patient implements Serializable {
private long id;
private String firstname;
private String lastname;
// Geters and seters
}
My Controller (PatientController.java):
#Controller
public class PatientController {
#GetMapping("/patient")
public String patientForm(Model model) {
model.addAttribute("patient", new Patient());
return "addPatient";
}
#PostMapping("/patient")
public String patientSubmit(#ModelAttribute("patient") Patient patient, Model model) {
model.addAttribute("patient", patient);
return "addedPatient";
}
}
My addPatient.html:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTL-Testet Prototype</title>
</head>
<body>
<h1>Add a patient</h1>
<from action="#" th:action="#{/patient}" th:object="${patient}" method="post">
<p>Id: <input type="number" th:field="*{id}"/></p>
<p>Firstname: <input type="text" th:field="*{firstname}"/></p>
<p>Lastname : <input type="text" th:field="*{lastname}"/></p>
<button type="submit">Register</button>
</from>
</body>
</html>
My addedPatient.html:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTL-Testet Prototype</title>
</head>
<body>
<h1>Add a patient</h1>
<p th:text="'Added ' + '[' + ${patient.id} + ']' + ${patient.firstname} + ' ' + ${patient.lastname}"></p>
Add another patient
</body>
</html>
The from tag on the addPatient.hmtl page is wrong, if you change it to form tag as below, the problem is solved:
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>HTL-Testet Prototype</title>
</head>
<body>
<h1>Add a patient</h1>
<form action="#" th:action="#{/patient}" th:object="${patient}" method="post">
<p>Id: <input type="number" th:field="*{id}"/></p>
<p>Firstname: <input type="text" th:field="*{firstname}"/></p>
<p>Lastname : <input type="text" th:field="*{lastname}"/></p>
<button type="submit">Register</button>
</form>
</body>
</html>

why wire:click not working in laravel livewire

laaravel version:8.0
livewire version: 2.x
Hi there
I am new to laravel livewire and facing a strange issue!. in order to execute the action i used wire:click as can be seen in the following code in my admin-login.blade.php
#section('content')
<div class="admin-login display-flex flex-align-items-center flex-justify-content-center">
<button wire:click="toDo">{{$login}}</button>
<div class="admin-form display-flex flex-direction-column flex-justify-content-center" >
#livewire('header',['name'=> 'Admin Login','width'=> '100%','height' => '20%'])
<form class=" display-flex flex-direction-column flex-justify-content-center" >
<section style="margin: 2%;">
<label for="Email">Email :<span style="color: red">*</span></label>
<input type="email" required>
</section>
<section style="margin: 2%;">
<label for="Password">Password :<span style="color: red">*</span></label>
<input type="password" required>
</section>
<button style="width: 40%; height: 5vh; align-self: center;justify-self: flex-end;">Login</button>
</form>
</div>
</div>
#endsection
my app.blade.php file in layouts directory is
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="{{asset('css/admin/app.css')}}">
#livewireStyles
<title>Admin Dashboard</title>
</head>
<body>
#livewire('nav-bar')
#livewire('side-bar')
#yield('content')
</body>
#livewireScripts
<script>
var isStudentDropDown = false
Livewire.on('showSidebar',()=>{
document.getElementById('sidebar').style.display = "block"
})
Livewire.on('closeSidebar',()=> {
document.getElementById('sidebar').style.display = "none"
})
Livewire.on('showDropdown',data => {
if(document.getElementById(data).style.display === "block"){
document.getElementById(data).style.display = "none"
}else{
document.getElementById(data).style.display = "block"
}
})
</script>
</html>
now my component php file
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class AdminLogin extends Component
{
public $login = "login";
public function render()
{
return view('livewire.admin-login');
}
public function hell(){
$this->login = "signup";
}
public function toDo(){
dd('do some thing');
}
}
i have checked my devtools and got no request being send to the server
Pardon me for any mistake!
Extends layouts from component
ref link https://laravel-livewire.com/docs/2.x/rendering-components#custom-layout
public function render()
{
return view('livewire.admin-login')
->extends('layouts.app')
->section('content');
}
and remove #section from admin-login.blade.php

MEAN stack ajax POST Error: TypeError: Cannot read property 'userName' of undefined

So, here's some background: I am working on a MEAN stack app for my school where we can read and post our Galaga and Dig Dig highscores to a mongo database.
I am getting an error:
POST http://url.com/api/scores 500 (Internal Server Error)
TypeError: Cannot read property 'userName' of undefined at /app/server.js:37:22
server.js:37 is:
app.post("/api/scores", function(req, res){
Score.create({
name:res.body.userName,
game:res.body.game,
points:res.body.userPoints
});
});
The index.html that the res.body.* is coming from is:
<!DOCTYPE html>
<html ng-app="nameOfApp">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.10/angular.min.js"></script>
<script src="core.js"></script>
</head>
<body ng-controller="mainController">
<div class="container">
<div class="jumbotron text-center">
<div class="container">
<h1>HelpDesk Gaming Leaderboard</h1>
</div>
</div>
<div class="container">
<table>
<tr>
<td><b>Name</b></td>
<td><b>Score</b></td>
</tr>
<tr ng-repeat="score in scores">
<td>{{score.name}}</td>
<td>{{score.points}}</td>
</tr>
</table>
</div>
<br/>
<h2>Score?</h2>
<form>
<input name="userName" type="String" class="form-control" id="userName" ng-model="formData.userName" placeholder="Your Name">
<input name="game" type="String" class="form-control" id="game" ng-model="formData.game" placeholder="The game?">
<input name="userPoint" type="Number" class="form-control" id="userPoint" ng-model="formData.userPoint" placeholder="Points?">
<button type="submit" class="btn btn-default" ng-click="createScore()">Submit</button>
</form>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js">
</script>
</body>
</html>
and the core.js, which is the angular piece is:
var nameOfApp= angular.module('nameOfApp', []);
nameOfApp.controller("mainController", ["$scope", "$http", function($scope, $http) {
$scope.formData = {};
// when landing on the page, get all scores and show them
$http.get('/api/scores')
.success(function(data) {
$scope.scores = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
$scope.createScore = function() {
$http.post('/api/scores', $scope.formData)
.success(function(data) {
$scope.formData = {};
$scope.scores = data;
console.log(data);
})
.error(function(data) {
console.log('Error: ' + data);
});
};
}]);
Thanks for your input, and if there are any stylistic things that I have wrong, I would love to hear them. I am trying to get better at MEAN stack development.
It's not res.body.* you want to use in your Score.create method, you want to be using req.body.*. 'req' is what has all the data from your http request.
Should be:
app.post("/api/scores", function(req, res){
Score.create({
name:req.body.userName,
game:req.body.game,
points:req.body.userPoints
});
});

ajax:send form, can't receive parameters?

I try to send a form use ajax. I can send the information successfully. And I can receive the information. However, I can't get parameters form the request. I don't know the reason.
I try IE, FIREFOX, Chrome, none of them can send the form.
This is my code:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta http-equiv="Expires" content="0">
<meta http-equiv="kiben" content="no-cache">
<title>Login Page</title>
<%String account =(String) session.getAttribute("fail"); %>
</script>
<script language="javascript" type="text/JavaScript" src="jquery-1.3.2.min.js">
</script>
<script language="javascript" type="text/JavaScript">
window.onload = function fillChecklist(){
var error ="${sessionScope.fail}";;
if(null != error&& error!=""){
alert(error);
}
}
function doFind() {
if(document.getElementById("username").value.length>0&&document.getElementById("password").value.length>0){
$.ajax({
cache : false,
type : "POST",
url : "login",
data : $("#ajaxFrm").serialize(),
async : false,
error : function(request) {
alert(“error");
},
success : function(data) {
//$("#ajaxDiv").html(data);
alert(data);
}
});
}
}
</script>
</head>
<body>
<form id="ajaxFrm" >
UserName<input type="text" id="username" ><br />
Password &nbsp<input type="password" id="password">
</form>
<input type="checkbox" name="remember" id="remember">Remeber Username</input><br />
<input value="Submit" type="button" onClick="doFind()"/>
<input value="Delete" type="button" onClick="DelCookie()"/>
<div id="ajaxDiv"></div>
</body>
</html>
Please change your input type="button" to input type="submit" first, and then submit with ajax.e.g
<html>
<head>
<script type="text/javascript" src="jquery-1.8.3.js"></script>
<script type="text/javascript">
$("form#ajaxFrm").submit(function() {
var mydata = $("form#ajaxFrm").serialize();
console.log(mydata); //check data before send to server
$.ajax({
type: "POST",
url: "myUrlToPostData.php",
data: mydata,
success: function(response, textStatus, xhr) {
alert("success");
},
error: function(xhr, textStatus, errorThrown) {
alert("error");
}
});
return false;
});
</script>
</head>
<body>
<form id="ajaxFrm" method="post">
UserName<input type="text" id="username" name="username"/><br />
Password <input type="password" id="password" name="password"/>
<input value="submit" type="submit" name="submit"/>
</form>
</body>
</html>

Resources