lundi 15 juin 2020

Not able to download Pdf/Excel with JQuery AJAX get request with some data sent with get request

I am trying to Send some data with GET/POST request to the server.

Then server prepares a PDF( using mpdf library) and sends it back to the client.

FrontEnd Code to Send GET/POST request with data is as follows.

$("#edit_setting").click(function () {
        $.ajax({
            url: "http://localhost:8000/get_pdf",
            type: "POST",
            data: {
                data : {
                    "abhinav" : "kumar keshari"
                }
            },
            headers: {
                'Accept': "application/json",
                'Authorization': 'Bearer ' + getCookie(ACCESS_TOKEN),
            },
            success: function (data, textStatus, request) {
                let w = window.open('about:blank');
                w.document.open();
                w.document.write(data);
                w.document.close();
            },
            error: function (XMLHttpRequest, data) {
                console.log("something went wrong.");
                console.log(data);
                console.log(XMLHttpRequest.status);
                console.log(XMLHttpRequest.responseJSON);
            }
        });
    });

On server side the Controller sends a PDF.

class DownloadPdfController
{
    public function store(Request $request){
        $data_received = $request->data;
        error_log(print_r($data_received,true));
        $mpdf = new \Mpdf\Mpdf();

        $mpdf->Bookmark('Start of the document');
        $mpdf->WriteHTML('<div>Section 1 text</div>');
        return $mpdf->Output();

    }
}

the pdf sent by the server is captured in data variable of the success callback of AJAX.

I want the response ( stored in data variable ) to be opened in a new window so that the download process may begin. But this is not working . Instead Browser loads with a bunch of gibberish.

If instead of Making a AJAX request, i make a get request using Browser Search Tab. The PDF Downloads Fine.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire