S SAM
S SAM

Reputation: 211

Canvas will not save server side PHP

I have a canvas which I need to save to a directory and store the URL in a database.

When I save the file without storing the URL in the database it works fine, and vice versa.

However, when I put the two together and specify the PHP file through AJAX, for some reason it doesn't recognise the session variable?

When I try to call the "success" on AJAX, nothing shows up. I get no response.

This could possibly be an easy fix! I think I've been staring at this code for too long.

JavaScript:

function doodleSave() {
  var canvas = document.getElementById("doodle-canvas");
  var canvasData = canvas.toDataURL("image/png");

  $.ajax({
    url:'doodleupload.php', 
    type:'POST', 
    data:{ data:canvasData },
    success: function(response){
        alert(response);
        //echo what the server sent back...
    }
  });
}

PHP:

<?php
  session_start();

  /* AUTOMATED VARIABLES */
  $url             = md5(uniqid(rand(), true));
  $unique_user_id  = $_SESSION['unique_user_id'];
  $unique_post_id  = md5(uniqid(rand(), true));
  $timestamp       = time();
  $nature          = "doodle";
  $imageUrl        = $upload_dir.$url.'.png';

  $upload_dir = "images/external/doodles/";
  $img = $_POST['data'];
  $img = substr($img,strpos($img,",")+1);
  $data = base64_decode($img);
  $file = $upload_dir . $url . ".png";
  $success = file_put_contents($file, $data);

  echo $success ? $file : 'Unable to save the file.';

  require_once 'php/connect.php';

  try
  {

    $stmt = $pdo->prepare("INSERT INTO posts (unique_user_id, unique_post_id, nature, image_url, timestamp) VALUE (:unique_user_id, :unique_post_id, :nature, :image_url, :timestamp)");
    $stmt->bindParam(":unique_user_id",$unique_user_id);
    $stmt->bindParam(":unique_post_id",$unique_post_id);
    $stmt->bindParam(":nature",$nature);
    $stmt->bindParam(":image_url",$imageUrl);
    $stmt->bindParam(":timestamp",$timestamp);

    if($stmt->execute())
    {
      echo "File in database";
    }
    else
    {
      echo "Not in database";
    }
  }
  catch(PDOException $e){
    echo $e->getMessage();
  }

?>

Upvotes: 0

Views: 71

Answers (1)

Junius L
Junius L

Reputation: 16132

Move $upload_dir at the top, as you are calling it before you initialize it.

$upload_dir = "images/external/doodles/";
$url             = md5(uniqid(rand(), true));
$unique_user_id  = $_SESSION['unique_user_id'];
$unique_post_id  = md5(uniqid(rand(), true));
$timestamp       = time();
$nature          = "doodle";
$imageUrl        = $upload_dir.$url.'.png';

Upvotes: 1

Related Questions