how to call servlet from javascript using ajax - javascript

I am doing a samall jsp page to search a name enter in text box .. i called javascript function from jsp .. the bello is javascript code
function fncStudsearch()
{
//alert("yes")
var ele=document.getElementById("stdSearch").value;
var xmlhttp;
var strAjUrlData="stdSearch?key="+ele;
//alert(strAjUrlData)
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
}
else
{
alet(xmlhttp.status);
}
}
xmlhttp.open("GET",strAjUrlData,true);
xmlhttp.send();
}
I am calling servlet .. and i configured web.xml as follows
<servlet>
<servlet-name>stdSearch</servlet-name>
<servlet-class>com.slokam.Act.StudentSearch</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>stdSearch</servlet-name>
<url-pattern>/stdSearch</url-pattern>
</servlet-mapping>
</web-app>
I am unable ti go to servlet class
and servlet code i have written is
public class StudentSearch extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String stdkey=request.getParameter("key");
stdkey="%"+stdkey+"%" ;
System.out.println(stdkey);
}
}
please help in this regard how to goto servlet

If the app is not deployed as the root application on the appserver, you might need the context path in the url you are calling:
var ctx = "${pageContext.request.contextPath}/";
var strAjUrlData=ctx+"stdSearch?key="+ele;
...
This code assumes you are using jsp 2.0 and EL

Possibly this might help, there is an javascript error:
alet(xmlhttp.status); // you're missing here `r`
alert(xmlhttp.status);
Secondly, you have to print out some contents from servlet, use PrintWriter for that.
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String stdkey=request.getParameter("key");
stdkey="%"+stdkey+"%" ;
// test purpose
PrintWriter pw = response.getWriter ();
pw.print(stdkey);
pw.close();
}

Related

Getting image/video from html into java servlet as new File()

I want to get a file (image or video) from an
<input type='file' id='file_i'/>
// Not this <input type='submit'/>
Using an XMLHttpRequest like this
function img() {
var fd = new FormData();
fd.append('file', document.getElementById("file_i").files[0]);
var req;
if (window.ActiveXObject) {
req=new ActiveXObject();
} else {
req=new XMLHttpRequest();
}
req.open("post", "Image", true);
req.send(fd);
}
for example.
Then in the servlet doing this:
new FileInputStream(new File(request.getParameter("file")))
How can I retrieve that file?
Thanks in advance.
I fixed it. Here it is:
JAVASCRIPT
var fd = new FormData();
fd.append('file', document.getElementById("file_i").files[0]);
var req;
if (window.ActiveXObject) {
req=new ActiveXObject();
} else {
req=new XMLHttpRequest();
}
req.open("post", "Image", true);
req.send(fd);
JAVA
#MultipartConfig
public class addImage extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Part filePart = request.getPart("file");
InputStream fileContent = filePart.getInputStream();
}
}
XML
<servlet>
<servlet-name>Add Image</servlet-name>
<servlet-class>servlets.addImage</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Add Image</servlet-name>
<url-pattern>/Image</url-pattern>
</servlet-mapping>
I think you miss some points.
It seems in your JavaScript code, that you just create the request. But you didn't respond to results.
req.addEventListener("load", reqListener);
You should define reqListener like that:
function reqListener () {
// Here try to handle the response text, using "this.responseText"
console.log(this.responseText);
}
See the full info here:
Using XMLHttpRequest
Also in your Java code, you just stated that you created a file stream.
You should read from this input stream into the request's output stream. Also you should set the header Content-Type: put_your_mime_type_here, For example: Content-Type: application/json, if your file is a json file, Content-Type: image/png, if your file is a PNG image.
See an example here: Example for making a file download URL in Java

AJAX call to struts action not working

Hi i have a requirement in which i have to check something from struts action class and then send the result back to the browser using ajax call called in a JS fx'.The issue is im not able to hit the action class and console is throwing the following error:
org.apache.struts.action.RequestProcessor processActionCreate No action instance for path /ChangePwdAjax could be created
java.lang.ClassNotFoundException:test.ChangePwdAjaxAction.java
The class is compiled and the package context is valid test.ChangePwdAjaxAction.java
Any ideas what and where im doing it wrong?
Here is what i have written so far.
JS code
function checkError()
{
var valuePassword="test";
var url = "/test/ChangePwdAjax.do?newPass="+valuePassword;
var xmlHTTP = getXMLHTTPRequest();
xmlHTTP.onreadystatechange = function() {
handleResponse(xmlHTTP); }
xmlHTTP.open("GET",url,true);
xmlHTTP.send();
}
function handleResponse(xmlHTTP){
alert("handleResponse");
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
alert("handleResponse");
var xmlDoc = xmlHTTP.responseXML;
alert(xmlDoc.documentElement.getElementsByTagName("pwdFlag")[0].text);
}
}
function getXMLHTTPRequest(){
alert("getXMLHTTPRequest");
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("XMLHttpRequest is not supported!");
}
}
Action class code
public class ChangePwdAjaxAction extends Action {
public ActionForward execute(final ActionMapping mapping, final ActionForm form,
final HttpServletRequest request,final HttpServletResponse response)
{
System.out.println("----IN--AJAX ACTION----------");
final HttpSession session= request.getSession(false);
if(session==null || session.getAttribute("user_id")==null){
return mapping.findForward("sessionexpired");
}
final String user_id=(String)session.getAttribute("user_id");
try{
final BusinessDelegate busdel=new BusinessDelegate(user_id,session.getId());
String newpwd = (String)request.getParameter("newPass");
boolean b=busdel.checkOldPWd(user_id, newpwd);
//checking return values from bus delegate
response.setContentType("text/xml");
PrintWriter printwriter = response.getWriter();
printwriter.println("<?xml version=\"1.0\"?>");
printwriter.println("<Root>");
if(b)
{
System.err.println("----New password Failed--Y--------");
printwriter.println("<pwdFlag>"+"Y"+"</pwdFlag>");
}
else
{
System.out.println("----New password OK---N-------");
printwriter.println("<pwdFlag>"+"N"+"</pwdFlag>");
}
printwriter.println("</Root>");
}catch(Exception e){
logger.logCommon("Login Action : Login Process in Action : ", "EXCEPTION");
logger.logError(e);
}
return null;
}
}
Struts-config entry
<action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction.java"/>
OOps this had to be
action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction"/>
rather than
action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction.java"/>

How get the data using MVC- Servlets, JPS and JavaScripts

I have JSP page that has links (When people click on the link it is supposed to go to a servlet and then Bean class and DB Connection class to pull the data)..and when a user clicks on the like I tried to display the page using AJAX...however i am currently not getting any data/page pulled. Can someone please explain on how to achive this?
here is the link i have in my HTML page..but when i click on it is not showing up anything.
VT
Thanks for your help
Sorry here is my code
public class VacationTrackerDAO {
public static List<VactionTrackerBean> list() throws SQLException{
List<VactionTrackerBean> appr= new ArrayList<VactionTrackerBean>();
try{
DBConnection conObj=new DBConnection();
Connection dbCon= conObj.getCon();
Statement stmt=conObj.getStmt();
String queryCPList="select * from Capacity_Plan";
String queryApprList="Select First_Last_Name from Vacation_Approvers";
PreparedStatement preStmtCPList=dbCon.prepareStatement(queryCPList);//get metadat
PreparedStatement preStmtApprList=dbCon.prepareStatement(queryApprList);//get names
ResultSet rsCPList=preStmtCPList.executeQuery();
ResultSet rsApprList=preStmtCPList.executeQuery();
ResultSetMetaData metaCPList=rsCPList.getMetaData();
VactionTrackerBean vtBean=new VactionTrackerBean();
while(rsApprList.next()){
vtBean.setApprover((rsApprList.getString("First_Last_Name")));
appr.add(vtBean);
}
}catch(Exception e){
System.out.println("In the Vacation TrackerDAO.java class:"+e);
}
return appr;
}
}
Here is my Servlets which gets the request.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try{
List<VactionTrackerBean> vacBean=VacationTrackerDAO.list();
request.setAttribute("vacTracker", vacBean);
request.getRequestDispatcher("WEB-INF/VacationTracker.jsp").forward(request,response);
}catch (SQLException e){
System.out.println("Error in VacationTracker.java due to VactionTrackerDA.java:"+e);
request.getRequestDispatcher("WEB-INF/Error.jsp").forward(request,response);
}
Here is the code that i have in the JSP page.
<li> <a href="Main.jsp" > home </a> </li>
<li>Vacation Tracker </li>
</ul>
Here is the code for my Javascript
function getHTTPObject(){
var xhr=false;
if(window.XMLHttpRequest){
xhr= new XMLHttpRequest();
} else if(window.ActiveXObject){
try{
xhr= new ActiveXObject("Msxml2.XMLHTTP");
} catch(e){
try{
xhr=new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
xhr=false;
}
}
}
return xhr;
}
function grabfile(file){
var request=getHTTPObject();
if(request){
request.onreadystatechange=function(){ displayResponse(request);};
}
request.open("POST",file,true);
request.send(null);
}
function displayResponse(request){
if(request.readyState==4){
if(request.status==200){
document.getElementById ("middle_sub").innerHTML=request.responseText;
}
}
}

onclick insert in to ms sql database

I have asp.net application with JavaScript and I want to save in to ms sql DB additional information(TimeStamp) when a button is clicked.
onclick= "functionName();"
the function "functionName()" has another task and I want another function that store the timestamp as well
Write JS as below:
function functionName() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var now = new Date(); // You can also any kind of data using query string
xmlhttp.open("GET", "saveTimespan.aspx?datetime=" + now, true);
xmlhttp.send();
}
Write below code to code behind of saveTimespan.aspx' page as below(remove all markup other thanPage` directory of this page):
protected void Page_Load(object sender, EventArgs e)
{
UpdateTimeStamp();
}
public void UpdateTimeStamp()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE TargetTable SET DateTimColumnName = #DateTimColumnName";
cmd.Parameters.AddWithValue("#DateTimColumnName", MyDateTime);
cmd.CommandType = CommandType.Text;
try
{
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
Response.Write("Data Updated Successfully!");
}
}
catch (Exception ex)
{
//Handle exception
}
}
Try using jQuery ajax, would be easier like
function functionName() {
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
}
Ref: http://api.jquery.com/jQuery.ajax/

not receiving data from http inputstream

function sendRequestToDelicious()
{
var xmlhttp=false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
var url = "http://localhost:52271/WebForm1.aspx";
var params = "q=hello";
xmlhttp.open("POST", url, true);
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.send(params);
}
In my ASP.NET app, I am reading the stream from page_load event, but I'm not receiving the data. what am I doing wrong?
C# CODE IN ASP.NET:
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
StreamReader reader = new StreamReader(Page.Request.InputStream);
String data = reader.ReadToEnd();
}
...
It looks like this post contains the precise code for what you are trying to do:
Fake a form submission with C# WebClient
If you just need the data at Page_Load there isn't a requirement to do this with JavaScript- right?
I personally don't use the XmlHttpRequest object any more. I have abandoned it in favor of using the jQuery AJAX functions. The callback function for a successful post would make it easy to capture the response from the server.
Here is an example of how to do it with jQuery AJAX:
$.ajax(
{
type : 'POST',
url : 'http://localhost:52271/WebForm1.aspx',
dataType : 'json',
data:
{
q:'hello'
},
success : function(data)
{
$('mydiv').text(data.msg).show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown)
{
$('mydiv').text('There was an error.').show(500);
}
}
);

Categories

Resources