I need to make my jsp page work without reloading page using jquery.
$(".btn.btn-default.btn-lg").click(function( event ) {
event.preventDefault();
$.post(main.jsp,{operand1: request.getParameter("operand1")});
alert(<%= request.getParameter("operand1") %>);
});
I'm trying to post parameter to the page and alert it. Nothing happens.
However function works fine.
what's my mistake?
Here is full jsp code.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="css/bootstrap.min.css" rel="stylesheet">
<title>Insert title here</title>
</head>
<body>
<script src="https://code.jquery.com/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<form class="form-horizontal" role="form" method="get">
<div class="form-group">
<div class="col-lg-10">
<input name="operand1" id="operand1" class="values"></input>
<input name="operand2" id="operand2" class="values"></input>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<select name="operation" id="operation" class="values">
<option value="plus">+</option>
<option value="minus">-</option>
<option value="multiply">*</option>
<option value="divide">/</option>
<option value="mod">mod</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-lg-10">
<input type="submit" class="btn btn-default btn-lg" value="Submit"></input>
</div>
</div>
</form>
<script>
$(".btn.btn-default.btn-lg").click(function( event ) {
event.preventDefault();
$.ajax({
method:"POST",
url: "main.jsp",
data: {operand1: document.getElementById("operand1").value, operand2: document.getElementById("operand2").value, operation: document.getElementById("operation")}
}).done(function (result) {
alert(result);
});
alert($('input.values').val());
});
</script>
<%
Double operand1=0.0;
Double operand2=0.0;
String operation=new String();
if ((request.getParameter("operand1")!=null)&&(request.getParameter("operand2")!=null)&&(request.getParameter("operation")!=null)){
operand1 = Double.parseDouble(request.getParameter("operand1"));
operand2 = Double.parseDouble(request.getParameter("operand2"));
operation=request.getParameter("operation");
}
Double result=0.0;
if (operation.equals("plus")){
result=operand1+operand2;
}
if (operation.equals("minus")){
result=operand1-operand2;
}
if (operation.equals("divide")){
result=operand1/operand2;
}
if (operation.equals("multiply")){
result=operand1*operand2;
}
if (operation.equals("mod")){
result=operand1%operand2;
}
if ((request.getParameter("operand1")!=null)&&(request.getParameter("operand2")!=null)&&(request.getParameter("operation")!=null)){
String resultString="Result:";
out.println(resultString+result);
}
%>
</body>
</html>
Any suggestions?
You should use ajax something like this:
$(".btn.btn-default.btn-lg").click(function( event ) {
$.ajax({
method:"POST",
url: "main.jsp",
data: {operand1: document.getElementById("operand1").value}
}).done(function (result) {
alert(result)
});
});
request is a JSP implicit object which will not work in javascript. Instead you can use following to get the value.
$('#operand1').val(); //operand1 is an id of the element
Use the success callback :
$(".btn.btn-default.btn-lg").click(function( event )
{
$.ajax(
{
method:"POST",
url: "main.jsp",
data: {operand1: document.getElementById("operand1").value},
success: function(result)
{
alert(result);
}
})
});
Related
I am writing a login form and I need to make an authentication for the username and password.
The form is written in dreamweaver html code. And the database is local in visual studio .net core code. I am still trying to figure out a way to use $post and $get methods, but I even can't write the url correctly. I am using swagger to host my api.
Here is my visual studio controller code :
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using authentication.Models;
using authentication.Repository;
using Microsoft.AspNetCore.Http;
namespace Taskb.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
private UsersRepository users = new UsersRepository();
private int count = 0;
[HttpGet]
public ActionResult<IEnumerable<user>> GetAllUser()
{
return users.GetAllUsers();
}
[HttpPost]
public ActionResult<user> CreateUser( user newUser)
{
foreach (user item in users.GetAllUsers())
{
if (newUser.username == item.username && newUser.password == item.password)
{
count++;
}
}
if (count == 0)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Username or password incorrect");
}
return Ok("Authentication Successfull");
}
}
}
And here is my html code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Roy Daher</title>
<link href="styles/style.css" rel="stylesheet" type="text/css">
<meta name="viewport" content="width=device-width, initial scale 1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"
type="text/javascript"></script>
<!--include jQuery Validation Plugin-->
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.12.0/jquery.validate.min.js"
type="text/javascript"></script>
</head>
<body bgcolor="#F1F1F1" class="body">
<div class="cont" >
<div class="top"></div>
<div class="bottom"></div>
<div class="center">
<form id="form" method="post">
<!--<div class="image">
<img src="images/28-287073_elonlol-discord-emoji-elon-musk-laughing-deer-hd.png" width="282" height="290" alt="Picture" class="elon">
</div>-->
<div class="container">
<label for="user"><b>Username</b></label>
<input type="text" placeholder="Enter Username" name="user" required id="userinput">
<label for="pass"><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="pass" required id="passinput">
<button id="loginButton" type="button">Login</button>
<label for="remember">Remember me</label>
<input type="checkbox" checked="checked" name="remember">
</div>
<div class="container" style="background-color:#F1F1F1">
<span class="forgot">Forgot <a href="pages/PassRecovery.html" target="_blank" >password?</a></span>
</div>
</form>
</div>
</div>
</body>
<script>
$(document).ready(function(){
$("button").click(function(){
var inputVal = document.getElementById("userinput").value;
var passVal = document.getElementById("passinput").value;
var obj ={
username:inputVal,
password:passVal
};
console.log(obj);
$.post("https://44332/api/User",
{
},
});
});
});
</script>
</html>
Thank you in advance for your help.
Your post method should use [FromBody] user newUser as the input parameter like below:
[HttpPost]
public ActionResult<user> CreateUser([FromBody] user newUser)
{
List<user> users = new List<user> {
new user{ username="a",password="a"},
new user{ username="b",password="b"},
new user{ username="c",password="c"}
};
foreach (user item in users)
{
if (newUser.username == item.username && newUser.password == item.password)
{
count++;
}
}
if (count == 0)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Username or password incorrect");
}
return Ok("Authentication Successfull");
}
And your ajax request should send like this:
<button id="loginButton">login</button>
<script>
$("#loginButton").click(function(){
var obj ={
username:"a",
password:"a"
};
$.ajax({
url: "https://localhost:44317/api/user",
type: 'post',
contentType: 'application/json',
data: JSON.stringify(obj),
success: function(data) {
alert(data);
}
})
});
</script>
Probably something simple going on here, but I have to attend to it before I attend to the PHP stuff. I'm going to try to use PHPMailer this time.
Also I've been trying to learn how to send a form on localhost for about a week now. Now I'm going to try to to incorporate PHPMailer. I had originally spent some time enabling a sites available to point to another folder, installing and testing PHP and installing msmtp on debian, even sent a test email with PHP, via command line but I haven't gotten one form to submit right yet and it's a :p
Also when working on forms before I made a couple changes to my php.ini files one on apache dir and one on cli dir, I think I uncommented some stuff and I hope it wont interfere with the what I'm trying to do.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Contact</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<style type="text/css">
input, textarea {
margin-top: 10px;
}
</style>
</head>
<body>
<div class="container" style="margin-top:100px;">
<div class="row justify-content-center">
<div class="col-md-6 col-md-offset-3" align="center">
<input id="name" placeholder="Name" class="form-control">
<input id="email" placeholder="Email" class="form-control">
<input id="subject" placeholder="Subject" class="form-control">
<textarea class="form-control" id="body" placeholder="Email Body"></textarea>
<input type="button" onclick="sendEmail()" value="Send an Email" class="btn btn-primary"></type>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script type="text/javascript">
function sendEmail() {
console.log('sending...');
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmtpy(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
body: body.val()
}, success: function (response) {
console.log(response)
}
});
}
}
function isNotEmpty(caller) {
if (caller.val()) == "") {
caller.css('border', 1px solid red');
return false;
} else
caller.css('border', '');
return true;
}
</script>
</body>
</html>
RAW Paste Data
Try use code below:
<script type="text/javascript">
function sendEmail() {
console.log('sending...');
var name = $("#name");
var email = $("#email");
var subject = $("#subject");
var body = $("#body");
if (isNotEmpty(name) && isNotEmpty(email) && isNotEmpty(subject) && isNotEmpty(body)) {
$.ajax({
url: 'sendEmail.php',
method: 'POST',
dataType: 'json',
data: {
name: name.val(),
email: email.val(),
body: body.val()
}, success: function (response) {
console.log(response)
}
});
}
}
function isNotEmpty(caller) {
if (caller.val() === "") {
caller.css('border', '1px solid red');
return false;
} else {
caller.css('border', '');
}
return true;
}
</script>
I checked. Work fine.
I am sending pdf file to server, and the form for creation of pdf file is not rendered, when the page loads. Its rendered when user click on something...
The problem is, that I cannot select id "file" which is input type="file" (html is generated by javascript).
How to select it the same as I am doing it with this code (the same result).
Thank you
$('.content').on('click','.file-btn', function() {
var data = new FormData();
var input = document.getElementById('file');
const title = $("#title").val();
const description = $("#textarea").val();
const sharingWith = $("#dropdown").val();
data.append('file', input.files[0]);
console.log("file" + data.get("file"));
$.ajax({
method: 'POST',
enctype: 'multipart/form-data',
url: 'https://localhost:8443/documents'+ "?title="+title + "&desc="+description + "&Role="+sharingWith ,
data: data,
processData: false,
contentType: false,
headers: {
'Authorization': 'bearer ' + localStorage.access_token},
success: function (data) {
alert("works!");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
})
export const createDocumentForm = () => {
const markup = `<form class="doc_form" id="doc-form">
<label for="title" id="title-label">Title</label>
<input type="text" id="title" required placeholder="Title">
<label for="textarea" id="textarea-label">Description</label>
<textarea id="textarea" placeholder="Enter description" required rows="5"></textarea>
<label for="dropdown" id="dropdown-label">Select groups for sharing document</label>
<select name="select" id="dropdown" multiple required>
<option value="USER">USER</option>
<option value="SUPERIOR">SUPERIOR</option>
<option value="ADMIN">ADMIN</option>
</select>
<div class="doc_sender">
<form class="form-horizontal" method="POST" enctype="multipart/form-data" id="id_form">
<input type="file" id="file"/>
</form>
<button class="btn btn-doc file-btn">Save file!</button>
</div>
</form>`;
elements.content.insertAdjacentHTML("beforeend", markup);
};
try using this to get your file
var input = $("#file").get(0).files[0];
1st: be sure your html file you have the main.js is below the src of jQuery src
2nd: wrap your js code like the example below
$(document).ready(function() {
console.log('your document is ready ...');
// your code ....
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="main.js"></script>
<title>Your title</title>
</head>
<body>
</body>
</html>
Unable to Perform Post method on my JSON File
My JSON File is
[{
"name": "Help",
"description": "Deletion not allowed for products!?",
"price": 100000.0 }]
<html>
<head>
<title>Product Management</title>
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/default.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"</script>
<script src="js/bootstrap.min.js"></script>
Function for Getting the Values
<script>
$(document).ready(function() {
$(window).load(function() {
$.ajax({
type: 'GET',
url: 'test.json',
dataType: 'json',
success: function(data) {
$.each(data, function(index, element) {
$("#abc").append($('<li>', {
text: element.name
}))
});
}
});
});
});
</script>
Function for Posting the Values in the JSON file
<script>
function sumbitForm(){
var x=document.getElementById("#name");
var y=document.getElementById("#description");
var z=document.getElementById("#price");
var Product={"name":x, "description":y, "price":z };
$.ajax({
url: "test.json",
type: "POST",
contentType: "application/json",
data: JSON.stringify(Product)
});
}
</script>
</head>
<body>
<div>
<ol id="abc">
</ol>
</div>
<div class="container">
Input Form for posting the Data
<form name="PForm" action="" method="POST">
<div class="form-group">
<label>Name:</label>
<input type="text" class="form-control" id="name" placeholder="Product Name">
</div>
<div class="form-group">
<label>Description:</label>
<textarea class="form-control" id="description" placeholder="Descrpition" rows="8"></textarea>
</div>
<div class="form-group">
<label>Price:</label>
<input type="text" class="form-control" id="price" placeholder="Price">
</div>
<button type="submit" class="btn btn-primary Right" onClick="submitForm()">Submit</button>
</form>
</div>
</body>
</html>
You need to get the value of the elements, like
var x=document.getElementById("#name").value;
Else you would send the DOM elements (which, converted to a string, would only be 'object')
I have a javascript code that I have hardcoded into my html file, but it never seems to load. My form sends data to a php file via post immediately without every going through javascript verification. Any ideas? Thanks!
<!DOCTYPE html>
<html>
<head>
<!-- Stylesheets - boostrap and get-shit-done, a free UI -->
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
<link rel="styelsheet" type="text/css" href="css/get-shit-done.css">
<link rel="stylesheet" type="text/css" href="css/styles.css">
<h1>Registration</h1>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$('#registration').on('submit', function(e){
var usernameValue = $("#username").val();
var passwordValue = $("#password").val();
var confirmationValue = $("#confirmation").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ usernameValue + '&password1='+ passwordValue + '&confirmation1='+ confirmationValue;
if(usernameValue==''||passwordValue==''||confirmationValue=='') {
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
</script>
</head>
<body>
<form id ="registration" action="register.php" method="post">
<fieldset>
<legend>Registration Details</legend>
<form class="form-inline">
<div class="form-group">
<input autocomplete="off" autofocus class="form-control" id="username" placeholder="Username" type="text"/>
</div>
<div class="form-group">
<input class="form-control" id="password" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<input class="form-control" id="confirmation" placeholder="Password" type="password"/>
</div>
<div class="form-group">
<button class="btn btn-default btn-round" type="submit" id="submit">
<span aria-hidden="true" class="glyphicon glyphicon-log-in"></span>
Log In
</button>
</div>
</form>
</fieldset>
</form>
<div>
<p class="text-center">or login</p>
</div>
</body>
</html>
You need to wrap your $('#registration').on('submit', function(e){ }); with in a $(function(){ }); (or $(document).ready()) as it is currently binding before the document is ready -
<script>
$(function(){
$('#registration').on('submit', function(e){
...
[rest of your code]
...
});
});
</script>
Please try adding your script inside jquery document ready . Example
$( document ).ready(function() {
$('#registration').on('submit', function(e){
var usernameValue = $("#username").val();
var passwordValue = $("#password").val();
var confirmationValue = $("#confirmation").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ usernameValue + '&password1='+ passwordValue + '&confirmation1='+ confirmationValue;
if(usernameValue==''||passwordValue==''||confirmationValue=='') {
alert("Please Fill All Fields");
}
else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "register.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});