Is there an issue with invoking Spring controller methods from JavaScript (via ajax) that is causing them

Using JavaScript to send a request to a method in Spring controller, the code looks like this:

<script language="javascript" type="text/javascript">
          var xmlHttp
          function show()
          {   
              if(typeof XMLHttpRequest != "undefined")
              {
              xmlHttp= new XMLHttpRequest();
               }
              else if (window.ActiveXObject)
              {
                  xmlHttp= new ActiveXObject("Microsoft.XMLHTTP");
              }
              if(xmlHttp==null)
              {
                  alert("Browser does not support XMLHTTP Request")
                  return;
              }
              var FAC_LICENSE_NO=document.getElementById("FAC_LICENSE_NO").value;
              //var url="/Final/WEB-INF/jsp/SurrenderViews/Ajax.jsp";
              var url="http://localhost:8080/Final/Ajax.FSu";
              url +="?param1="+FAC_LICENSE_NO;
              alert(url);
              xmlHttp.onreadystatechange = stateChange;
              xmlHttp.open("GET", url, true);
              xmlHttp.send(null);         
            }   
          function stateChange()
          {   
                if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
                {
                    document.getElementById("factoryname").innerHTML=xmlHttp.responseText
                }
         }
    </script>

and the corresponding controller is:

public class PhaseTwoFormSurrenderOfLicense extends MultiActionController implements Connections {

     public ModelAndView DataInput(HttpServletRequest request,HttpServletResponse response) 
     {
         return new ModelAndView("SurrenderViews/DataInput");
     } 
     public String Ajax(HttpServletRequest request,HttpServletResponse response) 
     {
           System.out.println("Maritammanafvara");
           String returning="<input type=\"text\" style=\"border: none\" name=\"Factory_name\" readonly=\"readonly\" value=\"HIHI\">";
           return returning;

     } 
}

However, while I can successfully call both DataInput and Ajax methods from an HTML anchor tag, calling them from the XMLHttpRequest object isn't working. Can anyone help me identify the issue?

Answer №1

Could you please attempt using var location="Ajax.FSu";

rather than

var location="http://localhost:8080/Final/Ajax.FSu";

Answer №2

Have you considered utilizing a library for handling AJAX requests? jQuery offers convenient methods for this purpose: api.jquery.com/category/ajax/

For instance:

$.ajax("http://website.com/Final/Ajax.FSu").done(function (data) {
    // manipulate the data here
}).fail(function () {
    // handle failures here
});

It's essential to properly encode the URL instead of hardcoding the localhost part. Spring MVC provides a useful tag for generating URLs automatically:

<spring:url value="Final/Ajax.FSu" />

Using this tag will output the generated URL, and with:

<spring:url value="Final/Ajax.FSu" var="yourURL" />

You can reference the URL stored in the context variable within your JSP files like so:

<a href="${yourURL}">Link</a>

Answer №3

There is no mention of the methodNameResolver in your code snippet, which Spring relies on to direct URLs to MultiActionControllers. It could be a built-in resolver like PropertiesMethodNameResolver or one you have developed yourself. Below is an excerpt of my dispatcher configuration:

    <bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
    <property name="paramName" value="method" />
</bean>


<bean class="your.controller">
    <property name="methodNameResolver" ref="methodNameResolver" />
</bean>


public class YourController extends MultiActionController

    public ModelAndView abcdef(...){

    }
}

This setup will handle requests to URLs containing ?method=abcdefg.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to utilize both the /app and /pages folders in my Next 13 application?

I am currently working on a project where the /app folder is utilized as the primary route container. However, we have encountered performance issues on localhost caused by memory leaks identified in an issue on the Next.js repository. I am curious to fi ...

If an iframe contains a div with a particular class inside, then execute the following code

I need to dynamically add a class to the parent element if a specific class is present in its child. The issue: the content is within an iFrame and I'm not very proficient with jQuery. It doesn't necessarily have to be jQuery, any alternative m ...

An effective method for targeting a specific button within a CSS file

I have multiple button tags in my code, but I need to style a specific one using CSS. How can I target this particular button and apply styles only to it while leaving the others unchanged? Do I need to assign the button to a variable and reference that va ...

Clicking on the input triggers the appearance of a border using the OnClick function

I am currently developing my own website with a login feature that requires input tags of text-type. I would like to implement a functionality where clicking on these input tags will display a border, even when the mouse is not directly hovering over them. ...

The malfunctioning Laravel 5.8 Likes feature: AJAX Post Request Issue

Struggling to implement a Like system for my recipe app using Laravel. My AJAX POST request isn't reaching the controller, preventing me from storing any likes. I've established relationships between three models - Like, User, and Recipe. Here& ...

Encountering a classnotfound exception with JSP JDBC SERVLET, but all code appears to be

index.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> < ...

Is it secure to use console.time() in a Node.js environment?

Looking at a small snippet of node.js code, here's what I have: console.time("queryTime"); doAsyncIOBoundThing(function(err, results) { console.timeEnd("queryTime"); // Process the results... }); Running this on my development system gives m ...

Ways to retrieve every element inside a specific div container

Is there a way to select all elements inside a div except for specific ones? For example, consider the following structure: <div id="abc"> <div class="def"> sagar patil</div> <div class="pqr"> patil</div& ...

The npm copy script is not functioning properly on the Windows 8.1 operating system

I am working on a sapui5 project and I need to execute the following npm script from my package.json: "scripts": { "flatten": "copy -r \\dist\\resources\\test\\commonjslib\\* dis ...

How can an Embedded React + JSS component safeguard generic elements such as <button> and <p> from being affected by the page's style?

I am facing a challenge with a React component that is being embedded in various webpages, either through an extension or as a third-party tool. Most of the styling for this component is done using JSS, ensuring unique class names that cannot be overridde ...

Issue with 'firebase.auth is not defined' error following SDK update

I've been using the Firebase JS sdk for web development without any issues for a year now. However, after recently updating my code from version 5.3.1 to the latest 6.5.0 SDK version, I encountered the following error: TypeError: firebase.auth is no ...

ACE.js enhances website security through Content Security Policy

I've been working on setting up a helmet-csp with ace running smoothly. Here's how my helmet-setup looks: var csp = require("helmet-csp"); app.use(csp({ directives: { defaultSrc: ["'self'", "https://localhost:8000"], ...

Invalid controller function path specified in Laravel framework for AJAX request

I am struggling to find the correct ajax URL as the one I am currently using is not working. The console shows the following error message: GET XHR localhost:8000/Controller/getUnitSellingPrice [HTTP/1.0 404 Not Found 203ms] In the create.blade View: ...

Converting SearchHit to Java Object within ElasticSearch

I am currently facing a challenge in my project where I need to extract data from an ES query and convert each retrieved hit into a Java Object. The process of transforming the hits from JSON to Java Objects using Gson seems inefficient to me. Here is an ...

The variable for Google Maps has not been defined

I'm currently working on developing a map that will display multiple markers based on custom posts with metaboxes. The end goal is to have a map showing markers with the post title, some description, and a link to the post. Although I feel like I&apo ...

Explorer not displaying or loading jQuery/Ajax content

Currently, I have been experimenting with a template heavily reliant on jquery and javascript. My main focus lately has been learning more about jquery and javascript. You can find my site at . The functionality of the site is smooth in Firefox and Safari, ...

Getting information from a database using PHP and AngularJS through the $http.get method

Currently, I am utilizing an AngularJS script to retrieve data from an external PHP file that is encoded in JSON within an HTML page. The method $http.get(page2.php) has been employed to fetch a JSON-encoded array located in another file. However, the issu ...

Steps to activate highlighting for the initial value in a quarterly datepicker

Concerning the quarterPicker feature in the Bootstrap datePicker (SO: how-to-change-bootstrap-datepicker-month-view-to-display-quarters, jsfiddle: jsFiddle): Is there a way to highlight an initial value upon startup? I have tried setting a value in win ...

Replicate and modify the settings on a fresh radio inspection

In my approach, I am avoiding direct HTML editing and instead utilizing JavaScript/jQuery to accomplish the desired outcome. Initially, one input (specifically 'Express Shipping') is pre-selected by default. The goal is to clone/copy the HTML co ...

The React Component is not displaying any content on the webpage

I developed a Reactjs application using the create-react-app. However, I am facing an issue where the components are not displaying on the page. I suspect that App.js is failing to render the components properly. Take a look at my code: App.js import R ...