Is there a way to transfer data depending on certain conditions?

I am working on a page where users can choose to email a single file or multiple files. Both options call the same page email.jsp with their corresponding JavaScript functions.

In the email.jsp page:

 String files=null;
        String url=null;
        String id=null;
        String hash=null;
        String[] array=null;
        String[] split=null;


        if(multiemail.equals("no")) {

           //get parameters from email()


           files= request.getParameter("filename");
            url = request.getParameter("link");
            id = request.getParameter("id");
            hash = request.getParameter("hash");

       }else{

            split = request.getParameter("link").split(",",0);
            array = request.getParameter("arrayList").split(",",0);

        }

This logic retrieves four parameters for single emails and two parameters for multiple emails. Next, once these attributes are obtained, I need to pass them to sendemail.jsp to process the data.

To achieve this, the send button triggers the sendmessage() function:

$.ajax({

               url: 'sendemail.jsp',
               type: 'POST',
               data: {
                   recipient: recipient,
                   subject: subject,
                   content: content,
                   id:"<%=id%>",
                   hash:"<%=hash%>"


               },

               success: function (data) {
                   alert("Successfully initiated email to queue");
               },
               error: function (request, error) {
                   alert("Request: " + JSON.stringify(error));
               }
           });

The AJAX call passes data as expected for single emails. However, when sending multiple emails by clicking the same send button, it still includes the unnecessary parameters id and hash which are not required based on the email.jsp code logic.

Now, I wonder if there is a way to conditionally pass data based on specific requirements?

Answer №1

Yes, it is definitely possible to achieve this.

To accomplish this task, you need to set up a condition before initiating your ajax call. Inside the curly braces of the if statement, you can make an ajax request with the required parameters. If you have multiple conditions to check, you will need to write separate ajax requests for each condition.

Below is an example of JavaScript code that demonstrates how to handle this scenario:


files = request.getParameter("filename");
url = request.getParameter("link");
id = request.getParameter("id");
hash = request.getParameter("hash");

// Javascript Code

if (files !== '' && url !== '' && id !== '' && hash !== '') {
    $.ajax({
        // Ajax code for all parameters provided
    });
} else if (id !== '' || hash !== '') {
    $.ajax({
        // Ajax code for partial parameters provided
    });
}

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 io.on connection event is being activated for each emit

Each time an event handler is triggered on my socket.io, the io.on connection function is called first. For instance, in a chat application I created, every time I send a message (emit it to all clients), it triggers the io.on connection and then proceeds ...

What causes variations in the appearance of my JButton on various computers?

For my application, I have been using JButtons with different colors which was achieved by setting the background color using btn.setBackground(col);. Surprisingly, while it worked perfectly on my computer, on another system the button appeared gray instea ...

The impressive 3D environment rendered by three.js appears crisp and detailed in Chrome, yet lacks clarity in Firefox

When viewing the same three-dimensional scene created using three.js, the clarity differs between Chrome and Firefox: Chrome (clear): Firefox (blurred): ...

Continuously tapping on overlapping slides

I encountered an issue where the slide that I set the opacity to 0 on is still clickable, despite setting pointer events to none. In my slideshow, consisting of 2 slides, clicking on the first slide redirects me to the hyperlink of the second slide. Chec ...

Fetching data from a URL using AngularJS while the view is being loaded

Struggling to perform an API call when loading a specific view. controllers.controller("detailsCtrl", ["$scope", "$routeParams", "$filter", "$http", function($scope, $routeParams, $filter, $http) { $scope.getCurrent = function(url, id, callBack, apiCal ...

Exploring the Depths of Multidimensional JSON Arrays in PHP

I am currently working on developing a web-based file manager that allows me to organize, view, create, edit, and delete folders and files. In order to store information about these folders, files, and subfolders, I am in need of an appropriate data struct ...

Display thumbnail images in jquery-ui dropdown menu

Hello, I'm looking to display a small image (the user's thumbnail) on the jquery-ui dropdown by making an ajax call. As someone new to ajax and unfamiliar with jquery-ui, I would appreciate some guidance in the right direction. Thank you! HTML/J ...

What is the best way to transform a date such as '2021-06-01T11:17:00-07:00' into the corresponding date and time for a specific location (New Delhi) using JavaScript?

How can I convert a date in the format '2021-06-01T11:17:00-07:00' to ISO standard? What does this format represent? let date = new Date('2021-06-01T11:17:00-07:00'); console.log(date.getHours() + " :" + date.getMinutes()); I ...

Is it possible to avoid sending multiple $http requests in Angular? Are there more efficient methods available?

I have developed a rather intricate method for retrieving resources using $http. This method returns a promise and first checks my local cache to see if the resources are already available. If they are, it will return the cached data; if not, it will make ...

Unable to align view to the center in RelativeLayout

I'm attempting to center a view within a parent RelativeLayout: private void addLoadingAnimation() { RelativeLayout mainView = (RelativeLayout) findViewById(R.id.medical_supply_tile_activity); mainView.removeAllViews(); GifView gifView = ...

Unable to incorporate a subpackage into Java code

Does anyone have any solutions for this issue?: I'm facing an error while trying to import a sub package in my Java code. When running javac Pixel.java, the following error occurs: Pixel.java:2: error: package image.color does not exist. I've ...

How can I transform this statement into a higher-order function that offers a resource instead of using an object for initialization and destruction?

Starting with this code snippet: convert utilizes svgInjector to start and terminate a resource. export async function convert( serializedSvg: string, svgSourceId: string, containerId: string ): Promise<string> { const svgInjector = new SvgI ...

Exploring data visualization through object classification in Angular JS

I am facing a scenario where my API returns a single JSON Object if there is only one element in the response, and an array of objects if there are more than one elements. This poses a challenge as I need to handle both cases without changing the JSON stru ...

Running Windows commands from Node.js on WSL2 Ubuntu and handling escape sequences

When running the following command in the CMD shell on Windows, it executes successfully: CMD /S /C " "..\..\Program Files\Google\Chrome\Application\chrome.exe" " However, attempting to run the same comman ...

Preventing the control flow from reaching the After method in the event of an exception

I am currently using Cucumber in conjunction with Selenium. There is a specific scenario where my code searches for certain objects, utilizing methods such as objectExists(WebElement). This method then calls WebDriverWait() and is enclosed within a try cat ...

How can we integrate Cordova plugins into Vue-Cordova framework?

Looking to integrate Vue-Cordova with Cordova-plugin-file-opener2 to open PDF files within iOS/Android applications. In the Vue-Cordova setup, plugins related to the device are defined on the data property of the App vue instance: data: function () { ...

How can I access URL parameters sent with XmlHttpRequest in GET method in an aspx page?

I need to extract the two parameters that have been passed in the URL. // Using an XMLHttpRequest to read a text file var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); alert("Object created"); } al ...

When using the executeScript() method, it unexpectedly gives a null result instead of allowing me to scroll

The following code snippet is used to scroll horizontally within a web page: WebElement element=driver.findElement(By.xpath("//div[@class='table-wrapper']")); JavascriptExecutor js=(JavascriptExecutor)driver; js.executeScript("arguments[0].scroll ...

Incorporate VLC player into a webpage without any visible control options

Is there a way to embed a flash video in a webpage without showing any controls? I managed to embed a flash video using VLC with the following code: <embed src="img/Wildlife.wmv" height="480" width="640"> However, I want the video to play without ...

Storing a jQuery variable in WordPress AJAX and displaying it in PHP - how to achieve this in function.php?

Can jQuery variables be sent to function.php and used in a PHP function? Possibly through AJAX. This question is theme-related and does not involve using a plugin. For example, CSS classes are added to posts on the client side using jQuery when clicked. ...