Utilizing Ajax, Jquery, and Struts2 for File Uploading

Can someone please provide guidance on uploading files using a combination of Ajax, jQuery, and Struts2? I have searched through numerous tutorials online but haven't found a suitable solution yet. The goal is to trigger a JavaScript function when a button is clicked. This function should initiate the Ajax engine, which will then call a Struts action to receive a response. Importantly, this request and response should occur without refreshing the page or relying on IFrames.

Answer №1

Utilizing an iframe allows me to submit data without the need for a page refresh.

i) The structure of my HTML code is as follows:

1) Include a form tag. // You can simply copy and paste my form tag, just remember to modify the action attribute

2) Specify target="my_iframe" // This is the name of the iframe, it can be any chosen name

<div class="bp_up_input">
  <form name="banner_image_uploads" id="banner_image_uploads" method="post" action="" target="my_iframe" enctype="multipart/form-data">
    <span>
      <input type="file" name="banner_image" class="my_vld" lang="Image_path" />
      <input type="button" id="banner_image_upload" value="Upload" class="bp_button_style" />
    </span>
    <input type="hidden" name="slt_store_id" value="" />
    <input type="hidden" name="sld_location" value="" />
  </form> 
</div> 

ii) Here is my JavaScript code snippet:

$('#banner_image_upload').live('click',function(){
  if($.trim($('input[name="banner_image"]').val()) != '' && $.trim($('select[name="bp_location"]').val()) != '' && $.trim($('#store_names').val()) != ''){
    $("iframe").remove(); // Remove previous iframe if one exists

    $("body").append('<iframe id="my_iframe" name="my_iframe" src="" style="display:none;"></iframe>'); // Add an iframe with the ID 'my_iframe' to the body

    $('#banner_image_uploads').submit(); // Submit the form with the ID 'banner_image_uploads'

    $("#my_iframe").load(function(){
      var val = $("iframe")[0].contentDocument.body.innerHTML; // Using PHP, I echo the desired response which is stored in the 'val' variable.

      var data = val.split(':'); // Splitting the variable by :

      // Below section can be skipped if not required
      var html = '<tr><td><img width="800" height="60" border="0" src="/assets/store_banners/live/'+$.trim($('input[name="sld_location"]').val())+'/'+data[1]+'" id="'+data[0]+'"><a href="#nodo"><img src="/images/delete_trash.png" width="9" height="12" class="image_delete" style="padding-left:37%;"/></a></td></tr>';
      
      $('.bp_table tbody').append(html); // Appending the uploaded image to the desired container

      $('input[name="banner_image"]').val(''); // Clearing the file name on successful upload
    });
  } else {
    alert('Please Select filters');
  }
});

Answer №2

Greetings, I have successfully tested the code below and found it to be effective. I trust that it will assist you as well.

JavaServer Pages Code:

<div id="uploadImg">
     <s:form id="uploadImgForm" action="strutsaction" method="post" enctype="multipart/form-data">
            <s:file name="imgFileUpload" label="Choose file to upload" accept="image/*"></s:file>
            <s:submit value="Upload" align="center" id="uploadImgSubmitBtn"></s:submit>
     </s:form>
<div>

JQuery Function:

$("#uploadImgSubmitBtn").click(function(e){

    // Retrieve form data
    var form = $('#uploadImgForm')[0];

    // Create FormData object
    var data = new FormData(form);

    $.ajax({
        type: "POST",
        enctype: 'multipart/form-data',
        url: "strutsaction.action",
        data : data,
        cache: false,
        processData: false,
        contentType: false,
        success: function(data){
            $('#uploadImg').html(data);
        }
    }); 
});

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

The local authentication feature in NodeJS Passport is experiencing issues and not functioning properly

I have integrated passportjs local for authentication. However, I am facing an issue where it always redirects to the failureRedirect without displaying any error messages. The redirect also includes the original username and password, resulting in a dupli ...

I am experiencing an issue with the functionality of Handlebars registerPartial()

Check out my code snippet on JsFiddle Error Message: Uncaught Error - The partial social could not be found Note: I have made sure to include all necessary libraries. Looking forward to your assistance. Thank you! ...

Clicking on the image "Nav" will load the div into the designated target and set its display to none. The div will

Can someone help me with loading a div into a target from an onclick using image navigation? I also need to hide the inactive divs, ensuring that only the 1st div is initially loaded when the page loads. I've tried searching for a solution but haven&a ...

What is the process for creating URL query parameters?

What is the process for generating parameters after node?_=xxxxxx? If I am using a Python script to access the URL, how can I retrieve these parameters? edit: I apologize for not providing enough information. This is my first post as a novice. I am atte ...

Receiving a blank array from the firestore database

I have written a code for the LeftBar Component where I am trying to retrieve data stored in the "contacts" document in Firebase. However, I am getting an empty array and I'm not sure why this is happening. Additionally, I would like to know how to ac ...

Issue encountered while subscribing to SalesForce topic using Node.js

Attempting to subscribe to a SalesForce topic through a Node.js server using the code provided in the JSForce documentation: conn.streaming.topic("InvoiceStatementUpdates").subscribe(function(message) { console.log('Event Type : ' + message.ev ...

Switching images dynamically using Flask and JavaScript

I'm currently working on Flask and encountering a perplexing issue. I'm attempting to update an image using JavaScript, but I am getting these errors from Flask: ... 12:05:34] "GET / HTTP/1.1" 200 - ... 12:05:38] "GET /img/pictur ...

Organizing a NodeJS module - properties and functions

I've been struggling to structure my NodeJS application with modules, and after hours of searching, I haven't found a definitive answer. Let's say I want to create a "user" module for creating new users in my code: var newUser = new User(); ...

Form submission is not possible while the login form is active

I'm encountering an issue where I am unable to trigger - ng-submit or ng-click on this code except for the local onclick function on the login button. If you have any insights or solutions, please share them: <form ng-submit = "login.submitLogin ...

The binding in Knockoutjs is working properly, but for some reason the href attribute in the anchor tag is not redirecting to

Here is the HTML code snippet I am working with: <ul class="nav nav-tabs ilia-cat-nav" data-toggle="dropdown" data-bind="foreach : Items" style="margin-top:-30px"> <li role="presentation" data-bind="attr : {'data-id' : ID , 'da ...

removing the mapStateToProps function will result in an undefined value

I am new to React and I'm in the process of converting a class component to functional components using hooks. I need some guidance on safely removing 'mapStateToProps' without encountering undefined errors. I have two pages, A.js and B.js. ...

When utilizing ASP.NET Core Razor pages for file uploads and utilizing AJAX Post to send the file to an IFormFile handler, the request

I have a straightforward task that involves uploading a file and using AJAX to post it to the Index page: <input type="file" id="file-selector" accept=".txt"> Here is the corresponding Javascript: const fileSelector ...

Tips for updating the content within an HTML tag with jQuery

I am looking to update the parameter value of an applet tag based on the selection from a dropdown menu. As I am new to jQuery, I would appreciate any guidance on how to achieve this using jQuery. This is my current applet code: <applet id="decisiontr ...

Trouble with Vuex Store: Changes to table values not reflected in store

I've been tackling a table project using Quasar framework's Q-Popup-edit and Vuex Store. The data populates correctly initially. However, any changes made on the table do not seem to persist and revert back to their original values. Here is a s ...

Steps to resolve eslint error in cases of using the node: protocol for importing Node.js built-in modules

Can someone guide me on what to include in my .eslintrc file for my specific situation? Link 1 Link 2 If I disable this rule, I encounter the following error: import path from "path"; // ESLint: Prefer `node:path` over `path`.(unicorn ...

Django Vue3 encounters access-control-allow-origin restriction

I am currently working on a Django rest-api project that uses Vue on the front-end. Unfortunately, I encountered an error while making requests via Vue: Console output: The following error is displayed: Access to XMLHttpRequest at 'https://api.iyziw ...

Encountering an issue: Module not found - 'cryptile' during express js installation

Just dipping my toes into the world of Node.js and I'm encountering some obstacles when trying to install Express.js. Seeking assistance in resolving this issue and successfully setting up Express.js. https://i.stack.imgur.com/PlHiB.png Interestingl ...

Encountered difficulty accessing the controller ActionResult from JavaScript代码

Resolution: After thorough investigation, I successfully identified and resolved the issue. Surprisingly, it was not related to the Javascript or Controller code as initially anticipated. The root cause stemmed from a .dll file that was causing discrepanci ...

Accessing information from a JSON array

I am encountering difficulties in fetching data from a JSON file. Whenever I click the button, it triggers the call function which then retrieves data from the json.jsp file containing an array. However, I am unable to retrieve the data successfully. Below ...

Exploring Angular unit testing using Jasmine: Techniques to customize or delete spyOn

Current software versions for AngularJS and Jasmine: AngularJS v1.2.26 Jasmine v2.2.0 I am facing an issue with a spyOn. When attempting to change or remove its behavior, I encounter the following error message: Error: getUpdate has already been spied u ...