Search code examples
javascriptphpjqueryajaxcroppie

Getting a php variable value back with an ajax result


I'm using croppie.js to crop user uploaded imaged, once the crop is done ajax is used to upload the result. Here is the codes for that...

Page A..

$('.upload-result').on('click', function (ev) {
    $uploadCrop.croppie('result', {
        type: 'canvas',
        size: 'viewport'
    }).then(function (resp) {
        $.ajax({
            url: "uploadown/uploader.php",
            type: "POST",
            data: {"image":resp},
            success: function (data) {
                html = '<img id="cropresult" style="margin: 0px;" src="' + resp + '" />;
                $("#uploaded-input").html(html);                
            }
        });
    });
});

Then uploader.php is..

<?php 
$data = $_POST['image'];
list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);
$data = base64_decode($data);
$imageName = time().'.png';
file_put_contents($imageName, $data);
?>

As you can see uploader.php is using time() for the $imageName variable.

I either need to pass $imageName back to Page A during upload or set $imageName in page A first and pass it to uploader.php at the same time as the image info.

After a few hours and many attempts having read many similar questions on here and cannot work out how to do this. Any help greatly appreciated.


Solution

  • Echo out the $imageName in php file, once done use it in javascript.

    PHP

    <?php 
      $data = $_POST['image'];
      list($type, $data) = explode(';', $data);
      list(, $data)      = explode(',', $data);
      $data = base64_decode($data);
      $imageName = time().'.png';
      if(file_put_contents($imageName, $data)){
        echo $imageName;
      } else {
        echo " ";//In this case src will be empty
      }
    ?>
    

    Java script

    $('.upload-result').on('click', function (ev) {
        $uploadCrop.croppie('result', {
            type: 'canvas',
            size: 'viewport'
        }).then(function (resp) {
            $.ajax({
                url: "uploadown/uploader.php",
                type: "POST",
                data: {"image":resp},
                success: function (data) {
                    html = '<img id="cropresult" style="margin: 0px;" src="' + data + '" />';
                    $("#uploaded-input").html(html);                
                }
            });
        });
    });
    

    For any queries comment down.