Obtaining a pdf file using javascript ajax is a straightforward process

Looking to access my JavaScript file generated by a microservice (byte[]):


public int retrieveLabel(Request request, Response response) throws IOException {
    response.header("Access-Control-Allow-Origin", "*");
    ArrayList<JSONObject> orders = generateJSONList(request.queryParams("orders"));
    response.header("Content-Type", "application/pdf");
    ServletOutputStream outputStream = response.raw().getOutputStream();
    outputStream.write(generatePDF(orders));
    outputStream.flush();
    outputStream.close();

    return 200;
}

Want to receive the response via ajax:


$("#printlabels").click(function() {
    var jsonData = $(this).data().ordersJson;
    console.log(jsonData)
    $.ajax({
        // type: GET,
        async: true,
        url: "http://localhost:60000/api/create-label",
        data: {orders: jsonData},
        success: function(resp){
            ???;
        }

    });
});

Desiring for the browser to either open or save the PDF file

Answer №1

Avoid using ajax, consider the following approach:

$("#printlabels").on("click", function() {
    var jsonData = $(this).data().ordersJson;

    var url = "http://localhost:60000/api/create-label";
    var $form = $('<form method="get" action="' + url + '" target="_blank" />');

    for (var key in jsonData) {
        $form.append('<input type="hidden" name="' + key + '" value="' + jsonData[key] + '" /> ');
    }

    $form.submit();
});

Find out why ajax is not suitable for this task:

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

Maintaining form data while dynamically including more instances of a <div> element to the form

I am currently developing a SpringMVC Webapp with a view that contains a dynamic form. The dynamic elements of the form are listed below: At the moment, I am passing the variable ${worksiteCount} from my controller to the view (stored in my portlet sessio ...

What is the optimal arrangement for constructors or classes in JavaScript code?

Constructors, being objects that are stored as copies, appear to behave similarly to variables in terms of their placement within the code. Unlike functions, constructors cannot be placed "anywhere" and must instead be positioned above the area where they ...

Sending data from MongoDB API to HTML in Electron using parameters

I am currently developing an Electron application for my personal use and utilizing MongoDB Atlas as the backend for my Node application. As I am relatively new to Electron, I am still experimenting with different approaches, so there might be some minor m ...

Compatibility issues between XMLHttpRequest and curl

Today, I am attempting to create a small XHR in JavaScript, Java, and C#, but it's not working for some reason... Below is the code snippet: var xhr = new XMLHttpRequest(); function init(){ xhr.open("POST","http://www.opsu.gob.ve/portal/controles/ ...

Steps to load a script when the document is ready:

What is the best method to include JavaScript using the following code: <script type="text/javascript" src="http://uads.ir/l.php?s=125125&w=5307cd5c027373e1773c9869"></script> only after the page has fully loaded? $(document).ready(funct ...

The required element was not discovered

Whenever I attempt to execute npm run serve, it reaches 98% completion and then halts, displaying the following error message: An issue occurred while compiling with a total of 1 error: ...

Determine the size of a BSON object before saving it to a MongoDB database using

I am currently in the process of determining the best way to calculate the size before storing certain data in MongoDB. After writing a script that parses and combines data into a single document, I have encountered an error when trying to use instance.sav ...

Node.js is indicating that the certificate has expired

When using Mikeal's request library (https://github.com/mikeal/request) to send an https request to a server, I keep encountering an authorization error of CERT_HAS_EXPIRED. request({ url: 'https://www.domain.com/api/endpoint', ...

How can I align rectangles with different heights to display side by side using Javascript?

Currently, I am designing a press page for a website where the headlines/articles are displayed in rectangles. To achieve this layout, I am using the following CSS: .press-blocks{ column-count: 4; column-gap: 2em; padding-left: 10%; padding ...

Using jQuery UI tabs with AJAX responseData

I have a collection of items labeled A, each containing a subset of items called B. The presentation of the B items within A is designed to appear as tabs using jQuery UI tabs. To display the list of A items on a page, I utilize a controller, and then load ...

Sending a file through an Ajax POST request to a PHP server

I am attempting to upload the HTML input file to my PHP file using a different method than the traditional synchronous HTML forms. The problem I am encountering is that it seems like I am not correctly POST'ing the input file to my PHP file because t ...

Disparity in React app: Misalignment between debugger and console output

Throughout the years, I've encountered this issue in various ways, and I have finally been able to articulate it. Take a look at the code snippet below: import React, {Component} from "react"; import aFunction from "./Function"; export default class ...

Writing a CSV file to AWS S3 proves to be unsuccessful

I have been working with TypeScript code that successfully writes a CSV file to AWS S3 when running locally. However, I have recently encountered an error message: s3 upload error unsupported body payload object NOTES: The code is not passing creden ...

I am encountering issues with my PostCSS plugin not functioning properly within a Vue-cli 3 project

I developed a custom postcss plugin that was working perfectly according to the postcss guidelines until I tried to implement it in a real project. For reference, here's the plugin on GitHub My goal is to integrate it into a Vue-cli app using Webpac ...

Administering User Settings for Subsequent Visits

My website now includes a notification feature for showcasing new updates. The notification is strategically placed at the top of the website to capture users' attention. With the help of jQuery, I have created a function that allows users to hide the ...

Issue with AddToAny plugin not functioning properly on FireFox

I’m having issues with AddToAny for social media sharing on my website. It seems like FireFox is blocking it because of tracking prevention measures. Error Message in Console: The resource at “https://static.addtoany.com/menu/page.js” was blocked d ...

Working with AngularJS's $q promise and socket.io

I am interested in creating an angularJS promise that can work seamlessly with socket.io. Currently, I have a callback function set up to handle the response like this: function request(event, data, callback) { socket.emit(event, data); socket.on( ...

Unable to store cookie using jQuery on Internet Explorer 9

Having trouble setting a cookie on IE9 and can't figure out why. My objective is to create a cookie that expires after a year, using the code below: $.cookie( name, value, { expires:days } ) where days equals 365. However, the cookie disappears as s ...

Ways to calculate the memory utilization of a JavaScript object

Suppose I want to compare the efficiency of storing bits of a static canvas/image with Alpha more or less than 0.5 using an "array of array of number" versus an "array of string," which would be better in terms of memory usage and speed? var c = $('m ...

Using PHP to accept a single file that has been transmitted via XHR Level 2

Although the question may seem basic, I am having trouble figuring it out. When using this method to send a file: $scope.uploadFile = function(file) { if ($scope.XHR2Support()) { var xhr = new XMLHttpRequest(); xhr.upload.onprogress = ...