简体   繁体   中英

Saving HTML5 canvas image then sending via e-mail with PHP

So I have a form on my website (www.100danish.com) which includes an HTML5 canvas element for the user to draw a picture along with their form.

What I want to have happen is the user clicks submit and this sends the image of the canvas along with the form information (name, e-mail, and message). Right now what I have is the following for my AJAX and PHP. I know that I will need to use JavaScript and PHP but PHP is not my expertise.

Any help would be much appreciated!!

JavaScript

//AJAX request to submit form
$('form').submit(function(evt) {
    evt.preventDefault();
    var canvasData = canvas.toDataURL('image/png');
    var url = $(this).attr("action");
    var formData = $(this).serialize();
    $.post(url, [formData, canvasData] function(response) {
        $('#contact-bottom').html("<p class='ajax-p'>Thanks for reaching out to us, we'll be in touch with you soon<br>Joey &amp; Trev</p>")
    })
});

PHP

<?php
    $name = $_POST['name'];
    $email = $_POST['email'];
    $message = $_POST['message'];


    $from = 'From: $name'; 
    $to = 'joey@100danish.com'; 
    $subject = '100 Danish Form Submission';
    $body = "From: $name\nE-Mail: $email\n\nMessage:\n$message";

    mail ($to, $subject, $body, $email);
  ?>

You're asking 2 separate questions: (1) send canvas data to server, (2) send email. Question 2 is everywhere on the internet. Question 1 can be solved as below:

HTML:

<canvas id="myCanvas" width="800" height="450"></canvas>

JS:

//get base64 data
var canvas = $("#myCanvas").get(0);
var data   = canvas.toDataURL();

//send to server
var request = $.ajax({
  type: "POST",
  url:  "canvas-data-receiver.php",
  data: { 
    base64Data:data
  }
});

request.done(function(response) {
  alert("Data posted to server!");
});

request.fail(function(){
  alert("Failed to send data to server!");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM