Sending Data from HTML to Servlet by two different methods - javascript

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

Related

PHPSESSID= not carried in ajax jquery

I'm trying to use $.ajax (jquery) to make an api call to my server (php). I'm successfully pinging the server, however, it's not validating that the user is logged in ( which is stored in PHPSESSID). This is a cross-domain request.
When I use PHP to make the api call from the front end, it works because the cURL request assigns the PHPSESSID to the CURLOPT_COOKIE.
Here is the $.ajax code on my site, www.foo.com
$(document).on('click','#pickup_now', function(){
//testing ajax function for 'cpr.php'
$.ajax({
url: "https://app.foo.com/CPR.php",
data: {
PickupLatitude: PickupLatitude,
PickupLongitude: PickupLongitude,
PickupAddress: PickupAddress,
PickupAddress2: '',
PickupCity: PickupCity,
PickupState: PickupState,
PickupZipCode: PickupZipCode,
DropOffLatitude: '34.0335328',
DropOffLongitude: '-118.48099309999998',
DropOffAddress: '2227 Wilshire Boulevard',
DropOffAddress2: '',
DropOffCity: 'Santa Monica',
DropOffState: '5',
DropOffZipCode: '90403',
ShipmentDescription: document.getElementById('description').value,
ShipmentImage: document.getElementById('ShipmentImage').value,
EstimatedTime: '180',
EstimatedDistance: '1'
},
type: "POST",
success: function(data,status){
console.log("Data: " + data + "\nStatus: " + status);
console.log(userSession);
} //ends success function
});
});
It's returning:
Data: {"LoginValid":false}
Status: success
So we know it's successfully pinging the server. Here is the code on https://app.foo.com/CPR.php
public static function CPR($pickupLatitude, $pickupLongitude, $pickupAddress, $pickupAddress2, $pickupCity, $pickupState, $pickupZipCode,
$dropOffLatitude, $dropOffLongitude, $dropOffAddress, $dropOffAddress2, $dropOffCity, $dropOffState, $dropOffZipCode,
$shipmentDescription, $shipmentImage, $estimatedTime, $estimatedDistance)
{
$results = new fooCommon\Results();
if ($results->LoginValid = SessionInfo::GetInstance()->LoggedIn())
$results->AddMembers(fooCommon\SHELPER::CPR(SessionInfo::GetInstance()->UserID(), $pickupLatitude, $pickupLongitude, $pickupAddress, $pickupAddress2, $pickupCity, $pickupState, $pickupZipCode,
$dropOffLatitude, $dropOffLongitude, $dropOffAddress, $dropOffAddress2, $dropOffCity, $dropOffState, $dropOffZipCode,
$shipmentDescription, $shipmentImage, $estimatedTime, $estimatedDistance));
return $results;
}
The $results->LoginValid = SessionInfo::GetInstance()->LoggedIn() uses the users SESSION info to validate that they are logged in and grabs their information as well.
Here is that code, found on SessionInfo.php
public function LoggedIn()
{
if (!isset($_SESSION["LoggedIn"]))
$this->SetLoggedIn(false);
return $_SESSION["LoggedIn"];
}
How can I pass that PHPSESSID information properly so that the SessionInfo::GetInstance()->LoggedIn() knows to grab it and validate the user info?
TL;DR -> Is there a $.ajax equivalent to cURLs CURLOPT_COOKIE? That seems to be what's bringing that information over through the proper channel when doing this through a cURL.
Thanks in advance everyone!
When the page renders, embed the session ID in a hidden input element, i.e.
<input type=hidden name=sessionid value='<? inject here ?>'/>
When you make your ajax call, read the value out of the hidden input element, and include it in your data that you're posting back.

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.

Use ajax to submit form and receive info from a servlet

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

codeigniter: I can't change view page

I'm having some problems changing the view page in the code. Note: i'm using ajax.
This is part of the controller function called "insert_inventario" after the information is saved in array_db it compares with the inventario_model and the result "true" or "false" is saved in obj_inv.
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
if($obj_inv){
$edit_view = $this->load->view(base_url()."inventario/edit",$array_db,TRUE);
$response = array('mensaje' => $edit_view,
);
$this->output
->set_status_header(200)
->set_content_type('application/json', 'utf-8')
->set_output(json_encode($response, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES))
->_display();
exit;
}
This is part of the view page called create, this is the submit button that executes the Javascript code that execute the controller function
<input type="submit" class="btn btn-danger" id="btn_enviar" value="Guardar">
The javascript Function
$("#btn_enviar").click(function(){
var r = confirm("Make sure the information you fill is correct");
if (r == true){
var url = base_url + "/inventario/insert_inventario";
$.ajax({
type: "POST",
url: url,
data: $("#form_inventario").serialize(),
success: function(data)
{
$("#contenido").html(data.mensaje);
}
});
}
return false;
});
The problem is, when i fill the form and press submit, the message box appears and when I click accept, it does nothing. I'm burning my brain so much to understand what I'm doing wrong, please help me.
The main problem is a error called jquery-2.1.4.min.js:4 POST http://161.196.112.19:8080/Inventario_Remedy/inventario/insert_inventario 500 (Internal Server Error) it happens when the code try to insert the array
$obj_inv = $this->Inventario_model->insert_inventario($array_db);
So, in order to fix this, you have to check your database values and keep trying.

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

Categories

Resources