duanliushua5026 2018-11-25 23:37
浏览 82

将数据从javascript发送到php以生成pdf但不起作用

I am using JavaScript to take the info from a form completed by the user, then sending this data to PHP and generate a PDF with FPDF. The problem is I want the browser to ask the user to save the PDF or view it online but I cannot figure out how. The PDF generates correctly but only when I save it directly to a certain path specified by me.

The question is how do you guys send data from JavaScript to PHP to generate a PDF file then the browser asks the user to open or download, Or how can I make a function where the user can retrieve this PDF.

The JavaScript:

function senddata() {//this activates when i push a button not a submit
    var peticion = new XMLHttpRequest();
    peticion.open('POST', 'generatepdf.php');
    var nueva2 = {};
    var key;

    for (i = 0; i < 6; i++) {
        key = document.forms[0].elements[i].id;
        nueva2[key] = document.forms[0].elements[i].value;
    }//here i take my data from the form and make an object

    var json = JSON.stringify(nueva2);//here i tranform my object to json string so i can send it to my php

    var parametros = "json_string=" + json;//here I do this so later I can easily transform the $_POST to an array in the form json_decode($_POST["json_string"],true); 

    peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");

    peticion.send(parametros);//it sends ok
}

The PHP with the FPDF class and things

<?php

require('fpdf/fpdf.php');
require('functions.php');

if($_SERVER['REQUEST_METHOD']=='POST'){

    $datos=json_decode($_POST["json_string"],true); //here i have my data in an array format so i can use the parameters to fill my pdf fields

    //...lots of pdf things here...//

 $pdf->Output('F',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this works but never ask the user
 //$pdf->Output('D',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this should force a dowload or send to the browser but doesnt work
 //$pdf->Output();//this should send to the browser but doesnt work
    }
  • 写回答

1条回答 默认 最新

  • duanjiu6697 2018-11-26 00:37
    关注

    To view your PDF inline to the browser, you should use the I variable instead. View full documentation here.

    Also I don't think outputting the file in two methods at the same time works. It might conflict each other. The best way to do that is to test each method and if it does conflict each other just simply add a condition for the user to decide whether he/she wants to download or view it in the browser. Hope this helps.

    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示