Setting up functions correctly in Jquery (for Ajax & PHP mail)
Hi Everyone,
I am having difficulties with the below code. I have it working, but for some strange reason it is temperamental. It works some times, and not others. By this I mean that sometimes I receive the email, sometimes I don't. Sometimes I receive the email with the full canvas png image, sometime is receive the email with the canvas png image without the text div but only the svg. Sometimes it works perfectly and I receive the email and the full canvas png.
I have a website with an online form. Next to the form is a preview Div displaying an <svg></svg> image which is dynamically altered with colors based on user selections from 4 form drop down boxes. Also within this preview div is another div containing dynamically generated text based on user input from one of the forms text fields. Once the user inputs their selections, the preview div represents a customized svg image with customized text.
When the user hits submit, the form submit function is called and the svg is saved to a canvas using canvg js plugin. The customized text within the div is also saved to the div but uses html2canvas js plugin. Apparently this is the best way as html2canvas does not work with svg and canvg doesn't work with divs.
Okay, so from here, the canvas is converted to a dataURL string which is the encoded representation of the png image file e.g.
data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA .. . This is sent and displayed in a separate text area (which I will use in the next step).
Next, all the form information is sent via Ajax to PHP where it is saved onto the server as a decoded png. Once decoded, the png is opened from the server, encoded and the dataURL is used to embed into a html email where it is sent.
If anyone could have a look at this code and tell me if there is a way of improving the form submit or php coding in a more succinct way I would be extremely grateful. Thank you.
Here is my form submit code:
- $('#form_check_out').submit(function() {
if ($(this).valid()) {
alert("Form Validated!");
//CREATE XML FROM THE SVG OBJECT
// SEND SVG TO CANVAS
function renderCanvas(){
var canvasTemp = document.getElementById("canvas-svg2");
var oSerializer = new XMLSerializer();
svg = document.getElementById("SVG_scene");
var sXML = oSerializer.serializeToString(svg);
canvg(canvasTemp, sXML,{ ignoreMouse: true, ignoreAnimation: true })
// SEND DIV WITH TEXT TO CANVAS
html2canvas($("#text-top-bottom"), {
onrendered: function(canvas) {
// canvas is the final rendered <canvas> element
var myImage = canvas.toDataURL("image/png");
var ctx = document.getElementById("canvas-svg2").getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0); // Or at whatever offset you like
loadHero();
};
img.src = myImage;
}
});
- // SEND CANVAS DATAURL TO TEXTAREA
function loadHero(){
var canvasTemp1 = document.getElementById("canvas-svg2");
var myImage2 = document.getElementById("canvas-svg2").toDataURL("image/png");
document.getElementById("svg-text").value = myImage2;
loadAjax();
};
}
function loadAjax(){
post_data = {
/* DETAILS */
'c_name' : $('input[name=name]').val(),
'c_address' : $('input[name=address]').val(),
'c_suburb' : $('input[name=suburb]').val(),
'c_postcode' : $('input[name=postcode]').val(),
'c_state' : $("#select_state1 option:selected").val(),
'c_phone' : $('input[name=phone]').val(),
'c_fax' : $('input[name=fax]').val(),
'c_email' : $('input[name=email]').val(),
'imgBase64' : document.getElementById("canvas-svg2").toDataURL("image/png")
};
//Ajax post data to server
$.post('http://localhost:8080/web/secure_email_code.php', post_data, function(response){
$("#form_check_out").hide().html(output).slideDown();
}, 'json');}
renderCanvas();
return false;
}else{
alert("This form has problems, lets start validating!");
return false;
}
});
Here is my PHP code for emailing the canvas image out
- <?php
if($_POST)
{
$to_email = "email@email.com"; //Recipient email, Replace with own email here
//check if its an ajax request, exit if not
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
-
- // BRING IN DATAURL, DECODE IT AND SAVE TO SERVER AS PNG
$img = $_POST['imgBase64'];
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$fileData = base64_decode($img);
//saving
$fileName = 'photo'.uniqid().'.png';
file_put_contents($fileName, $fileData);
//Sanitize input data using PHP filter_var().
/* DETAILS */
$c_name = ucwords(filter_var($_POST["c_name"], FILTER_SANITIZE_STRING));
$c_address = ucwords(filter_var($_POST["c_address"], FILTER_SANITIZE_STRING));
$c_suburb = ucwords(filter_var($_POST["c_suburb"], FILTER_SANITIZE_STRING));
$c_postcode = filter_var($_POST["c_postcode"], FILTER_SANITIZE_STRING);
$c_state = $_POST["c_state"];
$c_phone = filter_var($_POST["c_phone"], FILTER_SANITIZE_STRING);
$c_fax = filter_var($_POST["c_fax"], FILTER_SANITIZE_STRING);
$c_email = filter_var($_POST["c_email"], FILTER_SANITIZE_EMAIL);
// ENCODE PNG AND ASSIGN DATAURL TO img_binary FOR USE IN EMAIL BODY
$img_binary = fread(fopen($fileName, "rb"), filesize($fileName));
$img_string = chunk_split(base64_encode($img_binary));
fclose($fileName);
/* set timezone */
date_default_timezone_set('Australia/Melbourne');
$subject = 'Request Form';
$headers = "From: " . $c_email . "\r\n";
$headers .= "Reply-To: ". $c_email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message_body = "<h2>Form Submitted</h2>" . "\r\n" .
"<table style='border: collapse' border='0' cellpadding='5' cellspacing='0' bordercolor='#ccc'>\r\n".
"<tr><td colspan='2' align='center'><img src='data:image/png;base64,".$img_string."' /></td></tr>\r\n".
"<tr><td>Name:</td><td>".$c_name."</td></tr>\r\n".
"<tr><td>Address:</td><td>".$c_address."</td></tr>\r\n".
"<tr><td>Suburb:</td><td>".$c_suburb."</td></tr>\r\n".
"<tr><td>Postcode:</td><td>".$c_postcode."</td></tr>\r\n".
"<tr><td>State:</td><td>".$c_state."</td></tr>\r\n".
"<tr><td>Phone:</td><td>".$c_phone."</td></tr>\r\n".
"<tr><td>Fax:</td><td>".$c_fax."</td></tr>\r\n".
"<tr><td>Email:</td><td>".$c_email."</td></tr></table>\r\n";
$send_mail = mail($to_email, $subject, $message_body, $headers);
if(!$send_mail)
{
//If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
$output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
die($output);
}else{
$output = json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your email'));
die($output);
}
}
?>