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

ReactJS - troubleshooting webcam video stream issue

I can't figure out why this code is not working properly. I am able to access the camera stream and see the light on my camera indicating that it's working, but the stream doesn't seem to be attaching correctly. class VideoOutput extends ...

Choose a different option when there is a change

Here is an example of JSON data: [{ "user_id": "113", "employe_first_name": "Asaladauangkitamakan", "employe_last_name": "Nasibb" }, { "user_id": "105", "employe_first_name": "Ryan", "employe_last_name": ...

What makes fastify-plugin better than simply calling a regular function?

I recently came across a detailed explanation of how fastify-plugin operates and its functionality. Despite understanding the concept, I am left with a lingering question; what sets it apart from a standard function call without using the .register() metho ...

AJAX response for form validation

I need to validate my contact form when the submit button is clicked. If all fields are valid, I want to display a Processing message using AJAX, followed by a success message with the entered name. The content of my Form is: <form onsubmit="return va ...

Is there a way to retrieve the content of an element using JavaScript?

I'm currently working on retrieving the value and content of an option element. I've managed to obtain the value using this.value as shown in the code snippet below: <select name='name' id='name' onchange='someFunctio ...

What is the best way to transfer scope to a callback function in the context of node-mysql?

When running the code below, I encounter an error that says client is not defined: var mysql = require('mysql'); var conf = { 'database':'database', 'user':'user', 'password':'password ...

Looping through components using the render template syntax in Vue3

Below is my Vue3 code snippet: <template> {{click}} <ol> <li v-for="item in items" :key="item" v-html="item"></li> </ol> </template> <script setup> const click = ref(); const items = ...

JavaScript array containing objects remains static

I'm facing an issue with a complex array of objects (I will only display the necessary nodes to explain the problem): var arr = [ { json: { doc: { id: 1, atualizacao:{ ...

Utilize Mapbox-GL.JS to animate several points along designated routes

I'm encountering issues with the following example: Animate a point along a route My goal is to add another point and routes in the same map container. Here's what I've tried so far: mapboxgl.accessToken = 'pk.eyJ1IjoicGFwYWJ1Y2t ...

Transform the elements of a tensor in TensorFlow into a standard JavaScript array

Having utilized the outerProduct feature within the TensorFlow.js framework on two 1D arrays (a,b), I am faced with a challenge in obtaining the values of the produced tensor in regular JavaScript format. Despite attempts using .dataSync and Array.from(), ...

Update the URL and parse the data in a Backbone collection

For the purpose of development, I am looking to replace the collection with fake JSON results either from a JSON variable or a JSON file. However, I encountered an error when attempting to do so using url http://jsfiddle.net/qhoc/uZhM8/ GET http://fiddle ...

What is the significance of having nodejs installed in order to run typescript?

What is the reason behind needing Node.js installed before installing TypeScript if we transpile typescript into JavaScript using tsc and run our code in the browser, not locally? ...

Introducing the World of Wordpress Blogging

How can I create an introduction on my WordPress site similar to the one found at ? I am specifically interested in incorporating the expanding horizon line effect. It seems like it may just be a GIF that plays and then fades into the homepage. Are there ...

Having trouble pinpointing the issue with my JavaScript code

Recently, I've been experimenting with JavaScript code snippets and after making some edits to one particular sample, I can't seem to figure out why it's not working. Everything appears correct to me, but here is the code snippet (JSFiddle) ...

Using Double Equal in a JavaScript For Loop

I'm struggling to comprehend why utilizing a double equals (or even a triple equals) in the condition of a for loop doesn't function as expected. Consider this example: for (i = 1; i == 5; i++){ console.log(i) } When I replace == with <= ...

Applying Media Queries Based on Element Height

Situation: In my scenario, there is an image with two buttons below it, all of which share the same width. Issue: When the viewport is too wide horizontally, the buttons are not visible without scrolling down. This poses a challenge for tablets and small ...

Dividing image styles within css

I am trying to incorporate 4 arrow images into a CSS class (up, down, right, left). I started with a basic arrow css class: .arrow { background-repeat: no-repeat; background-position: center; } Next, I created subclasses like: .arrow .up { ...

Maintaining sequential order IDs for table rows even after removing records

I currently have a table structured as follows: <table> <tr> <td> <input type="hidden" name="help[0].id" /> </td> <td> <span class="tr-close">X</span> </tr> <tr ...

Fetching data dynamically using ajax as you scroll

Currently, I am using the jQuery Tools Plugin to create an image slider. However, I am facing a challenge with loading a large number of images all at once. Since the slider is coded in JavaScript, I am not sure how to control the scroll position. I would ...

Struggling to Add Ajax Functionality to Devise on Rails

I am exploring how to implement Devise exclusively through AJAX requests and responses formatted in JSON. Here is the current state of my code: I have initiated with the Devise::RegistrationsController: class Users::RegistrationsController < Devise:: ...