edan291
edan291

Reputation: 162

How can I return a filename to Jquery from PHP

I am saving a canvas image to a .png file using the following code:

jQuery:

$(".save").click(function () {
    var canvas = $("#standard_canvas");
    var src = canvas[0].toDataURL("image/png");
    $.ajax({
        url: 'save.php',
        type: 'POST',
        data: {
            data: src
        },
        complete: function (data, status) {
            if (status == 'success') {
                alert("image saved!")
            }
        }
    });
});

[save.php]

<?php
$based64Image = substr($_POST['data'], strpos($_POST['data'], ',') + 1);
$image        = imagecreatefromstring(base64_decode($based64Image));
imagealphablending($image, false);
imagesavealpha($image, true);

$fileName = '';
if ($image != false)
  {
    $fileName = 'image/designs/' . time() . '.png';
    if (!imagepng($image, $fileName))
      {
        //          fail;
      }
  }
else
  {
    //          fail;
  }

?>

What I would like to do is have the new filename passed back to my ajax call so that I can use it to populate a hidden input field (which I can then save along with a customer order). Can anyone help?

Thanks.

Upvotes: 0

Views: 400

Answers (2)

Roy M J
Roy M J

Reputation: 6938

Simply add following line in image upload success part :

echo $filename 

Then in your ajax call,

$.ajax({
    url: 'save.php',
    type: 'POST',
    data: {
        data: src
    },
    complete: function (data, status) {
        if (status == 'success') {
            alert("image saved!");
            alert("Filename : "+data);
            // Do anything with the file name here
        }
    }
});

This should do it for you.

Upvotes: 1

user1959328
user1959328

Reputation: 129

In your php file you could create a json response containing your filename

  $data['filename'] = $fileName;
  echo json_encode($data);

And read it out in your ajax response

$(".save").click(function () {
    var canvas = $("#standard_canvas");
    var src = canvas[0].toDataURL("image/png");
     $.ajax({
         url: 'save.php',
         type: 'POST',
         dataType: 'json',
         data: {
             data: src
         },
         success: function (data, status) {
             if (status == 'success') {
                 alert("image saved!")
                 var filename = data.filename //<--------
             }
         }
     });
});

EDIT: (which I can then save along with a customer order)

A better practice would be storing the filename in a session variable on the server side. This prevents the client form changing the filename (even if it's in a hidden field)

Upvotes: 1

Related Questions