0

here is the code I use to want to send an email with a pdf, I use html2canva to screenshot the user's screen then I generate a pdf with it, after all that I want to send it via mailjet with my API

EDIT : my pdf is generated and I can see it in a doc.save in the function, but now the problem is that I must be able to send it by email via the MAILJET API, so I created the function send_email a little lower, which should normally send it.. I knew that I would have had problems between js and php,how can i do this ?

echo '<form>
    <label for="email">Adresse e-mail :</label>
    <input type="email" id="email" name="email" required>
    <button id="generate-pdf" type="button">Capture d\'écran et envoi par e-mail</button>
</form>';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
  if (isset($_POST['email'])) {
      $email = $_POST['email'];

      echo '<script>
      function generate_pdf() {
          html2canvas(document.body).then(function(canvas) {
              var imgData = canvas.toDataURL("image/png");
              var doc = new jsPDF();
              doc.addImage(imgData, "PNG", 10, 10);
              var pdf = doc.output("datauristring");
              var email = document.getElementById("email").value;
          });
          sendpdf();  
      }
  
      document.getElementById("generate-pdf").addEventListener("click", generate_pdf);
  </script>';
}
}

function sendpdf(){
  
  $pdf = base64_encode(file_get_contents('test.pdf'));
  $apiKey    = "apikey";
  $apiSecret = "apisecret";
  $body = [
    'Messages' => [
      [
        'From' => [
          'Email' => "
          'Name' => "
        ],
        'To' => [
          [
            'Email' => "
            'Name' => "
          ]
        ],
        'Subject' => "test",
        'TextPart' => "test",
        'HTMLPart' => "test",
        'Attachments' => [
          [
            'ContentType' => "application/pdf",
            'Filename' => "test.pdf",
            'Base64Content' => $pdf
          ]
        ]
      ]
    ]
  ];
  $mailjet_client = new Client($apiKey, $apiSecret);
  $response = $mailjet_client->post(Resources::$Email, ['body' => $body]);
  $response->success() && var_dump($response->getData());
}
Gwen973
  • 23
  • 4
  • `if ($_SERVER['REQUEST_METHOD'] == 'POST') {` Is the method POST anytime? Your `
    ` says it's not
    – brombeer Mar 07 '23 at 09:43
  • I use this because the post refresh my page , and so the pdf don't have time to generate – Gwen973 Mar 07 '23 at 09:44
  • So do you submit your form using Javascript, using the POST method? – brombeer Mar 07 '23 at 09:47
  • `sendpdf();` is executed as a Javascript function - and it doesn't exist in JS context. That's what the error message is telling you – brombeer Mar 07 '23 at 09:48
  • With both I believe? , I want to retrieve the email present in the form, without refreshing the page by pressing the button so the "POST" – Gwen973 Mar 07 '23 at 09:48
  • Nothing in the code you posted makes a POST request to any of your PHP scripts. – brombeer Mar 07 '23 at 09:50
  • What **exactly** is not working with the given code? Is this a JS problem, or a PHP problem? Keep in mind that you cannot directly call a PHP function from JS – Nico Haase Mar 07 '23 at 09:50
  • Please add all clarification to your question by editing it – Nico Haase Mar 07 '23 at 10:22

1 Answers1

0

The issue is that the sendpdf() function is defined inside the generate_pdf() function, which means it is not accessible outside of that function. To fix the issue, you need to move the sendpdf() function outside of the generate_pdf() function, like this:

<form>
  <label for="email">Adresse e-mail :</label>
  <input type="email" id="email" name="email" required>
  <button id="generate-pdf" type="button">Capture d'écran et envoi par e-mail</button>
</form>

<script>
  function generate_pdf() {
    html2canvas(document.body).then(function(canvas) {
      var imgData = canvas.toDataURL("image/png");
      var doc = new jsPDF();
      doc.addImage(imgData, "PNG", 10, 10);
      var pdf = doc.output("datauristring");
      var email = document.getElementById("email").value;
      sendpdf(pdf, email); // Pass the pdf and email as arguments
    });
  }

  function sendpdf(pdf, email) {
    var apiKey = "apikey";
    var apiSecret = "apisecret";
    var body = {
      'Messages': [{
        'From': {
          'Email': "sender@example.com",
          'Name': "Sender"
        },
        'To': [{
          'Email': email,
          'Name': "Recipient"
        }],
        'Subject': "test",
        'TextPart': "test",
        'HTMLPart': "test",
        'Attachments': [{
          'ContentType': "application/pdf",
          'Filename': "test.pdf",
          'Base64Content': pdf
        }]
      }]
    };
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "https://api.mailjet.com/v3.1/send", true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.setRequestHeader("Authorization", "Basic " + btoa(apiKey + ":" + apiSecret));
    xhr.onreadystatechange = function() {
      if (xhr.readyState === 4) {
        console.log(xhr.status);
        console.log(xhr.responseText);
      }
    };
    xhr.send(JSON.stringify(body));
  }

  document.getElementById("generate-pdf").addEventListener("click", generate_pdf);
</script>
  • "_that the sendpdf() function is defined inside the generate_pdf() function_" It is not. It is _defined_ in PHP and _called_ inside the `generate_pdf()` function – brombeer Mar 07 '23 at 09:52
  • The xml method is not good , i send me an error CORS – Gwen973 Mar 07 '23 at 10:17