0

I have the following jquery code for a button that works for the most part, but Im missing a step.

$('#download').on('click', function(e) {
    var data = {
        header: $('#header').html(),
        title: $('#title').html(),
        table: $('#nfl').html(),
        rules: $('#rules').html(),
    };

    e.preventDefault();

    $.ajax({
        url: 'print',
        method: 'post',
        data: data,
        success: function(returnValue) {


        }
    });
});

It sends data to the print url that will generate a pdf file that automatically downloads. I can see the code generating the pdf in firebug, but the download does not happen. I never really understood the success: parameter all that well. I think this is where I should edit to get it to work

1
  • set async to false in the ajax call and then try. Commented Aug 2, 2015 at 2:48

2 Answers 2

1

When you say that "the print url ... will generate a pdf file that automatically downloads", I assume you mean, it includes a Content-Disposition: Attachment response header, with the intent that the user can save the pdf locally. I believe in this case you don't actually want AJAX, since it won't allow the user to save the download. Instead, submit an actual form. As long as the response has the Content-Disposition: Attachment header, it shouldn't change the page, but if you wanted to be double safe, you could set the form's target to an iframe or _blank.

$('#download').on('click', function(e) {
    e.preventDefault();

    var form = $("<form>", { action: "print", method: "POST", target: "_blank" });

    $("<input>", { name: "header", value: $("#header").html() }).appendTo(form);
    $("<input>", { name: "title", value: $("#title").html() }).appendTo(form);
    $("<input>", { name: "table", value: $("#nfl").html() }).appendTo(form);
    $("<input>", { name: "rules", value: $("#rules").html() }).appendTo(form);

    form.submit();
});
Sign up to request clarification or add additional context in comments.

1 Comment

This is just what i needed. Thanks
0

The point of the success: hook is so that your code can deal with the return value, which will be whatever the ajax-called script will output.

In this case you will need this function to display the pdf file you've created, which I assume would be setting the source of an iframe or inserting the object returned into the DOM.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.