Im new to AJAX/JQuery, and I'm wondering if there is a way to send, via an AJAX request, data from an HTML form that includes a text file, and 2 separate text boxes. I have been able to send the data from the text boxes, but the file is not sent.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
// this is the id of the form
$("#SQLsubmit").submit(function() {
var url = "DAOserv"; // the script where you handle the form input.
$.ajax({
type : "POST",
url : url,
data : $("#SQLsubmit").serialize(), // serializes the form's elements.
success : function(data) {
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
This is my AJAX call^
<div class="row">
<form id="SQLsubmit" name="SQLsubmit">
<div class="form-group col-lg-4">
<textarea rows="11" id="BAU" name="BAU" class="form-control"
placeholder="BAU Reason" form="SQLsubmit"></textarea>
<input type="file" name="file" /> <input type="submit"
class="btn btn-primary" value="Submit">
</div>
<div class="form-group col-lg-8">
<textarea rows="11" id="SQL" name="SQL" class="form-control"
placeholder="SQL Statements" form="SQLsubmit"></textarea>
</div>
</form>
Here is the HTML.
If anyone could show me how to get the two text files, and the file into my Java Servlet (using the doPOST method), so I am able to parse all into strings, that would be greatly appreciated!
Thanks!
edit: The problem I am having when running the code in the original post is that the text fields get sent, but the file is not being sent.
You should define enctype: 'multipart/form-data. Otherwise how jquery should know you are sending a file.
This link might help:
How can I upload files asynchronously?
Have you tried
$("#SQLsubmit").submit(function() {
var url = "DAOserv"; // the script where you handle the form input.
$.ajax({
type : "POST",
url : url,
data : new FormData(this),
success : function(data) {
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Related
I have a web application with HTML and JQuery, in which it has a login form. When I click the submit button I am using ajax to send the data using Post request to a web service.
The web service is built with Java.
Here is my html form:
<form id="mdxLogin" action="" method="post">
<div class="ui-content">
<p><input type="email" id="mdxEmail" name="mdxEmail" class="ui-field-contain" value="" placeholder="MDX Email" /> </p>
<p><input type="password" id="mdxPassword" name="mdxPassword" class="ui-field-contain" value="" placeholder="MDX Password" /></p>
</div>
<div class="ui-content">
<input type="submit" class="ui-field-contain" value="Login" id="sub"/>
</div>
</form>
The below is my Ajax code to post to my web service
$("#mdxLogin").submit(function(e) {
e.preventDefault();
var mdxEmail = $("input[name=\"mdxEmail\"]").val();
var mdxPassword = $("input[name=\"mdxPassword\"]").val();
$.ajax({
type: "POST",
url:"http://localhost:8080/RestService/rest/loginService/login",
dataType:"json",
data: $("#mdxLogin").serialize(),
success: function(data, textStatus, jqXHR) {
// handle your successful response here
alert(data);
},
error: function(xhr, ajaxOptions, thrownError) {
// handle your fail response here
alert("Error");
}
});
})
And the below is the method in my web service
#POST
#Path("/login")
#Produces(MediaType.TEXT_PLAIN)
public String login(#FormParam("mdxEmail") String mdxEmail, #FormParam("mdxPassword") String mdxPassword) {
System.out.println(mdxEmail);
DBStudent s = new DBStudent();
String url = null;
if (s.checkLogin(mdxEmail, mdxPassword)) {
url = s.getCalendar(mdxEmail, mdxPassword);
}
return url;
}
So far what I managed to do is to post the data to my web service but didn't get any response. My question is how can I access the returned url from my web service with Ajax?
In your code I spot one error which should prevent it to work properly.
In the client side you're saying to jQuery that the expected type is JSON, but the server produces a string, in your case a URL, which is not JSON.
Therefore jQuery when tries to parse the data received fails because it's not JSON data. This mistake should trigger the jQuery error block.
Apply just this change in the client:
dataType:"text"
If you want to test your code without worrying about the Same Origin Policy you can disable it, look at these threads
Disable firefox same origin policy
Disable same origin policy in Chrome
I got to know somewhat about Angular JS. I have watched this tutorial, but just basic only. I want to try out it in my Java application. I searched for a demo, but I don’t get any idea. So I am asking here.
I have Java entity baean model class called User, now it has just two fields.
String name;
String password;
I have service classes and daos for that to save data to a database using hibernate.
Now I want to try angularjs. I haven’t created any action class.
Here is the form in my HTML page
index.html
<div ng-app class="container">
<form class="form-signin" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<input type="text" class="input-block-level" placeholder="User name" required ng-model="name" name="name">
<input type="password" class="input-block-level" placeholder="Password" required name="password" ng-model="password">
<br>
<label class="checkbox">
<input type="checkbox" value="remember-me"> Remember me
</label>
<button class="btn btn-large btn-primary" type="submit">Sign in</button> or Signup
</form>
How can I use Angularjs to get the data and call action class? Based on success or error, how can I redirect to a success or error page?
Can someone give some idea(sample code) or some demo link(get some java object from HTML page, pass to java class redirect to some page based on return)? Because I don't find anyone. I want to learn how to use AngularJS using Java.
I give you an example from one of my project, hopefully it will point you in the right direction, basically you have to use $http in your factory/service:
(function() {
'use strict';
angular.module('app').factory('myService', myService);
function myService($http, config) {
var service = {
postData : postData
}
function postData(param) {
return $http.post(config.apiUrl + '/api/postData', param)
.then(function(result) {
return result;
});
}
return service;
}
})();
Don't worry about the config and config.apiUrl - thats basically = "http://localhost:8080/" + your api url ex. getData/postData etc. You just put your full URL $http.post('http://localhost:8080/api/postData', param). If you don't want to pass parameter just leave the param part out.
Or if you want a simple one that you can call directly from your controller:
$scope.postData = function(){
$http({
method: "POST",
url: "http://localhost:8080/api/postData",
data: $scope.data
}).then(function(response){
console.log(response);
if(response.data.success){
// do your stuff...
} else if(response.data.error) {
// or do this stuff...
}
});
}
The data object $scope.data will hold your username and password:
$scope.data.username = "username";
$scope.data.password = "password";
I am trying to find a way to invoke a piece of java code within the JSP using HTML form
<form method="get" action="invokeMe()">
<input type="submit" value="click to submit" />
</form>
<%
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
the above code is within the JSP. I want this run the scriptlet upon submit
I know the code looks very bad, but I just want to grasp the concept... and how to go about it.
thanks
You can use Ajax to submit form to servlet and evaluate java code, but stay on the same window.
<form method="get" action="invokeMe()" id="submit">
<input type="submit" value="click to submit" />
</form>
<script>
$(document).ready(function() {
$("#submit").submit(function(event) {
$.ajax({
type : "POST",
url : "your servlet here(for example: DeleteUser)",
data : "id=" + id,
success : function() {
alert("message");
}
});
$('#submit').submit(); // if you want to submit form
});
});
</script>
Sorry,not possible.
Jsp lies on server side and html plays on client side unless without making a request you cannot do this :)
you cannot write a java method in scriptlet. Because at compilation time code in scriptlet becomes part of service method. Hence method within a method is wrong.
How ever you can write java methods within init tag and can call from scriptlet like below code.
<form method="get" action="">
<input type="submit" value="click to submit" />
</form>
<%
invokeMe();
%>
<%!
private void invokeMe(){
out.println("He invoked me. I am happy!");
}
%>
Not possible.
When the form is submitted, it sends a request to the server. You have 2 options:
Have the server perform the desired action when the it receives the request sent by the form
or
Use Javascript to perform the desired action on the client:
<form name="frm1" action="submit" onsubmit="invokeMe()"
...
</form>
<script>
function invokeMe()
{
alert("He invoked me. I am happy!")
}
</script>
You can't do this since JSP rendering happens on server-side and client would never receive the Java code (ie. the invokeMe() function) in the returned HTML. It wouldn't know what to do with Java code at runtime, anyway!
What's more, <form> tag doesn't invoke functions, it sends an HTTP form to the URL specified in action attribute.
How to get values from a text box and display in a url in jsp
Use method="get" for your form and the values will automatically go into the URL when you submit the form.
<form action="youraction.jsp">
<input type="text" id="nameOfPerson"/>
<input type="submit" />
</form>
by default form's action is GET , it will append param of form to URL.
So on clicking submit button you will get url something like
youraction.jsp?nameOfPerson=valueEntered
Here's the code:
<script>
var url = window.location.href
</script>
<input onkeyup='window.location.href=url + "#" + this.value'>
I defined a modelview object named "buttonpressed" in spring controller file and I need to access that modelview object in ftl(freemarker) file which is being returned as a view from a controller like abcd.java
The abcd.java controller code is as below
if (questionAnswer.getAnswerId() == 1045)
{
modelAndView.addObject("buttonPressed","You have been added in mailing list");
modelAndView.setViewName("enterCode_nextSteps");
}
else
{
modelAndView.addObject("buttonPressed","Not added in the mailing list");
modelAndView.setViewName("enterCode_nextSteps");
}
the below ajax function is working fine currently but I am not sure how to access this object called "buttonpressed" in this ajax function. I have written like the way mentioned below but when i am clicking the submit link its not calling "partner.do" and also throwing error saying #buttonPressed is undefind (but in the script below its working fine and calling "partner.do" and even posting data)
So is that problem coming from javsscript code i mean due to incorrect use of
"buttonPressed" or might be problem from spring controller abcd.java file.
<div class="partnerOptInBox">
<div id="optInContent">
<form name="partnerOptIn">
<h4>Want the Latest</h4>
<p class="pad10Top">${partnerOpt.translation}</p>
<div class="pad10Top">
<input type="radio" name="questionAnswer['${partnerOpt.questionId}']" value="${partnerOpt.getAnswers()[0].answerId}" class="radioButton" /> <label for="questionAnswer['${partnerOpt.questionId}']" class="formLabel pad20Right">Yes</label> <input type="radio" name="questionAnswer['${partnerOpt.questionId}']" class="radioButton" value="${partnerOpt.getAnswers()[1].answerId}" /> <label for="questionAnswer['${partnerOpt.questionId}']" class="formLabel">No</label>
</div>
<div id="optInError" class="formError" style="display:none;">Oops... your request did not go through, please try again.</div>
<div class="pad15Top">
<img src="images/theme/btn_opt_in_submit.gif"/>
</div>
</form>
<script type="text/javascript">
function submitOptIn() {
$('optInError').hide();
dataString = $('#partnerOptIn').serialize();
$.ajax({
data: dataString,
url: "partnerOpt.do",
timeout: 30000,
type: "POST",
success: function(html){
var newHtml = "<h4>Thank you</h4><p>We appreciate your time to respond to our request.</p>";
$('#optInContent').html(newHtml);
},
*/trying this code for sucess is throwing me an error /*
<!-- buttonpressed function-->
success: function(html){
$('#optInContent').html(${buttonPressed});
},
<!-- buttonpressed function-->
error: function(){
$('#optInError').show();
}
});
}
</script>
Assuming the HTML code shown is part of the view in which model from abcd.java is accessible, you need to enclose ${buttonPressed} in quotes when you're invoking $('#optInContent').html() on it because it's a string.
Or if it doesn't work then you can output as javascript variable on the top of the page
and read later using DOM,
var buttonpressed = ${buttonPressed}, but i think above solution will work. But generally this approach works best if you have lot of javascript work in a page and needs backend data
and you don't want to do AJAX calls.