Use ajax to submit form and receive info from a servlet - javascript

I am developing a webapp using java and currently i need to to send information from a form to a servlet and send feedback back to the html page from the servlet. Specifically when a user connects i want to return from the servlet the username and password of all the users in my database
From what I 've searched the only way to do this properly is by using ajax, but i can't seem to be able to make it work.
Snippet from html page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="form" method="post" action="signIn">
<input id="uname" name="uname" class="form-control" type="text">
<input id="pass" name="pass" class="form-control" type="password">
<input id="button1" class="btn btn-primary" type="submit" value="Sign In" />
</form>
<div id=result></div>
My servlet (SingIn.java) currently looks like this
public class SignIn extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String uname = request.getParameter("uname");
String pass = request.getParameter("pass");
Registration.setOnline(uname);
try {
// loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
// creating connection with the database
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ted", "root", "root");
PreparedStatement ps = con.prepareStatement("select * from user");
ResultSet rs = ps.executeQuery();
out.println("<table>");
while (rs.next()) {
uname = rs.getString(1);
pass = rs.getString(2);
out.println("<tr><th>" + uname +"</th><th>"+ pass + "</th></tr>");
}
out.println("</table>");
} catch (Exception e) {
e.printStackTrace();
}
RequestDispatcher res = request.getRequestDispatcher("html/index.html");
res.include(request, response);
}
}
Part of my web.xml looks like this
<servlet-mapping>
<servlet-name>SignIn</servlet-name>
<url-pattern>/signIn</url-pattern>
</servlet-mapping>
As it is i can access the servlet and have the form info submitted, but the servlet's response shows up at the top of the page, whereas i need it to be shown in the "result" div.
I think it's best to use ajax and javascript but i really need help on this part
Update
Currently i am trying something like this in ajax
$(document).ready(function() {
// Add an event that triggers when the submit
// button is pressed.
$("#button1").click(function() {
// Get the text from the two inputs.
var uname = $("#uname").val();
var pass = $("#pass").val();
// Ajax POST request.
$.post('signIn',{"uname": uname, "pass": pass},
function() { // on success
$(#result).innerHTML=(not sure what);
});
});

Your JavaScript call should look like this:
// Ajax POST request.
$.post('./signIn',
{"uname": uname, "pass": pass},
function( data ) { // on success
$( "#result" ).html( data );
});
Or more clearly:
// Ajax POST request.
$.ajax({
type: 'POST',
url: './signIn',
data: {"uname": uname, "pass": pass},
success: function( data ) {
$( "#result" ).html( data );
}
});

Related

Get result back after form submit

I need a quick help.
I want users can upload a csv file. Then I do some parsing and meaningful things with the file in the back. Finally, display the results back to users. When they upload the file, I would like to check to see if the file size is <= 250kb or contains <= 1000 lines.
In JSP:
<form action="/Project/CSVUpload" method="post" enctype="multipart/form-data">
<br />
<input id="uploadfilebutton" type="file" name="file" class="tss-btn tss-btn-blue" accept=".csv" required />
<br />
<input id="processfilebutton" type="submit" value="Process File" class="tss-btn tss-btn-blue" />
</form>
So there is an upload button and a submit button. How can I get a status back after users click the submit button? For example, if the process fails I want to display an pop up error message.
In JavaScript:
function process()
{
$.ajax({
url:"/Project/CSVUpload",
type:'POST',
contentType: 'application/json',
dataType: 'json',
success:function(soapContents){
if (soapContents.haserrors)
{
BootstrapDialog.show({
title: 'Process File Failed',
message: soapContents.returnmessage,
buttons: [ {
label: 'Ok',
action: function(dialogItself){
dialogItself.close();
}
}]
});
}
}
});
}
This works when I don't use form. The form is required because enctype has to be like that.
In Java:
#WebServlet("/CSVUploads")
public class CSVUpload extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException
{
boolean hasErrors = false;
if (CSVUpload success) // assume we get the info from CSVUpload class
{
hasErrors = true;
}
if (hasErrors)
{
log.error("CSVUpload: "+returnMessage);
// Setup JSON response.
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("haserrors", hasErrors);
jsonObjectBuilder.add("returnmessage", returnMessage);
JsonObject jsonObject = jsonObjectBuilder.build();
// Write the JSON out as a response.
PrintWriter printWriter = response.getWriter();
printWriter.print(jsonObject);
printWriter.flush();
}
}
So I made some changes and add a new java class to handle the ajax query... it submits twice, first submit is getting the form info and second submit is checking for a success... I don't know if anyone has better idea, but this is what I change to make it work. It sounds not a good idea, but it works for now. If anyone has better idea please let me know, a working sample will be great.
Use button instead of submit. It is because submit type input is submitting the form, but you also send request using ajax. That's the reason of two requests.

How do i submit form via ajax?

i'm trying to submit forms without post back via ajax ..my code doesn't work
whats wrong in my script?
i'm new to ajax..help me with ajax scripts..
below is my code
note: i have two submit buttons with in single view. I want to make ajax call for both submit actions
my view
#model AjaxEF.Models.Customer
#using (Html.BeginForm("Index", "Main", FormMethod.Post,new { id="idForm"}))
{
#Html.EditorForModel()
<br />
<input type="submit" name="save" value="Save" />
<input type="submit" name="cancel" value="Cancel" />
}
<script>
$("#idForm").submit(function (e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var url = "~/Main/Result"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function (data) {
alert(data); // show response from the php script.
}
});
});
</script>
my controller
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(Customer obj, string save, string cancel)
{
if (!string.IsNullOrEmpty(save))
{
ViewBag.Message = "Customer saved successfully!";
}
if (!string.IsNullOrEmpty(cancel))
{
ViewBag.Message = "The operation was cancelled!";
}
return View("Result", obj);
}
public ActionResult Result()
{
return View();
}
Not sure why the other answer was deleted, but it was 100% correct. The URL you're hitting with your AJAX is your Result action, which does nothing but return a view. You need to post to your Index action, and since the form is already set to post there, the best way to get that URL for your AJAX is to select it from the form:
var url = $('#idForm").attr("action");

Why is my html form clearing the page contents after ajax?

The code should work something like this...
https://jsfiddle.net/Harout360/yhqoadqx/7/
But instead the form post does get correctly processed, then it redirects to the "/" url given as the action url in ajax. I can't figure out why it is redirecting, and if I place a console.log in the ajax it doesn't print to console.
HTML
<form method="post">
<input type="hidden" name="title" value="${title}" />
<button type="submit" value="Submit" id="sub-button" data-loading-text="Loading..." data-complete-text="Submitted!">
Submit
</button>
</form>
Javascript
$(document).ready(function() {
$("button[id=sub-button]").click(function(e){
e.preventDefault();
var button = $(this);
var form = $(this.form);
var form_data = form.serialize();
var form_method = form.attr("method").toUpperCase();
console.log('subscribing...');
$.ajax({
url: "/",
type: form_method,
data: form_data,
success: function(){
button.button('complete');
}
});
});
});
Java Servlet
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
String title = req.getParameter("title");
Database.addTitle(title);
}
UPDATE
The Javascript works now because my problem was assigning the function to buttons that didn't exist at the time that document.ready loaded. Instead I now assign the .click to the button when it was actually loaded onto the page. Also I changed button's type to button, removed the id and now use $(.movie) to identify the button by its class.
Updated fiddle to give slight understanding of new approach https://jsfiddle.net/Harout360/yhqoadqx/11/
New Issue
Now the problem is that button.button('complete') is not doing anything. Any guesses as to why?
UPDATE 2 (Solution to new issue)
setTimeout(function() { button.button('complete'); }, 500);

how can i modify a freemarker variable value inside a success block in jQuery AJAX

how can i change a value of a freemarker variable inside a success block in jQuery AJAX, i have two controllers for my page the first one returns me a simple string with the name of the view with a GET method, the second one is the one that process the data using a json with a POST method
here they are
#RequestMapping(value = "myform", method = RequestMethod.GET)
public String formmethod(Model model) {
model.addAttribute("successMessage", "i'm in the firts controller");
return "forms/myform";
}
my second controller
#RequestMapping(value = "myform", method = RequestMethod.POST)
public #ResponseBody String getTags(#RequestBody final String json, Model model)
throws IOException
{
ObjectMapper mapper = new ObjectMapper();
User userMapped= mapper.readValue(json, User.class);
User person = new Usuario();
person.setName("new name");
person.setLastName("new lastname");
model.addAttribute("successMessage", person.getName());
return toJson(userMapped);
}
my to Json method
private String toJson(User person)
{
ObjectMapper mapper = new ObjectMapper();
try
{
String value = mapper.writeValueAsString(person);
// return "["+value+"]";
return value;
}
catch (JsonProcessingException e)
{
e.printStackTrace();
return null;
}
}
and my page myform.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
function doAjaxPost()
{
// get the form values
var name= $('#name').val();
var lastName = $('#lastName ').val();
var json = {"name" : name, "lastName " : lastName };
console.log(json);
var FreeMarkervariable = "${successMessage}";
//this brings me the value that i put in the firts controller
$.ajax(
{
type: "POST",
url: "myform",
data: JSON.stringify(json),
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
beforeSend: function(xhr)
{
xhr.setRequestHeader("Accept", "application/json");
xhr.setRequestHeader("Content-Type", "application/json");
},
success: function(data)
{
//HERE I WANT TO CHANGE THE VALUE OF MY FREEMARKER VARIABLE SO I CAN
//PRINT A SUCCESS MESSAGE IN A DIV
<#assign successMessage = "success">
},
error:function(data,status,er) {
alert("error: "+data+" status: "+status+" er:"+er);
}
});
}
</script>
<!-- NEW WIDGET START -->
<article class="col-sm-12">
<div class="alert alert-warning fade in">
<button class="close" data-dismiss="alert">
×
</button>
<i class="fa-fw fa fa-warning"></i>
<strong>${successMessage} I WANT TO PRINT A SUCCESS MESSAGE HERE </strong>
</div>
</article>
<!-- WIDGET END -->
<fieldset>
<legend>Name in view</legend>
<form name="myform">
Name in view: <input type="text" name="name">
<br>
Last Name in view: <input type="text" id="lastName" name="lastName">
<br>
<input type="button" value="Add Users" onclick="doAjaxPost()">
</form>
</fieldset>
<br>
so far my freemarker variable gets the value that i put inside the success block but it appears "success" before i press my submit button, i believed that the succes block was executed after i hit the submit button so i dont know why it have the value even before i press the button it should have "i'm in the firts controller" before i press the submit button
Freemarker generates it's output on the server and this is then sent to the browser. The browser never sees any of the freemarker 'code'. You need to update the strong element using javascript/jQuery.
So instead of your <#assign...> use something like this
$("strong").text("Success");

Sending Data from HTML to Servlet by two different methods

I've been sending data from HTML to my servlet like this :
<form Action="http://caregap2.appspot.com/src.main.java.org.deri.hcls.caregap2.client" Method="GET">
Username: <input type="text" name="username" size="20" value="#gmail">
<BR>
<input type="submit" VALUE="submit">
<input type="reset" value="reset">
</form>
which sends the variable Username to the servlet. But I don't want to have click submit to send the data, I would like to just post the data and load the servlet without clicking anything. I've tried this :
$(document).ready(function() {
var username = "matthewgortnalon#gmail.com";
$.ajax({
type: "POST",
url: "http://caregap2.appspot.com/src.main.java.org.deri.hcls.caregap2.client",
data: { username: "username" }
}).done(function( msg ) {
// alert( "Data Saved: " + username );
window.location = "http://caregap2.appspot.com/src.main.java.org.deri.hcls.caregap2.client?q=" + username;
});
});
But it doesn't work, can anyone see what I'm doing wrong?? Or if I should use a different method? Help would be really appreciated!! :)
Here's my servlet method :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");{
ServletOutputStream out = response.getOutputStream();
try {
out.println("<html><head><title>" + "</title></head>");
out.println("<body><h1>" + "</h1>");
String name = request.getParameter("username" );
//String comment = request.getParameter( "comment" );
out.println("Name:" + name + "<BR>");
//out.println("Comment: " + comment + "<BR>");
}
catch(Throwable t ) {
out.println("<P><pre>");
t.printStackTrace( new PrintStream(out) );
out.println ("</pre><P>");
}
out.println ("</body></html>");
}
Your JSON data is wrong:
data: { "username": username }
First the key, than the value (variable)
Ok I think I know what it is you are tryng to do. AJAX requests are not what you want. From my understanding you are trying to load a servlet and display it without havign to interact with your page at all.
All you need to do is in javascript do the following
var username = "you username here";
window.location = "http://caregap2.appspot.com/src.main.java.org.deri.hcls.caregap2.client?username=" + username;
Using an ajax request will return the servlet body to the done method, this would be useful for displaying the information on the current page without reloading.
What you are currently doing is appending the servlet response body to the end of your query and as such redirecting to the wrong place.
Extra Info: The alternative using Ajax would be to get your servlet to return some html but not necesserily a full page, then use this response to populate part of your current page.
It seems your form is using a GET request and your ajax is performing a POST request. It is probable that your service is looking for GET parameters. Change the ajax request to use GET instead of POST

Categories

Resources