Guide on using Ajax to transmit data to Struts2 action class

In my Struts2 web application, I have the following files:

member.jsp:

<script type="text/javascript">    
    String str1 = "aaa";
    String str2 = "bbb";

    xmlhttp.open("GET", "http://localhost:8080/project/editprofile.action", true);
    xmlhttp.send(null); 
</script> 

struts.xml:

<action name="editprofile" method="editProfile" class="controller.ControllerSln">
    <result name="success" type="stream">
        <param name="contentType">text/html</param>
        <param name="inputName">inputStream</param>
    </result>
</action>  

ControllerSln.java:

public String editProfile() throws UnsupportedEncodingException {
    return SUCCESS;
} 

I am looking for a way to use Ajax to send the strings "aaa" and "bbb" to the

controller.ControllerSln#editProfile()
method. Can anyone assist with accomplishing this task?

Answer №1

Your ControllerSln contains two String attributes named str1 and str2. Eclipse will automatically generate their getter and setter methods for you. Next, your action should look like this: http://localhost:8080/project/editprofile.action?str1="+str1+"&str2="+str2; When the action is initiated, Struts will detect these parameters based on their matching names. You can view the values of str1 and str2 by printing them in your editProfile() method.

Answer №2

Provide the full javascript ajax call code in case of simple javascript

<script type="text/javascript>
        function sendRequest()
        {
            var xhr;
            if (window.XMLHttpRequest)
            {
                xhr = new XMLHttpRequest();
            }
            else
            {// Code for IE6, IE5
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
            }
            if (typeof xhr == "undefined")
            {
                responseDiv.innerHTML = "<h1>XMLHttp cannot be created!</h1>";
            }

            else {

                var param1 = "aaa";
                var param2 = "bbb";

                var params = '?param1=' + param1 + '&param2=' + param2;
                var requestUrl = 'sendData' + params;

                xhr.open("GET", requestUrl, true);
                xhr.onreadystatechange = function ()
                {
                    if (xhr.readyState == 4 && xhr.status == 200)
                    {
                        document.getElementById("ResultDisplay").innerHTML = xhr.responseText;
                        // ResultDisplay div where you want to show the AJAX response
                    }
                }

                xhr.send();
            }
        }
</script>

}

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

Failure to inherit props in child components when using React-Redux

I've been following a React-Redux tutorial and encountered an error in the first part of the section titled "React Redux tutorial: asynchronous actions in Redux, the naive way". Post.componentDidMount src/js/components/Posts.js:12 9 | ...

Is it possible to Use Vuejs 2 to Update MathJax dynamically?

Just figured out how to resolve this issue. Simply bind the data using v-html <div id="app"> <h1 v-html="equation"></h1> <button @click='change'>Change</button> </div> var vm ...

Issue with Jquery UI draggable positioning in a specific Reveal.js slide

While my jQuery draggable feature works flawlessly in a simple HTML page without the presence of reveal.js, I encounter an issue within my reveal.js presentation where I utilize embed=true [utilizing only a portion of the full page for each slide]. When i ...

Enhancing Highcharts: Extending Tooltip Functionality

My dataset contains a collection of data points that I want to display in a Highcharts chart. Here is an example of how the data looks: mydataset = [{ x: 1, y: 3, names: ["John", "Jane"] }, { x: 2, y: 4, names: ["Alice", "Bob"] }] ...

Create a server directory structure that populates multiple HTML dropdown lists using either jQuery or AJAX

As a novice navigating jQuery and Ajax, I find myself faced with a specific challenge. My current situation involves a structured set of directories on a server. My goal is to populate a dropdown dynamically with this file hierarchy. Upon click ...

HTML5 canvas processing causing web worker to run out of memory

Within the Main thread: The source image array is obtained using the getImageData method. It is represented as a uint8ClampedArray to store the image data. Below is the code executed in a web worker: (This operation generates a high-resolution image, but ...

Updating a Mongoose document without overwriting existing values using FindOneAndUpdate

I have the following schema: { guildId: { type: String, required: true, unique: true }, systems:{ reactChat:{ type: Array, required: true, ...

How can I open a new window, redirect the current one, and bring focus to the new window using JavaScript?

Trying to troubleshoot a problem I'm having with the following setup: - Using SAP Portal, I am launching an HTML page containing this code. - The goal is for the HTML page to open a new window. - Once the new window opens, the original HTML page ...

Ways to retrieve the content of a text box within a cell

Here is the code snippet I am currently working with: <tr val='question'> <td> <input style='width: 500px' type='text' placeholder='Q.Enter your question here for radio button? '> </ ...

Using TypedArray as a parameter in a Cordova plugin

I've been working on a plugin specifically for Cordova 3.3. Within my JavaScript code, I'm in the process of downloading a PDF file which is being stored as a uInt8Array. download: function ( ) { var xhr = new XMLHttpRequest(); ...

Troubleshooting issues with hint functionality and fullscreen mode in CodeMirror within a jQuery layout

I have integrated the codeMirror library into the UI Layout Plug-in on my website. Challenges: When using CodeMirror within the layout, the Full Screen Editing feature does not work as intended. Press F-11 to zoom in and Esc to exit full screen mode. I ...

Disregard any labels when it comes to clickable areas for mouse events

Here is a simple example in JSFiddle where a text is displayed over an image inside a div element. Depending on where the cursor hovers, it can exhibit three different behaviors: pointing hand over the image, allowing text selection over the content of the ...

How can I render just one event instead of all events when using the eventRender callback function?

I am currently working on adding an event to my calendar using a JSON format with specific attributes like id and start time. Here is what I have tried so far: $('#calendar').fullCalendar('renderEvent', my_event); $('#calendar& ...

Utilizing the power of Vue 2 and NuxtJS to effortlessly customize the appearance of child components

I am currently working on a Nuxt.js project (still using Vue 2) that consists of two components. I am trying to override the child style with the parent's style, but the ::v-deep pseudo selector doesn't seem to be effective. Regardless of my eff ...

What steps can be taken to guarantee that React updates occur in the correct order?

I'm currently working on developing a multi-select dropdown and facing the issue of hiding the options once a user selects one. The problem arises when I try to update the selectedCategoriesData state and then hide the dropdown using setShowCategories ...

Popper.js failing to initialize during page load

After attempting to initialize Popper.js as shown below, I am encountering an issue where nothing is happening. $().ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); Interestingly, when I apply the same code to a button, it w ...

Tips for integrating JavaScript libraries with TypeScript

I'm looking to add the 'react-keydown' module to my project, but I'm having trouble finding typings for it. Can someone guide me on how to integrate this module into my TypeScript project? ...

Has anyone figured out the issue with Uplodify? It suddenly ceased to function

For some time now, I've been using uplodify without any issues. Unfortunately, as of yesterday, it suddenly stopped working. I'm at a loss as to what might have caused this sudden change. Could someone please offer me some assistance? I've ...

Update and remove data using JavaScript in a Spine.js application

I am in the process of building a small API using Node.js (Express) for my Spine.js application. So far, I have successfully implemented functionality to retrieve and create new objects in the database. However, I have encountered an issue when it comes to ...

Expand the HTML Template and Resize Children to Fit the Window

My software creates HTML email templates that typically range from 600px to 650px in width, but can sometimes be as wide as 900px. The templates have nested table elements for email clients, with all dimensions specified in fixed pixels rather than relativ ...