Search code examples
javascriptajaxjsppdfdocument-body

Removing html elements from html body in ajax before sending it as data to controller


I have a JSP page with two buttons "download" and "sendemail". On click of Sendmail button, I am calling an ajax method that generates a pdf of the HTML body and sends it to the back-end(controller).

I tried to use :

document.getElementById('reportbuttons').remove();

before :

doc.addHTML(document.body, function() {....

where "reportbuttons" is the id of the div tag that includes "sendmail' and "download" button.But, both buttons dissapear once "sendmail" button is clicked.

function sendMail() { let doc = new jsPDF('p','pt','a4'); doc.setProperties({ title: ' Report PDF Document', subject: 'subject', author: 'XYZ', keywords: 'generated, javascript, web 2.0, ajax', creator: 'ABC ' }); doc.addHTML(document.body, function() { var data = doc.output('datauristring'); console.log(data); var reqJson = {}; reqJson.machineId = "<%=machineId%>"; reqJson.monthYear = "<%=monthYear%>"; reqJson.data = data; console.log(); $.ajax( { url : "sendMail/", type: "POST", dataType: 'json', data : JSON.stringify(reqJson), contentType: "application/json", success:function(data) { alert('mail sent successfully'); console.log(data); }, error: function(data) { } }); }); }

I want to remove these two buttons in the generated pdf, but it should not disappear on the jsp web page.


Solution

  • Don't remove your buttons before doc.addHTML(body,function(){})instead hide those two buttons and on success/error response from your ajax call, show those two buttons again.

                     success:function(data)
                     {
                         alert('mail sent successfully');
                         console.log(data);
                         document.getElementById('reportbuttons').style.display ="block";
    
                     }, 
                     error: function(data)
                     {
                         document.getElementById('reportbuttons').style.display ="block";
                     }
    

    Update:

    Create a clone of your document and remove the element from clone and then send the updated clone to your controller using ajax.

      var itm = document;
      var cln = itm.cloneNode(true);
      cln.getElementById("reportbuttons").remove();