After getting the user_name on client side using the below code :
<script type="text/javascript">
var WinNetwork = new ActiveXObject("WScript.Network");
var user_name = WinNetwork.UserName;
</script>
I was blocked how to pass the value of the variable "user_name" to the java code below,in order to test if this user exists on an oracle table :
<%
try {
ResultSet rs1 = stmt
.executeQuery("select * from utilisateur where upper(login) like upper('" + user_c + "')");
if (!rs1.next()) {
int i6 = stmt.executeUpdate("insert into utilisateur(login) values('" + user_c + "')");
}
}
catch (Exception e) {
System.out.print(e);
e.printStackTrace();
}
%>
In this case,you can’t get the user variable ,because jstl,el,is java code,when you render this page,it will go first ,then the html go second.
So you will see the blank in this two variable .
Related
I have an ASP.NET Web Application.I am using MasterPage for some reasons. I want to show a JavaSript message box. When a user click on certain button control, then it should displays a message accordingly. Now when i do this without MasterPage, it works fine but when a WebPage is inherited from my MasterPage , i mean if the page is a ContentPage, then the JavaScript message box doesn't show. I want a general method for that so that i can reuse the method in other content Pages.
Here is the Code.
private bool CheckEmployeeNo()
{
using (SqlConnection con = new SqlConnection(Base.GetConnection))
{
using (SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM [TableEmployee] WHERE EmployeeNo=#EmployeeNo", con))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("#EmployeeNo", tbEmployeeNumber.Text);
con.Open();
int UserExist = Convert.ToInt32(cmd.ExecuteScalar());
if (UserExist > 0)
{
string myMessage = "Here my msg goes...";
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Erroe " + myMessage + "');", true);
//lblMsg.Text = "Error: Message goes here.";
//lblMsg.ForeColor = Color.Red;
return false;
}
}
}
return true;
}
Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Erroe " + myMessage + "');", true);
use this
public ActionResult GiveTicket(Guid voteId, Guid applyId,string cptcha)
{
//檢查此票選是否允許此登入方式
var canVoteWay = _voteService.GetVoteWay(voteId);
string message = string.Empty;
string loginPath = $"{ConfigurationManager.AppSettings["DomainName"]}/Account/Login?returnUrl={Request.UrlReferrer}";
//檢查是否已登入
if (User.Identity.IsAuthenticated && WebLogic.HasValue(canVoteWay, (int)CurrentUser.LoginType))
{
// [驗證圖形驗證碼]
if (string.IsNullOrEmpty(cptcha) || cptcha != Session["VerificationCode"]?.ToString())
{
Response.Write("<script language=javascript> bootbox.alert('圖形驗證碼驗證錯誤,請重新輸入!!')</script>");
return null;
}
//var result = _voteService.GiveTicket(voteId, applyId, CurrentUser.Id, CurrentUser.LoginType);
Response.Write("<script language=javascript> bootbox.alert('投票成功')</script>");
return null;
}
message = _voteService.VoteWayString(canVoteWay, "請先登入,才能參與投票!! 投票允許登入的方式:");
Response.Write("<script language=javascript> if (confirm('" + message + "',callback:function(){})){window.location = '" + loginPath + "'}</script>");
return null;
}
My ajax code
function GiveTicket(applyId) {
var voteId = $('input[name="Id"]').val();
var captcha = $('input[name="Captcha"]').val();
$.ajax({
url: '#Url.Action("GiveTicket", "Vote")',
data: { applyId: applyId, voteId: voteId, cptcha: captcha },
type: 'Get',
success: function (data) {
console.log(data);
//bootbox.alert(data);
}
});
}
Like you see. I have many condition. SomeTime I need to pass alert or confirm to
web client . when I pass confirm. if user click Yes. I need to redirect Url.
So that I decide to write string to web client.
The problem is How I can just execute string from MVC like alert,confirm...
hello hopefully this post help you
you can passe your string to view using viewbag or viewModel as you like then in this view you put your redirect logic using razor.
I am trying to retrieve the value from DataBase using Java File and storing it to HashMap. Please find the below code (Sample.java):
import java.sql.*;
import java.util.HashMap;
public class Sample {
static Connection conn;
static PreparedStatement stmt;
static ResultSet rs;
String sql;
static String project="Project1";
public static HashMap< String, String> map = new HashMap< String, String>();
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
conn=DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue","root","root");
stmt=conn.prepareStatement("select * from TestCase where ProjectName= ?");
stmt.setString(1,project);
rs=stmt.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1)+" "+rs.getInt(2)+" "+rs.getInt(3)+" "+rs.getInt(4)+" "+rs.getInt(5));
map.put("ProjectName", rs.getString(1));
map.put("Total TestCase", String.valueOf(rs.getInt(2)));
map.put("TestCase Executed", String.valueOf(rs.getInt(3)));
map.put("Failed TestCase", String.valueOf(rs.getInt(4)));
map.put("TestCase Not Executed", String.valueOf(rs.getInt(5)));
System.out.println("ProjectName "+map.get("ProjectName"));
}
conn.close();
}
catch(Exception e)
{ System.out.println(e);}
}
}
Please find the below data which I am retrieving from the databse:
ProjectName TotalTestCase TestCaseExecuted TestCaseFailed TestCaseNotExecuted
Project1 50 30 8 20
I want to pass this value to Javascript and so that I am able to draw a chart using these values. Please find my HTML/Javascript code below (test.html):
<html>
<head>
</head>
<body>
<select id="ChartType" name="ChartType" onchange="drawChart()">
<option value = "PieChart">Select Chart Type
<option value="PieChart">PieChart
<option value="Histogram">Histogram
<option value="LineChart">LineChart
<option value="BarChart">BarChart
</select>
<div id="chart_div" style="border: solid 2px #000000;"></div>
<p id="demo"></p>
<p id="demo1"></p>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
var row = [];
var temp;
var stri;
google.load('visualization', '1.0', {'packages':['corechart']});
google.setOnLoadCallback(getValues);
function getValues() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
stri = xmlhttp.responseText;
drawChart();
}
};
xmlhttp.open("GET", "sample.java", true);
xmlhttp.send();
}
function drawChart() {
var data = new google.visualization.DataTable();
str = stri.split(",");
// How to call the value from java file so that I will be able to draw the below graph by passing the value.
data.addRows(row);
var a = document.getElementById("ChartType").value;
document.getElementById("demo1").innerHTML = "You selected: " + a;
var options = {'title':'How Much Pizza I Ate Last Night',
'width':400,
'height':300
};
var chart = new google.visualization[document.getElementById("ChartType").value](document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
</body>
</html>
Please let me know how to proceed or if anyone have any other example. Please share it with me. Thank you
You can convert your map to JSON. Instead of this
HelloWorld class, you can convert it into a service that returns this `JSON
import java.sql.*;
import java.util.HashMap;
public class Sample {
static Connection conn;
static PreparedStatement stmt;
static ResultSet rs;
String sql;
static String project = "Project1";
public static HashMap < String, String > map = new HashMap < String, String > ();
//Notice how your main class is now converted into a service
public static String getProjects() {
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3309/graphvalue", "root", "root");
stmt = conn.prepareStatement("select * from TestCase where ProjectName= ?");
stmt.setString(1, project);
rs = stmt.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getInt(2) + " " + rs.getInt(3) + " " + rs.getInt(4) + " " +
rs.getInt(5));
map.put("ProjectName", rs.getString(1));
map.put("Total TestCase", String.valueOf(rs.getInt(2)));
map.put("TestCase Executed", String.valueOf(rs.getInt(3)));
map.put("Failed TestCase", String.valueOf(rs.getInt(4)));
map.put("TestCase Not Executed", String.valueOf(rs.getInt(5)));
System.out.println("ProjectName " + map.get("ProjectName"));
/*______________ NEW CODE ______________*/
JSONObject resultMap = new JSONObject(map);
return resultMap.toString();
}
} catch (Exception e) {
System.out.println(e);
} finally {
conn.close();
}
return "";
}
}
Now convert your test.html to test.jsp and call that service
that we've created in previous step and output the resultant JSON
into a javascript variable.
test.jsp
<%#page import="com.path.to.Sample"%>
<html>
<head>
<script>
<!-- call that service and output that json into a javascript variable -->
var resultantJSON = <%= Sample.getProjects() %>
<!-- Now all that's left is to parse that json -->
var projects = JSON.parse(resultantJSON);
</script>
</head>
<body>
...
...
</body>
</html>
Now all your results that you fetched from your database are in projects variable in Test.jsp. You can use them like conventional javascript object in your jsp file.
You have to make the Java code accessable via http. There are several ways to do this. You can implement a servlet which retrieves the http request and can send data back as httpresponse. Search for a tutorial on java servlet, e.g. like this http://www.tutorialspoint.com/servlets/servlets-first-example.htm
You could also use a java rest service to supply the information. Search for java rest tutorial, e.g. like this http://www.vogella.com/tutorials/REST/article.html
I'm trying to compile some code and get it to work properly in this web service index program that I have created, via a virtual machine.
package com.cs330;
import javax.ws.rs.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
#Path("ws2")
public class IngredientServices
{
#Path("/ingredients")
#GET
#Produces("text/plain")
public String getIngredients() throws SQLException, ClassNotFoundException {
String connectStr="jdbc:mysql://localhost:3306/fooddb";
//database username
String username="root";
//database password
String password="csci330pass";
/* The driver is the Java class used for accessing
* a particular database. You must download this from
* the database vendor.
*/
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
//Creates a connection object for your database
Connection con = DriverManager.getConnection(connectStr, username, password);
/* Creates a statement object to be executed on
* the attached database.
*/
Statement stmt = con.createStatement();
/* Executes a database query and returns the results
* as a ResultSet object.
*/
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient");
/* This snippet shows how to parse a ResultSet object.
* Basically, you loop through the object sort of like
* a linkedlist, and use the getX methods to get data
* from the current row. Each time you call rs.next()
* it advances to the next row returned.
* The result variable is just used to compile all the
* data into one string.
*/
String result = "";
while (rs.next())
{
int theId = rs.getInt("id");
String theName = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId+ " , name: "+theName + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
#Path("/ingredients/{id}")
#GET
#Produces("text/plain")
public String getIngredientById(#PathParam("id") String theId)
throws SQLException, ClassNotFoundException {
int intId = 0;
try
{
intId = Integer.parseInt(theId);
}
catch (NumberFormatException FAIL)
{
intId = 1;
}//Obtaining an ingredient from the database
String connectStr="jdbc:mysql://localhost:3306/fooddb";
String username="root";
String password="csci330pass";
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection(connectStr, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient
WHERE id=" +intId);
String result = "";
while (rs.next())
{
int theId2 = rs.getInt("id");
String theName2 = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId2+ " , name: "+theName2 + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
#Path("/ingredients/name")
#GET
#Produces("text/plain")
public String getIngredientByName(#QueryParam("name") String theName)
throws SQLException, ClassNotFoundException
{
//Obtaining an ingredient from the database
String connectStr="jdbc:mysql://localhost:3306/fooddb";
String username="root";
String password="csci330pass";
String driver="com.mysql.jdbc.Driver";
Class.forName(driver);
Connection con = DriverManager.getConnection(connectStr, username, password);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, category FROM ingredient WHERE
name='" + theName + "'");
String result = "";
while (rs.next())
{
int theId3 = rs.getInt("id");
String theName3 = rs.getString("name");
String theCategory = rs.getString("category");
result += "id: "+theId3+ " , name: "+theName3 + "("+theCategory+")" + "\n" + "\n";
}
return result;
}//END METHOD
}//END CODE
Now, the first two methods, which are to retrieve everything and to retrieve items by ID are working properly, it's by retrieve by NAME code that isn't. While it is compiling correctly when I run it on cmd on my virtual machine and not showing any errors on Tomcat 8, The only code that is properly giving me results are the first two methods. For some reason, the third method keeps spitting out the first result and only the first result.
I have also attached the index.html file code to show you what the code above works with...
<html>
<head>
<title>Shakur (S-3) Burton's Web Services</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready( function() {
alert("running script");
$("#btnAll").click(function() {
alert("clicked");
$.ajax( {
url:"http://localhost:8080/webserv1/resources/ws2/ingredients/",
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
$("#p_retrieveAll").html(result); },
error:function(xhr) {
alert("error");
$("#p_retrieveAll").html("Error:"+xhr.status + " " + xhr.statusText);}
} );
});
$("#btnOneId").click(function() {
alert("clicked");
var inputId=document.getElementById("t_ingredId").value;
var theUrl = "http://localhost:8080/webserv1/resources/ws2/ingredients/"+inputId;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
$("#p_retrieveOneId").html(result); },
error:function(xhr) {
alert("error");
$("#p_retrieveOneId").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
$("#btnOneName").click(function() {
alert("clicked");
var inputName=document.getElementByName("t_ingredName").value;
var theUrl: "http://localhost:8080/webserv1/resources/ws2/ingredients/ingredient?name="+inputName;
$.ajax( {
url: theUrl,
type: "GET",
dataType: "text",
success: function(result) {
alert("success");
$("#p_retrieveOneName").html(result); },
error:function(xhr) {
alert("error");
$("#p_retrieveOneName").html("Error:"+xhr.status+" "+xhr.statusText);}
} );
});
});
</script>
</head>
<body>
<h3>Testing Web Services</h3>
<div id="retrieveAll">
<button id="btnAll">Click to Retrieve All</button>
<p id="p_retrieveAll">Ingredients List Goes here</p>
</div>
<div id="retrieveOneId">
<input type="text" id="t_ingredId" value="type id here" />
<button id="btnOneId">Click to Retrieve by Id</button>
<p id="p_retrieveOneId">Ingredient By Id Goes here</p>
</div>
<div id="retrieveOneName">
<input type="text" id="t_ingredName" value="type name here"/>
<button id="btnOneName">Click to Retrieve by Name</button>
<p id="p_retrieveOneName">Ingredient By Name Goes here</p>
</div>
</body>
</html>
Are there any suggestions that can be offered here as to why the GET by NAME method in my IngredientServices javascript isn't working properly? Am I missing something?
EDIT - 11/4/2014 - 16:05...
I figured that this problem might be in this part of the database program... Instead of searching for an ingredient by name by finding said element by ID, I should search within given parameters for it by NAME. Hopefully, this fixes the problem I was having...
BTW, this is the previous code I have modified: var inputName=document.getElementByName("t_ingredName").value;
When I added your code to the Firefox and Clicked on the Add-in called Firebug, it showed me the following error:
SyntaxError: missing ; before statement
var theUrl: "http://localhost:8080/webserv1/resources/ws2/ingredients/
Therefore it should be var theUrl= "http://localhost:8080/webserv1/resources/ws2/ingredients/ingredient?name="+inputName;
Have you tried debugging?
Also, instead of using alerts, use console.log("your message here"); - it will show up in the console in Firebug.
It turns out that that code I've created in the above question is thankfully working properly, despite some unfortunate bugs in the Retrieve Ingredient By Name method of my Java code... That was ultimately what needed some fixing.
I am currently doing an unpaid internship in C# and Asp.net. My employer has asked me to write out a javascript function so as to tell the user if they are sure if they want to delete a record from the database before deleting it.
After some research I was able to write out the Javascript function to tell the user if they are sure they want to delete this record before actually deleting it from the database.
The javascript function works. However now I have the problem of how do I call the backend C# function which will actually delete the record from the database from the front end javascript function which I have just written?
Here is my code:
Javascript function:
function watchdelete()
{
if (confirm("Are you Sure You want to delete this Manufacturer?") == true)
{
__doPostBack('btnDelete_Click','');//"PageMethods.btnDelete_Click();
}
else { }
}
Front end part which calls the javascript client side code attached to the delete button:
<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick=" return watchdelete()" OnClick="btnDelete_Click1" />
Back End C# function which I want to invoke in order to delete the record from the database:
(Please note I will be happy as long as I call this function and it executes, you need not worry
about its internal workings too much. Thank you)
protected void btnDelete_Click(object sender, EventArgs e)
{
String com, command, findmodel;
if (txtManufactureName.Text != "") // If the manufacturer name is not null
{
if (txtManufactureName.Text == grdManufact.SelectedRow.Cells[1].Text) // And the manufacturer name must not be
{ // Changed from selected one
string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
try
{
using (SqlConnection conn = new SqlConnection(strConnectionString))
{
conn.Open(); // Connect to database
String moderated = (checkBoxModerated.Checked) ? "true" : "false";
findmodel = "SELECT * From VehicleModels WHERE ManufacturerID = '" + txtManID.Text + "';";
com = "SELECT * From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "' AND Ismoderated ='" + moderated + "';";
command = "DELETE From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "' AND Ismoderated ='" + moderated + "';";
SqlDataAdapter finder = new SqlDataAdapter(findmodel, conn);
DataTable dat = new DataTable();
int nummods = finder.Fill(dat);
if (nummods == 0)
{
SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
DataTable dt = new DataTable();
int number = adpt.Fill(dt); // try to find record to delete
if (number == 0) // If there is no such record to delete
{ // Indicate this to user with error message
txtMessage.Text = "Sorry, there is no such record to delete";
}
else
{ // Otherwise delete the record
using (SqlCommand sequelCommand = new SqlCommand(command, conn))
{
sequelCommand.ExecuteNonQuery();
txtMessage.Text = "Manufacturer Deleted Successfully";
txtManufactureName.Text = ""; // Reset manufacturer name
txtDescription.Text = ""; // Reset Description
checkBoxModerated.Checked = false; // clear moderated checkbox
}
}
}
else
{
txtMessage.Text = "Sorry. You must delete associated models first.";
}
conn.Close(); // Close the database connection. Disconnect.
}
BindGrid(); // Bind Manufacturer Grid again to redisplay new status.
}
catch (SystemException ex)
{
txtMessage.Text = string.Format("An error occurred: {0}", ex.Message);
}
}
else
{
txtMessage.Text = "Sorry. You cant change the manufacturer name before deleting";
}
}
else
{ // Otherwise give error message if manufacturer name missing
txtMessage.Text = "Please enter a manufacturer name to delete";
}
}
Any ideas will be appreciated.
Let's simplified your validation function to:
function confirmDelete(){
return confirm("Are you Sure You want to delete this Manufacturer?");
}
Then your button with OnClientClick attribute will be something like
OnClientClick=" return confirmDelete()"
As long as your validation function returns false .NET will not submit your code the server.
To give people an understanding of how to call backend functions from client side Javascript I would like to put the answer here in my own words -> Simple plain English:
Step
1. Write your Javascript function and place it on the client side and enable scripts whatever, not going into too much detail here. See the code snippet below for an example
<script type = "text/javascript" >
function watchdelete()
{
return confirm("Are you Sure You want to delete this Manufacturer?");
}
Write your button or control front end code and ensure that your OnClientClick = the name of the javascript function you want to call plus the word return in front of it as in the example asp
code shown in the original post.
Ensure you fire up the backend C# function as per usual for example by double clicking on the button or control in design view of Visual Studio 2012 or 2013 or whatever so as to automatically build its backend function in the code behind page and code your backend function for what you want it to do obviously.
When you have done step 3 correctly you should have OnClick= whatever your backend C# function was.
Test your application. Once your front end javascript returns true it should automatically fire up
your backend function as long as you have put a return statement as per the front end code shown in the original post or similar.
Life can be simple if only you want it to be. The choice is yours.