AJAX with database - ajax

There is a jsp form for recording a new flight. I need to check the availability of the flight number using ajax in the database. I'm trying to write an ajax request, but I'm beginner in JS.
<div class="form-group">
<div class="input-group">
<input type="number" class="form-control" placeholder="Flight number" id="flightNumber" name="flightNumber" required>
<p class="error-input" id="loginError">
<c:if test="${duplicateFlightNumber == true}">
<fmt:message key="validate.sameFlightNumber"/>
</c:if>
</p>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="From city" id="fromCity" name="fromCity" required>
</div>
</div>
<div class="form-group">
<div class="input-group">
<input type="text" class="form-control" placeholder="To city" id="toCity" name="toCity" required>
</div>
</div>
Servlet that proceed this form without ajax:
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Flight flight = new Flight(); flight.setFlightNumber(Integer.valueOf(req.getParameter("flightNumber")));
flight.setFromCity(req.getParameter("fromCity"));
flight.setToCity(req.getParameter("toCity"));
if (!validation.flightNumberUnique(flightNumber)){
req.setAttribute(DUPLICATE_FLIGHT_NUMBER, true);
forward(Constants.Pages.Admin.ADD_FLIGHT_JSP, req, resp);
return;
}
getFlightService().add(flight);
LOGGER.trace("New flight added");
redirectToAction(Constants.ServletPaths.Admin.ADMIN_ALL_FLIGHT_PATH, req, resp);
}
How can I replace this manipulation with ajax

$("#flightNumber").change(function(){
var flightnumber = $("#flightNumber").val();
//get to and from values
$.post("servletname",{"flightNumber":flightnumber,"fromCity":fromCity,"toCity":toCity}, function(data, status){
//data contains elements that you print on your servlet
$("#loginerror").text("your message to be displayed in error field");
});
});
$(selector).post(URL,data,function(data,status,xhr),dataType) is used for ajax post request (Jquery)

Related

Model attribute inconsistent after form submission

I'm still trying to figure out what's happening on the backend here. Working with Spring Boot/Thymeleaf. I have a form template that updates a model attribute object on save. I'm trying to use the updated values on the backend, however it's inconsistent among my functions and I'm not sure why.
Thymeleaf template
<div layout:fragment="content" class="container">
<form action="#" th:action="#{/utility/exportbadges}" th:object="${badgeExport}" method="post">
<div class="form-group col-md-6">
<label class="col-form-label-sm">Badge type</label>
<select th:field="*{type}" class="form-control">
<option th:each="badgeType : ${T(org.myorg.myproject.model.badge.BadgeType).values()}"
th:value="${badgeType}"
th:text="${badgeType}">
</option>
</select>
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Use background?</label>
<input type="checkbox" th:field="*{background}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Mark preprinted?</label>
<input type="checkbox" th:field="*{preprinted}" class="form-control">
</div>
<div class="form-group col-md-3">
<label class="col-form-label-sm">Save to path (/tmp default):</label>
<input type="text" th:field="*{saveDir}" class="form-control" placeholder="/tmp">
</div>
<div class="form-group col-md-12 mt-2">
<div class="col-sm-10">
<input class="btn btn-primary" id="save" type="submit" value="Export" />
<input class="btn btn-secondary" type="reset" value="Reset" />
</div>
</div>
</form>
</div>
#RequestMapping(value = "/utility/exportbadges")
public String exportBadges(Model model) {
final BadgeExport badgeExport = new BadgeExport();
model.addAttribute("badgeExport", badgeExport);
return "utility/exportbadges";
}
POST method. The object is correct in this function. Any field that's edited in the form above reflects in this function. However, on redirect, the object is as if it only has default instantiation/has been unedited.
#RequestMapping(value = "/utility/exportbadges", method = RequestMethod.POST)
public String exportBadgeFlow(Model model,
#ModelAttribute("badgeExport") final BadgeExport badgeExport) {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir pre export: {}", badgeExport.getSaveDir());
switch(badgeExport.getType()) {
case "Attendee":
log.error("Attendee export not yet implemented");
break;
case "Vip":
return "redirect:exportbadges/vip-badges.pdf";
case "Specialty":
return "redirect:exportbadges/specialty-badges.pdf";
case "Staff":
return "redirect:exportbadges/staff-badges.pdf";
case "Guest":
return "redirect:exportbadges/guest-badges.pdf";
}
return "redirect:exportbadges";
}
Redirect function. Badge type will be null and saveDir will be /tmp as default instead of updated value in form.
#RequestMapping(value = "/utility/exportbadges/vip-badges.pdf")
public ResponseEntity<String> getAllVipBadgePdf(#ModelAttribute("badgeExport") final BadgeExport badgeExport) throws IOException {
log.info("BadgeExport badge type: {}", badgeExport.getType());
log.info("BadgeExport save dir during export: {}", badgeExport.getSaveDir());
}

cannot save data through Ajax laravel 8

when normal request performed , it saves data without any error but through ajax it returned error: [object HTMLDivElement].
but when I comment the create function in controller , request is performed successfully.
csrf token added in meta tag
data can be saved through normal request but not with the ajax
Route is properly configured
ass far as i understand , error is generating while performing create function in the controller.
Controller
public function store(Request $request)
{
$data = $request->all();
Contact::create($data);
return response()->json(['success'=>'Message Sent Successfully']);
}
Blade.php
<!-- ======= Contact Section ======= -->
<section id="contact" class="contact">
<form method="POST" action="{{route('contact.store')}}" class="php-email-form" id="contact-form">
<div class="row gy-4">
<div class="col-md-6">
<input type="text" name="name" class="form-control" placeholder="Your Name" required>
</div>
#csrf
<div class="col-md-6 ">
<input type="email" class="form-control" name="email" placeholder="Your Email" required>
</div>
<div class="col-md-12">
<input type="text" class="form-control" name="subject" placeholder="Subject" required>
</div>
<div class="col-md-12">
<textarea class="form-control" name="message" rows="6" placeholder="Message" required></textarea>
</div>
<div class="col-md-12 text-center">
<div class="loading">Loading</div>
<div class="error-message"></div>
<div class="sent-message">Your message has been sent. Thank you!</div>
<button type="submit" id="send-message">Send Message</button>
</div>
</div>
</form>
</section><!-- End Contact Section -->
Ajax
$(document).ready(function() {$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}
});
$("#contact-form").submit(function(e){
e.preventDefault();
$('.loading').addClass("d-block");
var name = $("input[name=name]").val();
var email = $("input[name=email]").val();
var subject = $("input[name=subject]").val();
var message = $("input[name=message]").val();
$.ajax({
type:'POST',
url:"{{route('contact.store')}}",
data:{name:name, email:email, subject:subject, message:message},
success:function(data){
$('.sent-message').addClass("d-block");
$('.sent-message').text(data.success);
//$('#contact-form').trigger("reset");
},
complete: function(){
$('.loading').removeClass("d-block");
},
error:function(data){
$('.error-message').addClass("d-block");
$('.error-message').text(data.error);
}
});
});
});

Input values are null in controller(ASP.Net MVC) using ajax

In my Login Page I want to show error message when user enter wrong email and password without refreshing page. I am trying to send data from view to controller using ajax. But in the controller, user.Email and user.Password are null when I debug, but the Ajax call works. I want to know what is wrong there?
<div class="login-container">
<div class="row">
<div class=" col-md-12 col-sm-12 col-12 login-form-1">
<h2>Login</h2>
<p>Log into your account</p>
#using (Html.BeginForm("Login", "Account", FormMethod.Post))
{
<div id="alertmessage">
<div class=" alert alert-danger">
<span>
Email or Password is incorrect
</span>
</div>
</div>
#Html.AntiForgeryToken()
<div class="form-group col-md-12 col-sm-12 col-12">
<input id="Email" type="text" class="form-control" placeholder="Your Email *" value="" name="Emaillog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12 ">
<input id="Password" type="password" class="form-control" placeholder="Your Password *" value="" name="Passwordlog" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12">
<input type="submit" class="btnSubmit" value="Login now" id="logbut" />
</div>
<div class="form-group col-md-6 col-sm-6 col-6">
Forget Password?
</div>
}
</div>
</div>
</div>
$(document).ready(function () {
$("#alertmessage").hide()
$("#logbut").click(function (e) {
e.preventDefault();
// collect the user data
var data = {};
data.Email = $("#Email").val();
data.Password = $("#Password").val();
var token = $('input[name="__RequestVerificationToken"]').val();
$.ajax({
url: "/Account/Login",
type: "POST",
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
data: {
model: data,
__RequestVerificationToken: token,
returnUrl: "Account/Login" // you can modify the returnUrl value here
},
success: function (result) {
if (result == "Fail") {
$("#alertmessage").show()
}
else {
window.location.href = "/Account/MainAccount";
}
},
})
})
})
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(User user)
{
string result = "Fail";
User appUser = _context.Users.FirstOrDefault(u => u.Email == user.Email);
if (appUser != null)
{
if (appUser.Password ==user.Password)
{
Session["ActiveUser"] = appUser;
return RedirectToAction("MainAccount");
}
}
return Json(result, JsonRequestBehavior.AllowGet);
}
How can I solve this problem?
Instead of using User Model in MVC action, use parameters in
Login(string email, string password)
And in Ajax pass
data:
{
email : email,
password : password,
__RequestVerificationToken: token
}
Can you please try this.
Note: you model class property same as inside form control name
Like example
UserName
Password
In you example
you are sending a request using ajax but your button type is submit when you click on button two requests come in server one is ajax and the second one is form.
Please see this example.
<div class="login-container">
<div class="row">
<div class=" col-md-12 col-sm-12 col-12 login-form-1">
<h2>Login </h2>
<p>Log into your account</p>
#using (Html.BeginForm("Login", "Account", FormMethod.Post,new {id="LoginFrom" }))
{
<div id="alertmessage">
<div class=" alert alert-danger">
<span>
Email or Password is incorrect
</span>
</div>
</div>
#Html.AntiForgeryToken()
<div class="form-group col-md-12 col-sm-12 col-12">
<input id="Email" type="text" class="form-control" placeholder="Your Email *" value="" name="Email" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12 ">
<input id="Password" type="password" class="form-control" placeholder="Your Password *" value="" name="Password" />
</div>
<div class="form-group col-md-12 col-sm-12 col-12">
<input type="button" class="btnSubmit" value="Login now" id="logbut" />
</div>
<div class="form-group col-md-6 col-sm-6 col-6">
Forget Password?
</div>
}
</div>
</div>
</div>
Jquery Code
$(document).ready(function () {
$("#alertmessage").hide()
$("#logbut").click(function (e) {
$.ajax({
url: '#Url.Action("Login","Account")',
type: "POST",
data: $("#LoginFrom").serialize(),
success: function (result) {
if (result == "Fail") {
$("#alertmessage").show()
}
else {
window.location.href = "/Account/MainAccount";
}
},
})
})
})
For more detail -> check this link https://www.w3schools.com/jquery/ajax_serialize.asp

Form submit with a file in Spring mvc + bootstrap

Its a two part question.
I am trying to submit a pop up form with a file and textarea. I am not able to receive file in my controller code.
Part 1 - How do I receive the file at the controller.
Part 2 - Once I submit the form, how do I close the popup and remain on the same page so that URL does not change.
Popup code-
<form name="eperform">
<div class="modal fade" id="export" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">
<span class="glyphicon glyphicon-remove" aria-hidden="true" style="padding-top: 10px;"></span>
</button>
<h4 class="modal-title custom_align" id="Heading">Provide ID's here:</h4>
</div>
<div class="form-group">
<div>
<fieldset style="margin-left: 10px;">
<legend style="font-size: medium;">File Upload</legend>
<input id="fileUpload" name="fileUpload" type="file" style="margin-left: 20px"/>
</fieldset>
</div>
<br/>
<div>
<fieldset style="margin-left: 10px;">
<legend style="font-size: medium;">Ids</legend>
<label for="envIds"></label>
<textarea class="form-control noresize" rows="4" style="width:98% " name="ids" id="ids" value="">
</textarea>
<input type="hidden" id="server" name="server" value="${server}">
<input type="hidden" id="port" name="port" value="${port}">
<input type="hidden" id="queuename1" name='queuename1' value="">
<input type="hidden" id="environment" name="environment" value="${environment}">
</fieldset>
</div>
</div>
<div class="modal-footer ">
<button type="button" class="btn btn-success" id="eid"
onclick="exportObjects(document.getElementById('ids').value,document.getElementById('queuename1').value,'${port}','${server}','${environment}',document.getElementById('fileUpload').value)">
<span class="glyphicon glyphicon-ok-sign"></span>Export
</button>
<button type="button" class="btn btn-default" data-dismiss="modal">
<span class="glyphicon glyphicon-remove"></span> Cancel
</button>
</div>
</div>
</div>
</div>
</form>
Javascript code-
function exportObjects(ids, queueName, port, server, environment, fileUpload) {
var strHREF = "/exportObjects?ids=" + ids
+ "&queueName=" + queueName + "&port=" + port + "&server="
+ server + "&environment=" + environment +"&fileUpload=" + fileUpload;
document.eperform.action = strHREF;
document.eperform.submit();
}
Controller code-
#RequestMapping(value="/exportObjects", method = RequestMethod.GET)
public ModelAndView exportObjects(HttpServletRequest request) throws Exception{
String server =request.getParameter("server");
String port =request.getParameter("port");
String environment = request.getParameter("environment");
String type =request.getParameter("queueName");
String ids = request.getParameter("ids");
CommonsMultipartFile file = (CommonsMultipartFile) request.getAttribute("fileUpload");
if(file != null && file.getSize() != 0){
String path=request.getServletContext().getRealPath("/");
String filename=file.getOriginalFilename();
System.out.println(path+" "+filename);
try{
InputStream in = file.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString());
}catch(Exception e){System.out.println(e);}
}
// Perform action on ids and file data
ModelAndView model = new ModelAndView();
// I do not know what to do here.
return model;
}
It seems that you are not familiar with web developement,I recommend you take some time to review the java web development knowledge.
Below are the answer for your two questions:
If you want to upload a file to the server,you must add enctype="multipart/form-data" to your form
<form name="eperform" enctype="multipart/form-data">
<div>
<fieldset style="margin-left: 10px;">
<legend style="font-size: medium;">File Upload</legend>
<input id="fileUpload" name="fileUpload" type="file" style="margin-left: 20px"/>
</fieldset>
</div>
</form>
If you want to stay on the same page,you should using an asynchronous method to submit your action,and Ajax is your best choice.You need to submit your request and in the success callback method close the popup dialog.
$.ajax({
url:"exportObjects",
type:"post",
data:{
queueName:queueName,
port:port,
server:server,
environment:environment
},
success:function(data){
//if the request submit success,invoke 'close' method to close the dialog
$("#dialog_div").dialog("close");
}
});
In your springmvc code,you should not use ModelAndView because it will forward to a new page,you need to return an original string,like the code listed below,after that you can use MultipartFile to get your upload file:
#RequestMapping(value="eperform",method=RequestMethod.POST)
#ResponseBody
public String updateNodeRelation(#RequestParam(value="fileUpload")
MultipartFile file,HttpServletRequest request) {
System.out.println(file.getOriginalFilename());
return "success";
}
UPDATED
If you want to submit a file and then stay on the same page,then you need to use iframe and not use Ajax,as below:
<!-- using iframe to stay on the same page-->
<form id="eperform"name="eperform" action="exportObjects" enctype="multipart/form-data"
target="hidden_frame">
<div>
<fieldset style="margin-left: 10px;">
<legend style="font-size: medium;">File Upload</legend>
<input id="fileUpload" name="fileUpload" type="file"
style="margin-left: 20px"/>
</fieldset>
</div>
<iframe id="hidden_frame" name="hidden_frame"
style="display:none"/>
<button type="button" onclick="submitFile()">Submit</button>
</form>
And using the below Javascript code to submit the form and close popup dialog**
function submitFile(){
$("#eperform").submit();
$("#dialog_div").dialog("close");
}

Cannot submit a form on SpringMVC

I am fairly new to SpringMVC and have a form that can not submit to the back-end. I created the form as following and when I submit it error 404 will be returned. I changed action to /MyProject/contact but did not work.
<form class="form-horizontal" role="form" method="post"
action="/contact">
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Name
</label> <input type="text" class="form-control" id="name"
name="name" placeholder="Your name" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Email
Address</label> <input type="email" class="form-control" id="email"
name="email" placeholder="Your email" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Phone
Number</label> <input type="number" class="form-control" id="phone"
name="phone" placeholder="Phone number" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Enquiry</label>
<textarea class="form-control" rows="4" name="message"
placeholder="Please enter your enquiry"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-2 " style="float: right;">
<input id="submit" name="submit" type="submit" value="Send"
class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
Controller
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
Error
HTTP Status 404 - /contact
type Status report
message /contact
description The requested resource is not available.
Its beacuse spring does not know how to pass the param Contact contact to your controller method. You need to do couple of things to make it work. Change your form to like below.
<form class="form-horizontal" role="form" method="post" modelAttribute="contact" action="/contact">
Your controller to take contact as model attribute.
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(#ModelAttribute Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
For a better understanding of what a model attribute does, there are plenty of samples and explanation online. Hope this helps.
I could solve the problem by help of minion's answer, following this tutorial and adding following link
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public ModelAndView contactForm() {
System.err.println("here in GET");
return new ModelAndView("contact", "command", new Contact());
}

Resources