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.
Related
I am developing a spring+hibernate webapp for practicing translation skill from Russian to English.
In one of my jsp pages I am retrieving all the questions from database and placing them into a table with the following columns: text in Russian, field for user's translation, button for checking the result. The goal is to save user's input into database without refreshing the page. How can I do it?
I tried several options, but none of them worked for me.
I used the solution from Send javascript variables to spring controller in my project, but nothing happened at all.
Part of "firstPage.jsp" ("/first" path in the controller):
<head>
<title>Title</title>
<script>
function searchViaAjax(id) {
var tempId = id;
alert("Start");
$.ajax({
type : "POST",
url : "./search/api/getSearchResult",
data : {id:tempId},
timeout : 100000,
success : function(id) {
alert("success");
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
alert("error");
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
alert("done");
console.log("DONE");
}
});
}
</script>
</head>
<body>
<button onclick="searchViaAjax(1)">Simple button</button>
</body>
Controller class:
#Controller
public class DemoController {
#RequestMapping("/first")
public String getFirst(){
return "firstPage";
}
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult", method=RequestMethod.POST)
public String getSearchResultViaAjax(#RequestParam("id") Integer id) {
System.out.println("come to ajax"+ id);
return "hello";
}
}
The "Start" message gets printed, but other messages from searchViaAjax() don't. And controller method doesn't start.
You can pass id in controller as it is no issue in your 'id', and also you can skip value attribute in #RequestParam.
#ResponseBody
#RequestMapping(value = "/search/api/getSearchResult")
public String getSearchResultViaAjax(#RequestParam("id") integer id) {
System.out.println("come to ajax"+ id);
return "hello";
}
Specify the methodType
#RequestMapping(value = "/search/api/getSearchResult", methodType=RequestMethod.POST)
It is also a good practice to use wrapper instead of primitive
#RequestParam("tempId") Integer id
the problem is in your ajax url attribute.
It should be url : "./search/api/getSearchResult",
Root Cause:
When you are about to hit your controller, it construct the url like this
http://localhost:8080/search/api/getSearchResult
and hence such resource is not available and it causes 404 not found error.
In actual the url should be
http://localhost:8080/contextroot/search/api/getSearchResult
here contextroot refers your project name.
Now if you hit url ./search/api/getSearchResult then ./ refers the base url i,e localhost:8080/contextroot and the entire url will be constructed properly.
I would like to recommend you to create global variable in JavaScript say baseUri and assign./ into it.
<script>
var baseUri="./";
</script>
In your AJAX it becomes
url : baseUri+"search/api/getSearchResult",
Hope this will help
The code from user9634982 was fine, thanks to him. The problem was because I was using slim jQuery version so my browser was giving me "$.ajax is not a function" error. And I didn't see it for hours because I didn't know where to look :facepalm: Thanks again to user9634982 for discovering browser inspector to me :D After replacing slim version to usual it still didn't work because of spring security. I added _csrf token and all worked fine.
.jsp:
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
<script>
function searchViaAjax(id) {
var csrfHeaderName = "X-CSRF-TOKEN";
var csrfTokenValue;
var metaTags = document.getElementsByTagName('meta');
for(var i = 0; i < metaTags.length; i++) {
var metaTagName = metaTags[i].getAttribute("name");
if(metaTagName === "_csrf_header")
csrfHeaderName = metaTags[i].getAttribute("content");
if(metaTagName === "_csrf")
csrfTokenValue = metaTags[i].getAttribute("content");
}
$.ajax({
type : "POST",
url : "./addAnsweredQuestion",
data : {id:id},
timeout : 100000,
beforeSend:function(xhr){xhr.setRequestHeader(csrfHeaderName, csrfTokenValue);},
success : function(id) {
alert("success");
console.log("SUCCESS: ", id);
display(id);
alert(response);
},
error : function(e) {
alert("error");
console.log("ERROR: ", e);
display(e);
},
done : function(e) {
alert("done");
console.log("DONE");
}
});
}
</script>
Controller:
#PostMapping(value = "/addAnsweredQuestion")
public void getSearchResultViaAjax(#RequestParam("id") Long id) {
System.out.println("come to ajax"+ id);
}
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 .
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.
Can someone help me solve this problem. I just want to add an Items in element in html with database field using c# and javascript, but my code has no output. Also, I tried to input a button and Called the Function "loadGrp" on onClick property of the button. eg: input type="submit" value="Add Item" onClick ="loadGrp();" but also it does not work. how to fix this problem, i know someone out there has a capability to solve this, so please help me guys Guys..
JS
function loadGrp()
{
$.ajax({
type: 'POST',
url: '../WebService/wsLeaveRequest.asmx/LoadGroup',
dataType: 'json',
//data: '',
contentType: 'application/json; charset=utf-8',
success: function (response){
$('#cboGroup').empty();
var cell = eval("(" + response.d + ")");
for (var i = 0; i < cell.length; i++)
{
$('#cboGroup').append('<option value="' + cell[i].grpID + '">"' + cell[i].grpShortName + '</option>');
}
},
error: function (error) {
console.log(error);
},
complete: function () {
}
});
}
C#
[WebMethod]
public string LoadGroup()
{
List<GroupInfo> mylist = new List<GroupInfo>();
using (SqlConnection conn = new SqlConnection(connectionString()))
{
conn.Open();
SqlCommand cmd = new SqlCommand("spLoadGroup", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
SqlDataReader dr = cmd.ExecuteReader();
while(dr.Read())
{
mylist.Add(new GroupInfo
{
grpID = dr["groupID"].ToString(),
grpShortName = dr["groupShortName"].ToString()
});
}
dr.Close();
conn.Close();
}
JavaScriptSerializer js = new JavaScriptSerializer();
string jsn = js.Serialize(mylist);
return jsn;
}
HTML
<!DOCTYPE html>
<html>
<script src="Script/jsSetting.js"></script>
<script src="Script/jsleaverequest.js"></script>
<div class="row cells12">
<div class="cell colspan3">
<div class="input-control select full-size">
<h5>Filter Group:</h5>
<select id="cboGroup"></select>
</div>
</div>
</div>
</div>
<body>
<head>
</head>
</body>
</html>
Here are couple of observations
url: '../WebService/wsLeaveRequest.asmx/LoadGroup',
The .. may not be making any sense here
If there is no form in the page then replace input type = "submit" with input type = "button"
var cell = eval("(" + response.d + ")"); seems fishy. Using eval is not a good idea and specifically here it dont seems to make any sense.
Put a debugger or a log statement at the first line of function loadGrp and see if the function is getting executed on button click. Then check from developer's window(For Chrome press f12 -> Click on network -> Hit the input type = button) and validate if it is making any network call and validate the response of it
#RequestMapping(value = "/ajaxtest", method = RequestMethod.GET)
public #ResponseBody
String getTime() {
Random rand = new Random();
float r = rand.nextFloat() * 100;
String result = "<br>Next Random # is <b>" + r + "</b>. Generated on <b>" + new Date().toString() + "</b>";
System.out.println("Debug Message from CrunchifySpringAjaxJQuery Controller.." + new Date().toString());
return result;
}
#RequestMapping(value = "profile", method = RequestMethod.GET)
public #ResponseBody String processAJAXRequest(#RequestParam("regnum") String regnum, ModelMap map)
{
/*System.out.println(regnum);
System.out.println(studentService.studentRegNo(regnum));*/
boolean b= studentService.studentRegNo(regnum);
if(b==true)
{
return "Give the Different Reg number";
}
else
{
return "Enter";
}
}
IN JSP
<script type="text/javascript">
function crunchifyAjax() {
var regnum = $('#regnum').val();
/* alert(regnum); */
var data = 'regnum='
+ encodeURIComponent(regnum);
/* alert("inside ajax"); */
$.ajax({
url : 'profile.html',
data : data,
success : function(data) {/* alert(data); */
$('#result').html(data);
}
});
}
</script>
<td><form:label path="regnumber">Registration Number<span class="mandatory">*</span></form:label></td>
<td>
<form:input path="regnumber" class="textFLD" required="required" onblur="crunchifyAjax();" id="regnum"/></td>
<td width="40%"><div id="result" class="message" ></div></td>
I had posted my controller and jsp page please help me to clear my textbox if duplicates are entered to regnum field now message is displaying when duplicates are entered but i also want to clear textbox.
Try this to clear the input:
/* alert("inside ajax"); */
$.ajax({
url : 'profile.html',
data : data,
success : function(data) {/* alert(data); */
if(data=='Give the Different Reg number'){
$('#regnum').val('');
}
else {
$('#result').html(data);
}
}
});