I have a registration form where I am validating the "preferred login id" using AJAX so it searches the users table and shows if it's available or not, and it displays next to the text box "username available" or "username not available".
My requirement is when it's not available I want to pass the text "username not available" back to the javascript in the JSP from the Servlet so that I can stop the user from proceeding the form. I believe I can do it using AJAX. But I dont know how to do it. Could someone help me on this with the code?
I would use JQuery, and the get() method in particular as an example
Here is a pseudo solution (didn't test it, but it's the basic approach I would use)
JavaScript
var userIsAvailable = false;
function checkUsernameAvailability(userIdToCheck){
$.get("pathToServlet",{userId: userIdToCheck},function(resultMessage){
userIsAvailable = resultMessage=="username available" //this is bad practice, just an example, pass true/false
$("#userAvailabilityMessage").text(resultMessage);
}
});
HTML
<form onsubmit="if(!userIsAvailable){alert('user is not available')}; return userIsAvailable">
<label for="userId">preferred login id<label>
<input id="userId" ... type="text" onblur="checkUsernameAvailability(this.value)">
<div id="userAvailabilityMessage" />
...
</form>
Servlet (partial)
#WebServlet("/pathToServlet")
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String result;
if(isUserNameAvailable(request.getParameter("userId"))){
result = "username available";
}else{
result = "username not available";
}
response.setContentType("text/plain");
response.getWriter().print(result);
}
}
You need to send object with some flag in message. You can use json for this.
On servlet side:
// This object we will transfere from java to javascript
public class Message {
private boolean error;
private String errorMessage;
// Getters and setters ommited
}
// Servlet code - return content
Message message = new Message();
message.setError(true);
message.setErrorMessage("Your error message");
Gson gson = new Gson(); // GSON - java json library from Google. I prefer it
String content = gson.toJson(message);
response.setContentType("text/json");
response.getWriter().print(content);
And finally javascript code:
function processRequest() {
var result = jQuery.ajax ({
url: "your.url",
method: "post",
async: false,
data: "your=data&andsomedate=somedata"
});
// Creating object from json
var message = jQuery.parseJSON(result.responseText);
// Now we can access all object fields:
if(message.error) {
alert("Error message: " + message.errorMessage);
}
}
Related
I have this URL
var url = "/test/Create/" + $("#hdnFlag").val() +"?CmpT="+"Ilim";
window.location.href = url;
and in my Test controller I do this to get query string value
tM_PMO.Type = Request.QueryString["CmpT"];
But always give me null values.
There is a difference between the GET and POST types.
Query string can be read with the URL of the GET request. However, you cannot read the Query string value in the URL when you make a POST request. For this you need to submit it to the server.
Below I give you a few examples of usage.
GET Request
You can read Query string with URL as below
public ActionResult Test(string CmpT)
{
if (!string.IsNullOrWhiteSpace(CmpT))
{
//your codes...
}else
{ }
return View();
}
POST Request
If you are making a POST request and trying to read from the URL, it will return null. In order to read it, you need to send this value to the server as follows.
1st way : In your Html.BeginForm in your View Below, submit Query string as below and read this value as Action parameter
View Page
#using (Html.BeginForm("Test", "XController", new { returnUrl = Request.QueryString["CmpT"] }, FormMethod.Post, new { role = "form" }))
{
<button type="submit">Send</button>
}
Controller
public ActionResult Test(string returnUrl)
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//your codes...
}else
{ }
return View();
}
2nd way : Create a hidden form element as part of the form between the Html.BeginForm tags in your view page and give its value as a query string. Then call it in Action method like below.
View Page
#using (Html.BeginForm("Test", "XController", FormMethod.Post, new { role = "form" }))
{
#Html.Hidden("returnUrl", Request.QueryString["CmpT"])
<button type="submit">Send</button>
}
Controller
public ActionResult Test(string returnUrl)
{
if (!string.IsNullOrWhiteSpace(returnUrl))
{
//your codes...
}else
{ }
return View();
}
or for multiple form items (You can also access other form elements this way)
public ActionResult Test(FormCollection fc)
{
string _returnUrl = fc["returnUrl"];
if (!string.IsNullOrWhiteSpace(_returnUrl))
{
//your codes...
}else
{ }
return View();
}
I hope you are looking for below code sample where we just fetch the value in url which we says query string:
Request.QueryString["querystringparamname"].ToString();
You can assign this in any Var and use accordingly.
I'm looking into taking payments through the Square connect API on a website, but I can't figure out how to allow the user to key in any payment amount they wish (like a PayPal pay me button). Is this possible to do, or can you only take payments in pre-set fixed amounts via Square?
It looks like in Square's examples the amount is being set in the backend code and there's no way to send the amount for the transaction through from the frontend.
I am following Square's walkthrough using Node here: https://developer.squareup.com/docs/payment-form/payment-form-walkthrough
Apologies if this has been asked before, but I couldn't find anything recent that addressed the issue.
If you want to send the amount from the frontend, you would need to submit it via a field in a form (like the nonce in the example you provided). Ie if you wanted the customer to fill out the amount you would have something like:
<form>
...
<input type="text" id="amount" name="amount">
...
</form>
as a field in your form, and then in your backend retrieve it from the amount name (which depends on what backend language you're using, but as an example PHP would be something like $_POST['amount'].
I ended up solving this by coding the fetch to /process-payment explicitly in the frontend .js code instead of having it in the form submit so it looks like this:
function submitPaymentRequest(event) {
let nonce = document.getElementById("card-nonce").value;
fetch("process-payment", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({
nonce: nonce,
amount: document.querySelector('input[name="amount"]').value
})
})
.then(response => {
console.log(response);
response.json().then(data => {
console.log(data);
alert(JSON.stringify(data));
});
})
.catch(function(error) {
console.log("the error was", error);
});
}
I posted a full working example of this here.
Yes i face the same issue but i made the solution.
Firstly You make a hidden type field and give them some value e.g 100
**> <input type="hidden" id="amount" name="amount" value="1000" />**
add this line in below your form.Then go to payment-processing page,
**
> string am = Request.Form["amount"];
**
get that input value i am doing in c# so its a c# code.
then pass this am string type variable to Amountmoney section. like below.
var amountMoney = new Money.Builder()
**.Amount(Convert.ToInt64(am))**
.Currency("USD")
.Build();
Here is the full code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Square;
using Square.Models;
using Square.Exceptions;
using Square.Apis;
public partial class process_payment : System.Web.UI.Page
{
private SquareClient client;
public string ResultMessage
{
get;
set;
}
protected void Page_Load(object sender, EventArgs e)
{
client = new SquareClient.Builder()
.Environment(Square.Environment.Sandbox)
.AccessToken("YOUR ACCESS TOKEN")
.Build();
string nonce = Request.Form["nonce"];
string am = Request.Form["amount"];
IPaymentsApi PaymentsApi = client.PaymentsApi;
var amountMoney = new Money.Builder()
.Amount(Convert.ToInt64(am))
.Currency("USD")
.Build();
string idempotencyKey = NewIdempotencyKey();
var body = new CreatePaymentRequest.Builder(
sourceId: nonce,
idempotencyKey: idempotencyKey,
amountMoney: amountMoney)
.Build();
CreatePaymentRequest createPaymentRequest = new CreatePaymentRequest.Builder(nonce, idempotencyKey, amountMoney)
.Note("From Square Sample Csharp App")
.Build();
try
{
CreatePaymentResponse response = PaymentsApi.CreatePayment(createPaymentRequest);
this.ResultMessage = "Payment complete! " + response.Payment.Note;
}
catch (ApiException es)
{
this.ResultMessage = es.Message;
}
}
private static string NewIdempotencyKey()
{
return Guid.NewGuid().ToString();
}
}
I have a function in js file(exp : validateMyfile.js) that get a string parameter, this String has a value in myFile.properties and I need this value.
Now I want to get parameter value by spring message source.
How to use spring message source inside js file?
function validate(msg){
-- so I need msg value (value iside myFile.properties);
}
We normally read the message into a javascript variable in jsp file before passing it to a js function as follows
<%#taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<script type="text/javascript">
var successmsg = "<fmt:message key='message.key'/>";
function validate(){
alert(successmsg);
}
</script>
Sometimes, we also pass it as a message from the Controller for a ajax call.
#Controller
public class EmployeeController{
#Value("${employee.add.success}")
private String successMessage;
#Value("${employee.add.failure}")
private String failureMessage;
#ResponseBody
#RequestMapping("/addEmployee")
public String addEmployee(...){
...
if(added){
StatusObject status = new StatusObject();
status.setCode(..);
status.setMessage(successMessage);
}else{
StatusObject status = new StatusObject();
status.setCode(..);
status.setMessage(failureMessage);
}
//return status object
}
}
And access it as follows
$.ajax({
...
success: function(status){
$("#result").text(status.message);
}
});
I have made a login form which compares the usernames and passwords entered from a text file and then displays whether username/password is incorrect or the access is allowed.
<form role="form" action="/traveositelogin" method="post">
<div class="form-group">
<label class="sr-only" for="form-username">Username</label>
<input type="text" placeholder="Username..." class="form-username form-control" id="username">
<p id="UsernameIncorrect" hidden>Incorrect Username. Try Again</p>
</div>
<div class="form-group">
<label class="sr-only" for="form-password">Password</label>
<input type="password" placeholder="Password..." class="form-password form-control" id="password">
<P id="PasswordIncorrect" hidden>Incorrect Password. Try Again.</p>
</div>
<button type="submit" class="btn" id="Login">Login</button>
<p> Forgot Password?</p>
<div class="form-group">
</div>
This is my servlet code:
package com.traveosoft;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public class TraveoWebsiteLoginServlet extends HttpServlet {
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, this is a testing servlet. \n\n");
Properties p = System.getProperties();
p.list(resp.getWriter());
}
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
String filePath = "{login.txt}";
String username = null;
String password = null;
//resp.setContentType("text/plain");
//resp.getWriter().println("Hello, this is a testing servlet. Post method \n\n");
//Properties p = System.getProperties();
//p.list(resp.getWriter());
if (req.getParameter("Login")!= null )
{
username = req.getParameter("username");
password = req.getParameter("password");
//resp.sendRedirect("index.html");
}
try
{
FileInputStream fstream = new FileInputStream("login.txt");
// Use DataInputStream to read binary NOT text.
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
int count = 0;
while((strLine = br.readLine())!= null)
{
//Enter userName
String[] creds = strLine.split(",");
System.out.println("creds[0], creds[1]:" + creds[0] + "," +creds[1] );
//System.out.println("User name from the file is:"+ creds[0]);
if (creds[0].equals(username))
{
//user name matches. So we need to check for password now
count++;
if (creds[1].equals (password))
{
//Great... password also matches. Allow the user access to our repository
System.out.println("Allow access");
}
else
{
// Password didn't match. Ask the user to reenter the password
System.out.println("Wrong password. Try Again.");
}
break;
}
//strLine = br.readLine();
//count++;
//Enter Password
//System.out.println("Password from the file is:"+ creds[1]);
}
if (count == 0 )
{
// No user name matched with the user name entered by the user. So user name itself is wrong
System.out.println("Your user name is wrong. Try Again.");
}
fstream.close();
br.close();
}
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}
How can I write a javascript code, that when the username is wrong, prints "username is wrong"; password is wrong, then prints "password is wrong"; and if both are correct, allows me to put a hyperlink reference to a page where the resources are kept.
I would appreciate example code in javascript (instead of jsp files). I am still learning all this, any help would be really appreciated. Thanks In Advance.
If I understood correctly you want a response object (or say message) to be send from the server-side to client-side directly to JS rather than sending it via JSP.
In order to do that you require some more efforts to do...
You can follow following steps:
1. Create a response object.
2. Convert that object to JSON format.
3. Set your response content type as text/json and set the response.
// Response object which is to be send to JavaScript
public class ResponseMessage {
private boolean isLoginSuccess;
private String errorMessage;
// Getters and setters ...
}
// Servlet code
ResponseMessage message = new ResponseMessage();
message.setError(true);
message.setErrorMessage("Your error message");
Gson gson = new Gson(); // GSON: library to convert Java object to JSON
String content = gson.toJson(message);
response.setContentType("text/json");
response.getWriter().print(content);
JS Code
function processRequest() {
var result = jQuery.ajax ({
url: "your.url",
method: "post",
async: false,
data: ""
});
// Create JS object from JSON
var message = jQuery.parseJSON(result.responseText);
// Now you can show your message
if(message.isLoginSuccess) {
alert("Welcome");
}else{
alert("Login Failed");
}
}
I'm with a little problem on my project.
Hi have several jsp's and Java class. In one jsp i create a form with only a input type="file" and type="submit", then I have an ajax call and send all the formdata to a doPost class on my servel. Then I send that file to the DataBase and it all's go fine, my problem is I want to return the id from the database to the .jsp. I can access and have prints on the doPost to check my key, but cant send it to success function inside the ajax call..
Here's my code, i really apreciate any kind of help, thanks!
<form id="uploadDocuments" target="invisible" method="POST" action="UploadDocumentsAjaxService" enctype="multipart/form-data">
<iframe name="invisible" style="display:none;"></iframe>
<h3 style="width: 71%;margin-left: 8%;">ANEXAR FICHEIROS:</h3>
<h4 style="margin-left: 8%; color: #F7A707" >Escolher ficheiro para anexar: </h4>
<input type="file" id="file_input" name="file" size="50" style="width: 60%; margin-left: 8%;"/>
<input type="submit" value="Upload" />
</form>
the I have my Ajax Call:
$("#uploadDocuments").submit(function (e) {
alert(10);
alert($("#uploadDocuments").attr('action'));
$.ajax({
type: $("#uploadDocuments").attr('method'),
url: $("#uploadDocuments").attr('action'),
contentType: $("#uploadDocuments").attr( "enctype"),
data: new FormData($("#uploadDocuments")[0]),
processData: true,
success: function (data) {
alert("submitDocument");
alert();
/* key = data;
addFilesToTable(key); */
return true;
}
});
e.preventDefault();
$(form).off('submit');
return false;
});
And then my servlet class:
protected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
response.setContentType("text/html;charset=ISO-8859-1");
PrintWriter out = response.getWriter();
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
ChangeEntityRequestActionBean actionBean = new ChangeEntityRequestActionBean();
if(!isMultipart)
return;
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Sets the size threshold beyond which files are written directly to
// disk.
factory.setSizeThreshold(MAX_MEMORY_SIZE);
// constructs the folder where uploaded file will be stored
String uploadFolder = getServletContext().getRealPath("") + DATA_DIRECTORY;
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(MAX_REQUEST_SIZE);
String fileName = "";
Long documentKey = null;
String key = "";
try {
// Parse the request
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (!item.isFormField()) {
fileName = new File(item.getName()).getName();
String filePath = uploadFolder + File.separator + fileName;
File uploadedFile = new File(filePath);
System.out.println(filePath);
// saves the file to upload directory
item.write(uploadedFile);
}
documentKey = actionBean.insertDocument(item, fileName);
System.out.println("Key from DAO ------->>>>>"+documentKey);
key = String.valueOf(documentKey);
}
System.out.println("Key in String from DAO ----->"+key);
System.out.println();
out.println("success");
response.flushBuffer();
}catch (FileUploadException ex) {
throw new ServletException(ex);
} catch (Exception ex) {
throw new ServletException(ex);
} finally {
out.close();
}
}
All I want is to send the key value to out.println so I can use that value on a jquery function
In the first line of doPost() in your servlet, change the content-type of the response to "application/json". Then write a JSON string to the output stream. There are libraries available to do this for you, but for something so simple, you can compose the JSON yourself. This might actually have an advantage because your key is a java long; treat it as a string and you don't have to worry about how the integer is represented.
// replace out.println("success"); with this:
out.print("{\"key\": \"" + key + "\"}");
Then in the success callback function, you can access the key as a field of the data object. You'll need to specify the data type in the ajax method (dataType: 'json').
success: function (data) {
var key = data['key'];
addFilesToTable(key);
return true;
}