Harshad Patil
Harshad Patil

Reputation: 100

PHP - jquery ajax crop image before upload using croppie plugin

I have written the code for cropping the image using PHP, jQuery, and Ajax with Croppie plugin.

I'm also trying to add the input value with it.
But I don't know how to post input value with ajax using PHP.
I mean to say when I'm a uploading image, I want input value also post with the image.

Please check with below code for your reference:-

$uploadCrop = $('#upload-demo').croppie({
  enableExif: true,
  viewport: {
    width: 853,
    height: 292,
    type: ''
  },
  boundary: {
    width: 853,
    height: 292
  }
});

$('#upload').on('change', function () {
  var reader = new FileReader();
  reader.onload = function (e) {
    $uploadCrop.croppie('bind', {
      url: e.target.result
    }).then(function(){
      console.log('jQuery bind complete');
    });

  }
  reader.readAsDataURL(this.files[0]);
});

$('.upload-result').on('click', function (ev) {
  $uploadCrop.croppie('result', {
    type: 'canvas',
    size: 'viewport'
  }).then(function (resp) {

    $.ajax({
      url: "upload.php",
      type: "POST",
      data: {"image":resp},
      success: function (data) {
        html = '<img src="' + resp + '" />';
        $("#upload-demo-i").html(html);
      }
    });
  });
});
<script src="http://demo.itsolutionstuff.com/plugin/jquery.js"></script>
<script src="http://demo.itsolutionstuff.com/plugin/croppie.js"></script>
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/bootstrap-3.min.css">
<link rel="stylesheet" href="http://demo.itsolutionstuff.com/plugin/croppie.css">

<div class="row">
  <div class="col-md-4 text-center">
<div id="upload-demo" style="width:350px"></div>
  </div>
</div>
<!--<div class="row">
<div class="col-md-4" style="">
<div id="upload-demo-i" style="background:#e1e1e1;width:300px;padding:30px;height:300px;margin-top:30px"></div>
</div>
</div>-->
<div class="row">
  <div class="col-md-4" style="padding-top:30px;">
<strong>Select Image:</strong>
<br/>
<input type="file" id="upload">
<br/>
<input type="text" name="title">
<button class="btn btn-success upload-result">Upload Image</button>
  </div>
</div>

upload.php

<?php
$data = $_POST['image'];

list($type, $data) = explode(';', $data);
list(, $data)      = explode(',', $data);

$data = base64_decode($data);
$imageName = time().'.jpg';
file_put_contents('upload/'.$imageName, $data);

echo 'done';

?>

Upvotes: 1

Views: 2079

Answers (1)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

So you just want to know how to add the title to the data to post via Ajax?

That is easier than what you've already done!!
if YOU've done it...

Here is how:

data: {"title:":$("input[name='title']").val(),"image":resp}

You'll get the title using $_POST['title'] on PHP side.

I've made a CodePen demo where, obviously, Ajax is commented out...
But the data which would be sent is displayed in console.

Upvotes: 2

Related Questions