Get result back after form submit - javascript

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.

Related

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);

Save form inputs to txt, popup result, no page changing

I would like to build a newsletter subscription function to my website. and I want to get all the input save into a txt file in the host folder. However, I don't want to switch page after people submit it. Just show a popup message saying "Thank You for Subscribing" will be perfect. I know how to do it with PHP to show a message in a separate page, but not sure how to do it in a popup box. Here is my html and PHP code. Please help, thanks a lot.
<html>
<head>
<title></title>
</head>
<body>
<form>
<form action="myprocessingscript.php" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Text file</a>
</body>
PHP function is
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
Once you have included jQuery to your page, something like following should work:
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'field1' : $('input[name=field1]').val(),
'field2' : $('input[name=field2]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myprocessingscript.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// data is the output from your php, check it and display alert appropriately
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Take a look at source article

Form not submitting file / Undefined index: FileInput - PHP/AJAX/jQuery

I am trying to use jQuery to trigger a form submission and then use AJAX to call a PHP script that will handle the file and return a response. The issue, though, is that the file is not being uploaded upon submitting the form.
HTML:
<div id="browseButton" class="step1Button" onclick="browseFile()">Browse</div>
<form method="post" id="fileForm" style="display:inline-block;">
<input id="browseInput" type="file" name="FileInput" style="display: none"/>
<label for="upload-click-handler"></label>
<input id="upload-click-handler" type="text" readonly />
<input id="submitForm" type="submit" style="display: none"/>
</form>
<div id="previewButton" class="step1Button pull-right" onclick="uploadFile()" style="background-color: #57a957">
Preview
</div>
jQuery:
function uploadFile() {
submitForm();
parseExcel();
}
var submitForm = function() {
$('#previewButton').click(function(){
$('#submitForm').click();
});
};
var parseExcel = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET",'default/ParseExcel',true);
xmlhttp.send();
console.log("made it past excel parse");
};
The PHP that's called:
public function actionParseExcel() {
print "made it to parse".PHP_EOL;
print "File:";
if($_FILES['FileInput']['tmp_name']) {
print_r($_FILES['FileInput']['tmp_name']);
}
else {
print "Not found";
}
print "Done.";
}
I know the issue is that my form isn't submitting the chosen file because that's typically why the "Undefined index" error is thrown. But I can't understand why.
First, if you don't want your page to refresh, you better use <input type="button">
or else call your JavaScript via <form onSubmit="uploadFile()"> and return false at the end of your function uploadFile().
Second, you'll need to put enctype="multipart/form-data" in your <form>.
I see you're using JQuery, you should use it to send your AJAX request too :
// This code supports multiple type="file" inputs
// Variable to store your files
var files;
// Add events
$('input[type=file]').on('change', prepareUpload);
// Grab the files and set them to our variable
function prepareUpload(event)
{
files = event.target.files;
}
// Create a formdata object and add the file
var data = new FormData();
// In case you want to upload more than one file
$.each(files, function(key, value)
{
data.append(key, value);
});
$.ajax({
url: 'your.php?FileInput',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Prevent the file from beeing converted to string
contentType: false, // Set the content file to false prevent JQuery from using 'application/x-www-form-urlencoded; charset=UTF-8' as default type
...
});
I hope this will lead you to the solution...
Edited : var files declaration + files processing
To send forms with files you need to use enctype="multipart/form-data".
BUT, as far as I know, you can't send files using ajax.
So, the solution for that is to use a hidden iFrame:
Create a hidden iFrame (outside of your form) and assing it an ID
Create the form pointing to yout PHP file, and using the attribute enctype="multipart/form-data" and target="ID_OF_THE_IFRAME" (so the form, when submitted, will be sent to that iframe)
When the PHP finish procesing the file, you could output a javascript that calls parent.YOURFUNCTION(), so you can do whatever you want when the process is done.
Good luck!

post method not working

I want to submit form data using post using ajax because in form post after submit it is redirected to a new page.
<form id="myContactForm">
<p>
<label for="byour_name">Your name</label><input type="text" name="byour_name" value="" id="byour_name">
</p>
<p>
<label for="byour_email_address">Your email address</label><input type="text" name="byour_email_address" value="" id="byour_email_address">
</p>
<p>
What's on your mind?<br>
<textarea name="Message" rows="10" cols="25"></textarea>
</p>
<p>
<input type="submit" value="Send it!" onClick="sendMail()">
</p>
</form>
function sendMail() {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),
success: function( response) {
alert(response);
},
error: function() {
alert('failure');
}
});
}
Every time I make request error function is executing.I am writing app on google app engine. I am keep getting this error:
self._sock.sendall(view[write_offset:write_offset+buffer_size])
error: [Errno 32] Broken pipe
My post request handler is:
def post(self):
Content = self.request.get("Message")
byName = self.request.get("byour_name")
byEmailAddress = self.request.get("byour_email_address")
gmailUser = 'id#gmail.com'
gmailPassword = 'password'
dataSend = byName
mail.send_mail(sender = gmailUser,
to = gmailUser,
subject ="Email Sent By : "+ byName + "#" + byEmailAddress,
body = Content)
self.response.out.write(byEmailAddress)
And after I click submit button URl changes to:
http://localhost:8080/?byour_name=username&byour_email_address=userEmail#gmail.com%40gmail.com&Message=mlm%0D%0A#contact
as I am making a get request can someone help me..But how post request changes to get request.
You're not preventing the default submit. Either return false from your sendMail function, or take the event as a parameter and call preventDefault() on it.
Please remove form tag and the get the desired values by id and then use ajax method. Because may be ajax post and form request method are conflicting. I think form has default get method as you said earlier may be that's the reason whenever you click on submit first ajax post make request soon after form get method and may be that's the reason the error is thrown by your server.
I think I know what your trying to do , to fix this you can do the following:
remove onclick="sendMail()"
and change your JavaScript function to something like:
$('#myContactForm').submit(function () {
$.ajax( {
url: "/email",
type: "POST",
data: $("#myContactForm").serialize(),success:
function( response) {
alert(response);
},
error: function(){
alert('failure');
}
});
});

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