AJAX call to struts action not working - javascript

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"/>

Related

C# - Sending a XML over to Action result via JavaScript in cshtml

I have a .cshtml file which contains JavaScript function to perform a POST action to my controller class.
<input type="text" placeholder="Username" id="username" />
<button type="submit" onclick="sendResult()">Submit</button>
<script type="text/javascript">
function sendResult() {
let username = document.getElementById('username').value;
try {
let xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "/Test/Test");
xmlhttp.setRequestHeader('Content-Type', 'text/html');
let xml = `<?xml version="1.0"?><query><Username>${username}</Username></query>`;
console.log(xml)
xmlhttp.send(xml);
let xmlResponse;
xmlhttp.onreadystatechange = async function () {
if (xmlhttp.readyState === XMLHttpRequest.DONE && xmlhttp.status === 200) {
xmlResponse = await xmlhttp.responseXML;
console.log(xmlResponse)
}
}
} catch (error) {
console.log(error)
}
}
</script>
In my controller class, I did not manage to receive the xml string (myXML) after clicking on the submit button. Why is that so?
// TestController.cs
public ActionResult Test()
{
return View();
}
[HttpPost]
public ActionResult Test(string myXML)
{
Service1Client o = new Service1Client();
o.Test(myXML);
return View();
}

Controller not receiving data?

i'm trying to send data from a view to a controller using POST but i doesn't seems to work.
Here's my code (javascript function) :
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
var titre = str;
xmlhttp.open("POST", "CheckReturn", true);
//xmlhttp.send(titre);
xmlhttp.send({"titre":titre});
}
}
the html triggering it :
<div id="check-name" class="form-row">
<input id="name" type="text" name="name" placeholder="Titre de l'événement" onkeyup="showHint(this.value)">
<span id="txtHint"></span>
</div>
and finally, the controller SUPPOSED to get it :
[HttpPost]
public ActionResult CheckReturn(string titre)
{
var contexte = new intranetEntities();
var ajax = contexte.evenementiel.SqlQuery("Somequery" + titre);
ViewBag.ajax = ajax;
return PartialView();
}
i checked bit firebug, the data is sent, but with visual studio's debugger, i see that "titre" always stay null.
What can i do ?
I've run into something similar in the past with asp.net but I never really tried to understand what's happening. What fixed it for me was the following:
make a new class somewhere in your back-end (anywhere, doesn't matter for now)
class TitreWrapper {
public string titre {get; set;}
}
then in your controller
[HttpPost]
public ActionResult CheckReturn(TitreWrapper titreWrap)
{
string titre = titreWrap.titre;
}
this should work according to my previous experience
the top answer is wrong (but right in other circumstances I think)
for this problem the following worked:
xmlhttp.open("POST", "/CheckReturn?titre=" + titre, true);
and then just
xmlhttp.send();
OR
xmlhttp.open("POST", "CheckReturn", true);
then
xmlhttp.send("titre=" + titre);

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