Making Ajax calls execute more than once - javascript

I am trying to load an changed image into a modal box with ajax. For example, the photo changes to the selected one when I click "Make Profile Picture" but it keeps the old one showing in the modal box unless I refresh the page. Is there a way to have ajax execute not just on page load but perhaps execute always to check the photo is the new one?
Here is the code I have in place:
PHP -
public function getprofileimageAction()
{
$layout = $this->layout();
$layout->setTerminal(true);
$view_model = new ViewModel();
$view_model->setTerminal(true);
$params = $this->identity();
$dir = #array_diff(#scandir(getcwd() . '/public/images/profile/' . $params . '/current/', 1), array('.', '..'));
if (!$dir) {
// set default avatar
$string_img = "<img src=\"/images/profile/defaults/avatar2.png\" class=\"w3-round w3-border\" onclick=\"document.getElementById('a-modal').style.display='block'\"
style=\"width: 200px; height: 200px;\" alt=\"Avatar\" id=\"avatar\">";
} else {
$string_img = "<img src=\"/images/profile/$params/current/$dir[0]\" class=\"w3-round w3-border\" onclick=\"document.getElementById('a-modal').style.display='block'\"
style=\"width: 200px; height: 200px;\" alt=\"Avatar\" id=\"avatar\">";
}
$data = array(
'profile_photo' => $string_img
);
echo $data['profile_photo'];
return $view_model;
}
JavaScript/jQuery -
var replaced_src;
var replace;
$.ajax({
type: "POST",
url: "/members/profile/get-profile-image",
}).done(function(data) {
$("#profile-pic").html(data);
replaced_src = $("#avatar").attr('src');
replace = replaced_src.replace(/(defaults)/g, '');
// fix this so it loads the changed image.
$('#current-photo').html("<img src='" + replace + "' alt='Avatar' class='w3-center w3-round w3-border' style='height: 280px; width: 400px;'>");
}).fail(function(data) {
alert("Error loading image");
});
This is the event click to change the profile picture
$('#make-profile-photo').on('click', function() {
$.ajax({
type: "POST",
url: "/members/profile/change-profile-picture",
data: { image: $('#other-photo').attr('src') }
}).done(function() {
document.getElementById('p-modal').style.display = 'none';
$('#profile-pic').load('/members/profile/get-profile-image');
});
});
HTML -
<div class="w3-modal" id="a-modal">
<div class="w3-modal-content w3-card-4 w3-theme-d2 w3-round" style="width: 432px;">
<div class="w3-container">
<p class="w3-center w3-small">
<span onclick="document.getElementById('a-modal').style.display = 'none'" class="w3-closebtn">×</span>
Current Profile Picture
</p>
<br>
<p id="current-photo" class="w3-center">
<br>
</p>
<script type="text/javascript">
var modal = document.getElementById('a-modal');
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = 'none';
}
}
</script>
<div class="w3-clear"></div>
</div>
</div>
</div>
So basically what I am asking is if there is a way to reload the changed image so $('#current-photo') will display it without having to refresh the page.
Hope that makes sense
Thanks!
If it helps, here is a screenshot of my issue:
http://imgur.com/a/DkPhQ

Related

Dropzone display server images but not saving laravel

I'm using Dropzone.js,I displayed server images inside dropzone box with remove link and it works fine but my problem is when I click on butto to save uploaded images server images not saving in database just new uploaded images are saving
my code
<script type="text/javascript">
Dropzone.options.dropzone =
{
autoProcessQueue: false,
maxFiles: 50,
maxFilesize: 12,
acceptedFiles: ".jpeg,.jpg,.png,.gif",
addRemoveLinks: true,
uploadMultiple: true,
timeout: 50000,
init: function () {
var myDropzone = this;
$.get('/getphoto',{'key': $('[name=key]').val()},function(data){
var files = data;
console.log(files.length);
for (var i = 0; i < files.length; i++) {
var name= files[i].name;
var link = "http://127.0.0.1:8000/storage/images/events/galleries/"+ name;
console.log(link);
var mockFile = { name: files[i].name, size: 128456, type: 'image/png', url:link};
myDropzone.emit('addedfile', mockFile);
myDropzone.options.thumbnail.call(myDropzone, mockFile, link);
myDropzone.emit('complete', mockFile);
myDropzone.files.push(mockFile);
var existingFileCount = 1; // The number of files already uploaded
myDropzone.options.maxFiles = myDropzone.options.maxFiles - existingFileCount;
}
});
// Update selector to match your button
$("#button").click(function (e) {
e.preventDefault();
myDropzone.processQueue();
});
this.on('sending', function(file, xhr, formData) {
// Append all form inputs to the formData Dropzone will POST
var data = $('#dropzone').serializeArray();
$.each(data, function(key, el) {
formData.append(el.name, el.value);
});
});
},
removedfile: function(file)
{
var fileRef;
return (fileRef = file.previewElement) != null ?
fileRef.parentNode.removeChild(file.previewElement) : myDropzone.removeFile(file);
},
success: function(file, response)
{
var name = file.upload.filename;
console.log(name);
window.location.href = "{{ route('eventlist') }}";
},
error: function(file, response)
{
return false;
}
};
function del(file)
{
console.log(file.name);
return myDropzone.removeFile(file);
}
</script>
my view blade:
<div>
<form action="{{ route('savegallery',$event->id) }}" class="dropzone" id="dropzone" method="POST" class="dropzone" enctype="multipart/form-data">
#csrf
{{-- <div class="fallback">
<input name="images" type="file" multiple="multiple">
</div> --}}
<div class="dz-message needsclick">
<div class="mb-3">
<i class="display-4 text-muted mdi mdi-upload-network-outline"></i>
</div>
<h4>Drop files here or click to upload.</h4>
</div>
</form>
</div>
<div class="text-center mt-4">
<button type="submit" id="button" class="btn btn-primary waves-effect waves-light">Send
Files</button>
</div>
First I delete all images then I get images from dropzone then save it
public function savegallery(Request $request,$id){
$eventgalleries = Eventgallery::where('event_id',$id)->delete();
foreach ($request->file('file') as $img) {
// $image = new Eventgallery;
//get file name with extention
$filenameWithExt = $img->getClientOriginalName();
//get just file name
$filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
//GET EXTENTION
$extention = $img->getClientOriginalExtension();
//file name to store
$fileNameToStore = $filename . '_' . time() . '.' . $extention;
//upload image
$path = $img->storeAs('public/images/events/galleries', $fileNameToStore);
$url = asset('storage/images/events/galleries/' . $fileNameToStore);
$img = new Eventgallery;
$img->name = $fileNameToStore;
$img->event_id = $id;
$img->save();
}
return redirect()->route('eventlist')->with('success', 'The galleries created successfully.');
}
and this function for route (/getphoto) to get all images and then display it in dropzone
public function getphoto(){
$data = Eventgallery::all()->toArray();
return $data;
}
Can someone help me I spend many days to find a solve but no result.

How to get the image path on dynamically adding new file field using ajax

Here it is the main field that to dynamically add the elements. In this form by clicking add button it add the html part in the page. That works fine.
<div class="col-md-12 input_fields_wrap2"></div>
<button class="btn btn-primary add_field_button2" id="btnclr2">Add</button>
And the remaining script work is here for adding the fields.
<script>
$(document).ready(function()
{
var wrapper = $(".input_fields_wrap2"); //Fields wrapper
$('.add_field_button2').click(function(e)
{
var sub = 1;
e.preventDefault();
$(wrapper).append('<div><div class="row"><div class="col-md-4"><div class="form-group"><label>Sub-Article Heading</label><input type="text" class="form-control" id="subarticle_title" placeholder="Sub Article Heading" name="sub_article_heading[]"></div></div><div class="col-md-4"><div class="form-group"><label>Sub Article Image<span style="color: red;">*</span></label><input type="file" class="form-control required" name="file_upload1[]" id="file_upload1" value="" placeholder=""/><input type="hidden" name="giftcardpath1[]" id="giftcardpath1" value="" ><span id="giftimage1" style="display: none"><img src="" id="giftcard1"></span><span style="color: red;"></span></div></div><div class="col-md-4"><div class="form-group"><label>Sub-Article Image-Caption</label><input type="text" class="form-control" id="title" placeholder="Sub Article Image caption" name="sub_article_img_caption[]" value="" required=""></div></div><div class="col-md-12"><div class="form-group"><label>Content</label><textarea class="form-control" name="sub_article_content[]" rows="6" placeholder="Sub Articles Content..."></textarea></div></div><div class="clearfix"></div></div><a style="margin-bottom:15px; href="#" class="remove_field btn btn-danger btn-xs">Remove</a><br></div>');
$('#file_upload1').on('change',function(){
var file ;
file = this.files[0];
var img = new Image();
var _URL = window.URL || window.webkitURL;
img.src = _URL.createObjectURL(file);
img.onload = function () {
var reader = new FileReader();
reader.onloadend = function() {
// alert(reader.result);
$.ajax({
type: "POST",
url: base_url+"Admin/UploadImg",
data: {
imgBase64: reader.result,
}
}).done(function(data){
data = $.parseJSON(data);
if(data.imgpath!='')
{
$('#giftcardpath1').val(data.imgpath);
alert('Image upload successfull');
}
});
}
reader.readAsDataURL(file);
};
});
sub +=1;
});
//user click on remove text
$(wrapper).on("click",".remove_field", function(e)
{
e.preventDefault();
$(this).parent('div').remove();
});
});
</script>
But the Main problem is whenever i am upload a first file it works fine and display the alert and image path but later uploading image in second added field it can not store the path of that second image and did not display the alert.
My Upload image code is
public function UploadImg()
{
$rawData = $_POST['imgBase64'];
$filteredData = explode(',', $rawData);
$unencoded = base64_decode($filteredData[1]);
$datime = time();
$fp = fopen('upload_dataimage/'.$datime.'.jpg', 'w');
fwrite($fp, $unencoded);
fclose($fp);
$img_url = 'upload_dataimage/'.$datime.'.jpg';
echo json_encode(array('result'=>'1','imgpath'=>$img_url));
exit;
}
please help me to get rid of this problem and made me happy.
Thanks in advance..

how to change XmlHttpRequest url in image upload

I am trying to upload image and it is working. but the problem is when I am trying to update this image I m having problem because it is redirecting to wrong url. The form is post to this url
POST http://127.0.0.1/mgt/upload/processImage/foodImage
and the result is coming like this
GET
http://127.0.0.1/mgt/food/viewFoodDetails/temp/uploads/images/foodImage/937d932fcbf3c6ba36b7eed65cecd045.png
But, I want the get result should come like this (I dont want it to get food/viewFoodDetails from url)
GET
http://127.0.0.1/mgt/temp/uploads/images/foodImage/937d932fcbf3c6ba36b7eed65cecd045.png
can anyone help me please?
here is my js
$.fn.uploadFile=function(opts)
{
var opts=$.extend({
allowed:['png, jpg']
},opts);
return this.each(function(){
var pb='<div class="progress" style="width:0"><span>0%</span></div>',
_this=$(this),
progressbar=$(_this.attr("data-progressbar")),
endpoint='http://127.0.0.1/mgt/upload/processImage/foodImage',
viewer=$(_this.attr("data-viewer")),
element=$(_this.attr("data-element")),
downloadLink=$(_this.attr("data-downloadLink"));
//cct=$(_this).parents("form").find("input[name=csrfwebpos]").val();
//console.log(_this, progressbar, endpoint, viewer, element, downloadLink);
_this.change(function(){
var filename=_this.val().toLowerCase().split(/[\\\/]/).pop(),is_allowed=false,
ext=filename.split(".").pop();
//console.log(filename, ext);
if(filename==''){
return;
}
$.each(opts.allowed,function(i,el){
if(ext==el){
is_allowed=true;
}
});
if(!is_allowed){
showError("This file type is not supported. Please select another file.");
return;
}else{
progressbar.show(0);
var files=_this[0].files,
file=_this[0].files[0],
headers={
"Cache-Control":"no-cache",
"X-Requested-With":"XMLHttpRequest",
"X-File-Name":file.fileName||file.name,
"X-File-Size":file.fileSize||file.size,
};
if(file.size>700000){
showError("File can not be larger than 700KB in size.");
return;
}
_this.attr("disabled",true);
progressbar.append(pb);
var bar=progressbar.find(".progress"),percent=bar.find("span");
var xhr = new XMLHttpRequest();
var upload = xhr.upload;
upload.fileObj = file;
upload.downloadStartTime = new Date().getTime();
upload.currentStart = upload.downloadStartTime;
upload.currentProgress = 0;
upload.startData = 0;
viewer.hide(0);
upload.onprogress=function(e){
if(e.lengthComputable){
var _p=Math.floor((e.loaded/e.total)*100);
bar.css("width",_p+"%");
percent.html(_p+"%");
if(_p==100){
percent.html("Processing...");
}
}
};
xhr.onload=function(e){
status = xhr.status;
if(e.target.readyState == 4){
var data=eval("("+this.responseText+")");
console.log(this);
console.log(data);
if(data && data.successFunction){
data.successFunction.apply(_this);
}
if(data && data.fileName!=''){
element.val(data.fileName);
element.trigger("change");
viewer.show(0);
$(viewer).find("img").prop("src",data.fileName);
}
if(data && data.downloadLink!=''){
downloadLink.html('Download Server Response');
}
_this.val("").attr("disabled",false);
progressbar.find(".progress").remove();
progressbar.hide(0);
}
};
xhr.open("POST",endpoint,true);
//console.log(endpoint);
/*
var oMyForm = new FormData();
oMyForm.append("csrfwebpos", cct);
oMyForm.append("file", file);
*/
for(var prop in headers){
xhr.setRequestHeader(prop, headers[prop]);
}
xhr.send(file);
}
});
});
};
This is my image upload function upload.php
public function processImage($uploadFolder="profile", $userFileName="")
{
$tempFilePath="temp/$uploadFolder";
if (!file_exists($tempFilePath)) {
#mkdir($tempFilePath);
}
#chmod($tempFilePath, 0777);
$path=$tempFilePath."/";
$headers=getallheaders();
if (isset($headers['X-File-Size'], $headers['X-File-Name'])) {
// create the object and assign property
$file = new stdClass;
$file->name = basename($headers['X-File-Name']);
$file->size = $headers['X-File-Size'];
$file->content = file_get_contents("php://input");
$fileparts=fileExtension($file->name);
if ($userFileName=='') {
$filename = md5(
$this->session->userdata('userid') .
uniqid() .
microtime(true) .
mt_rand() .
$file->name .
$file->size .
$this->session->userdata('userid')
);
} else {
$filename=$userFileName;
}
$file->name=$filename.$fileparts["extension"];
// echo $path.$file->name;
if (#file_put_contents($path.$file->name, $file->content)) {
$old = getcwd(); // Save the current directory
#chdir($path);
chmod($file->name, 0644);
chdir($old);
}
}
}
This is my HTML
<script type='text/javascript'>
$(document).ready(function() {
$('#uploadImage').uploadFile();
});
</script>
<form method='post' action='<?=$baseUrl?>food/saveFood' accept-charset='utf-8' enctype='multipart/form-data'>
<table class='table table-bordered table-curved'>
<tr>
<td>
<div class='form-group col-md-12' style='padding:0px;'>
<div class='fileupload fileupload-new' data-provides='fileupload'>
<div class='input-group'>
<div class='form-control uneditable-input'><i class='icon-file fileupload-exists'></i>
<span class='fileupload-preview'></span>
</div>
<div class='input-group-btn'>
<a class='btn btn-default btn-file'>
<span class='fileupload-new'>Select file</span>
<span class='fileupload-exists'>Change</span>
<input type='file' class='file-input' id='uploadImage' data-progressbar='.pb' data-element='#appImg' data-viewer='#appPhoto' />
</a>
</div>
</div>
</div>
</div>
<div class='clearfix'></div>
<div class='pb pull-left col-md-12' style='display:none;'></div>
<div id='appPhoto'><img src='' /></div>
<input type='hidden' name='imagePath' id='appImg' value='' />
</td>
</form>
I solved it, I have added baseurl to the file path
from
$(viewer).find("img").prop("src",data.fileName);
to
$(viewer).find("img").prop("src",baseurl+data.fileName);

Ajax call not working second time

I have this ajax/php structure that works perfectly when selecting one image. But, if I click on "selecteer" to perform the same code for the second time, no images are shown. The "ajax" page does load correctly though.
Basically what I have;
Article page: This page shows 10 buttons "Selecteer". Under these 10 buttons you have a div where some images are shown after pressing Selecteer. When clicking on one of those images, the clicked image is selected and will be shown solely.
Javascript: This script binds the click events, and performs the ajax loading aswell as the image showing.
Images page: this page is loaded by ajax and is shown in a div inside the article page.
EDIT:
I did some testing. The second time the div is loaded with an ajax call (the images page) it does "Create" all the images with the createImage function. Yet I only see the search bar and the "zoek" button. So the real problem is: the images aren't showing the second time!
The code (I left some things out which I think are irrelevant)
article:
<?php for($i = 0; $i < constant("MAX_PICS"); $i++) { ?>
<button <?php echo"id='select_portal$i' class='select_portal_class'";?> type="button">Selecteer</button>
<div <?php echo"id='dialog_form$i'";?> style="display:none; position:absolute; width:auto; height:auto; margin-left: auto; margin-right: auto; z-index:1;"></div>
<div <?php echo"id='selected_image$i'";?> style="display:block; width:auto; height:auto">
<?php if(isset($_GET['edit_artikel'])) { ?><img src="../images/<?php $beeldbank = Beeldbank::find_by_portal_id($artikel->portal_id); echo $beeldbank[0]->imagelib_id; ?>/<?php echo $artikel->portal_id;?>" id="selid" width="125" /> <?php } else {?>
<img src="../images/icons/no_image_found.png" alt="No image available" <?php echo"id='selid$i'";?> width="125" /> <?php } ?>
<input type="hidden" <?php echo"id='portal_id$i'";?> name="portal_id" value="<?php if(isset($_GET['edit_artikel'])) { echo $artikel->portal_id; } ?>" />
</div>
<div id="selected_portal"></div>
javascript:
$(document).ready(function() {
(function() {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = document.location.protocol + '//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js';
var script2 = document.createElement('script');
script2.type = 'text/javascript';
script2.src = document.location.protocol + '//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js';
document.getElementsByTagName('head')[0].appendChild(script);
document.getElementsByTagName('head')[0].appendChild(script2);
})();
$( ".select_portal_class" ).each(
function( intIndex ){
$(this).bind('click', function() {
loadAjaxFrame(intIndex);
});
}
);
});
function loadAjaxFrame(id)
{
var dialog = $("#dialog_form"+id);
//alert(dialog.attr('id'));
dialog.css("display", "block");
dialog.css("top", "auto");
dialog.css("left", "auto");
dialog.css("right", "auto");
dialog.css("backgroundColor", "white");
document.getElementById(dialog.attr('id')).style.visibility = 'visible';
tempDialogID = id;
if(!ajaxLoad){
dialog.load("imglib.php");
ajaxLoad = true;
}
}
function showImage()
{
var portal = $("#portal_id"+tempDialogID);
var dialog = $("#dialog_form"+tempDialogID);
var selid = $("#selid"+tempDialogID);
alert(tempDialogID);
var img = document.getElementById(selid.attr('id'));
img.src = imgname;
var portal_id = document.getElementById(portal.attr('id'));
portal_id.value= imgid;
document.getElementById(dialog.attr('id')).style.visibility = 'hidden';
dialog.unload();
ajaxLoad = false;
}
function create_image(src,alt) {
var img = document.createElement("img");
var objTo = document.getElementById('imagesDiv');
img.src = src;
img.alt = alt;
img.className= "imgid";
$(img).height(imageHeight);
$(img).width(imageWidth);
$(img).bind('click', 'span', function () { imgid = alt; imgname = src; showImage(); });
objTo.appendChild(img);
}
$('#formpie').on('submit', function(e) {
e.preventDefault();
var dialog = $("#dialog_form"+tempDialogID);
$.ajax({
type : 'POST',
url : "imglib.php",
data : $(this).serializeArray(),
success: function(data) {
dialog.html(data);
}
});
});
And finally the images page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="javascripts/SelectImage.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var photos = <?php echo json_encode($photoSources); ?>;
var photoAlts = <?php echo json_encode($photoAlts); ?>;
var photoTags = <?php echo json_encode($photoTags); ?>;
var photoCount= <?php echo $total_count; ?>;
photoCount = photoCount/10;
photoCount = Math.ceil(photoCount);
function buttonClicked(id){
var page = id;
photoPage = page*10;
minCount = photoPage-10;
maxCount = photoPage;
jQuery("#imagesDiv").html("");
createButtons();
$( "#imagesDiv" ).append( " <br/>");
populateDiv();
}
function createButtons() {
var i = 1;
var button= "";
while(i <= photoCount)
{
var button = document.createElement("BUTTON");
var buttonName= document.createTextNode(i);
button.appendChild(buttonName);
button.id = i;
jQuery(button).bind('click', { id: i}, function(event) {
var data = event.data;
buttonClicked(data.id);
});
var objTo = document.getElementById('imagesDiv');
objTo.appendChild(button);
i++;
}
}
$(".moreButton").click(function() {
maxCount += 10;
minCount += 10;
jQuery("#imagesDiv").html("");
populateDiv();
});
function populateDiv() {
for(var i = minCount;i < maxCount; i++)
{
if(i < <?php echo $total_count ?>)
{
create_image("../"+photos[i],photoAlts[i]);
$( "#imagesDiv" ).append( "<p style=\"display:inline; padding-left:10px;\">" + photoTags[i] + "</p><br/>" );
}
}
}
createButtons()
$( "#imagesDiv" ).append( " <br/>");
populateDiv();
});
</script> <?php
if(isset($_POST['submit'])) {
$artikel->portal_id = $_POST['portal_id'];
}?>
<fieldset>
Afbeelding zoeken
<form id="formpie" name="zoek" action="" method="POST">
<input type="hidden" name="zoek" value="zoek" id="zoek"/>
<input type="text" name="tags" size="31" id="tags"/>
<input type="submit" name="zoek" id="search" value="Zoek" />
</form>
<div id="imagesDiv" style="width:800px; height:780px;">
<label for="portal_id"></label>
</div>
</fieldset>
<div id="selected_img_div" style="display:none; width:auto; height:auto;">
<?php if($selected_image == NULL) { echo "No image selected"; }
else { echo '<img src="images/'.$selected_image.' class="selimgid"/>'; } ?>
</div>
If you load content dynamically and you want bind actions to them you shouldn't use the .bind(), .click() and .on([action], function(){}) functions. Because these functions can be only bind into elements which rendered at page loading.
So you should use that function:
$('body').on([action], [selector], function(){});
[action]: what type of binding do you want (ie: click, submit,...)
[selector]: select the element what you want to bind (ie: '.moreButton')
For example, instead of that code:
$(".moreButton").click(function() {
maxCount += 10;
minCount += 10;
jQuery("#imagesDiv").html("");
populateDiv();
});
Use this code:
$('body').on('click' , '.moreButton', function() {
maxCount += 10;
minCount += 10;
jQuery("#imagesDiv").html("");
populateDiv();
});
Try changing to,
$('body').on('submit','#formpie', function(e) {
e.preventDefault();
var dialog = $("#dialog_form"+tempDialogID);
$.ajax({
type : 'POST',
url : "imglib.php",
data : $(this).serializeArray(),
success: function(data) {
dialog.html(data);
}
});
});
$('#formpie').on('submit', function(e) {
e.preventDefault();
var dialog = $("#dialog_form"+tempDialogID);
$.ajax({
type: 'POST',
url: "imglib.php",
data: $(this).serializeArray(),
success: function(data) {
dialog.html(data);
urlRefresh();
}
});
});
replace your code with it. I think there is a problem on url refresh. so Try it.
maybe you are using functions or events with new content?
if you are doing that, maybe you have the same problem like this
https://stackoverflow.com/a/26559809/2043592
I had same problem and it got resolved after adding below code in head tag.
<meta charset="UTF-8">
<meta http-equiv="cache-control"
content="no-cache, must-revalidate, post-check=0, pre-check=0" />
<meta http-equiv="cache-control" content="max-age=0" />
<meta http-equiv="expires" content="0" />
<meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 G`enter code here`MT" />
<meta http-equiv="pragma" content="no-cache" />

Using Jcrop form an ajax loaded image

I have a site where I would like to upload a profile picture to the server and store the image into the database, using ajax. This is pretty straight forward and does work. But I would like to be able to get the user to be able to to crop their image so that it is square using Jcrop. I have seen and downloaded examples of how to implement Jcrop, which are pretty straight foreword. But I just can't seen to get it to work on my site. The code I have so far is rough and still needs a bit of validation but I want to get the main function dealt with first.
To make the cropping process seem a little more user friendly I have created a basic light-box type thing to hold the upload form and then the image to crop after sent back from php. This seems to be the only difference form what I've seen online.
Here's my code:(I have just picked out the relevant parts as the site contains quite a lot of text and images in other divs that aren't relevant)
HTML IMPORTS:
<script src="jquery/jquery.min.js"></script>
<script src="jquery/jquery.Jcrop.min.js"></script>
<link rel="stylesheet" href="css/jquery.Jcrop.css" type="text/css" />
HTML: - form to upload a new Profile Pic
<div id="reg_pp">
<img src="images/logo.png" width="100%" height="150px" /><br/><button id="updateGender" style="float:right; width:auto;" class="form_fields_button" onclick="changeProfilePic('open')">Change Profile Picture</button>
</div>
HTML: - lightbox type thing
<div id="ppuo" class="overlay">
<div id="ppufh" class="tcs">
<div id="close_btn" onclick="changeProfilePic('close')"></div>
<div id="nppf">
<div id="preview"><img src="assests/preview.png" width="150px" height="150px" id="thumb" /></div>
<form id="uploadPP" enctype="multipart/form-data">
<input id="image" name="image" type="file" class="form_fields" size="20" style="width:100%" />
<input type="hidden" id="user" name="user" value="session_generated_id"/>
<div id="npp_err_msg"></div>
<input type="button" id="changePPBtn" value="preview" onclick="check()" />
</form>
</div>
</div>
</div>
Javascript: -toggle profile picture change dialog/lightbox
function changeProfilePic(toggle){
var overlay = document.getElementById('ppuo');
var content = document.getElementById('ppufh');
if(toggle === 'open'){
//display overlay
$('#ppuo').fadeIn({complete:function(){}},500);
}else{
//hide display
$('#ppuo').fadeOut({complete:function(){}},500);
}
}
JavaScript: - upload image and start of JCrop
function check(){
var formData = new FormData($('#uploadPP')[0]);
$.ajax({
url: 'global.func/upLoadPP.php',
type: 'POST',
xhr: function(){
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
//myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
data: formData,
//Ajax events
//beforeSend: beforeSendHandler,
success: function(data){
var return_type = data.substr(0,1);
var data_type = data.split(":");
if(parseInt(data_type[0]) === 4 || data_type[0] === '4'){
//no error
$('#ppufh').animate({width:'800px',height:'80%',marginTop:'10%'},500);
document.getElementById('thumb').src = data_type[1];
document.getElementById('thumb').style.width = '80%';
document.getElementById('thumb').style.height = 'auto';
document.getElementById('ppufh').style.overflow = 'scroll';
$('#thumb').JCrop({
aspectRatio: 1,
onChange: updateCoords,
onSelect: updateCoords,
bgColor: 'blue',
bgOpacity: .5,
sideHandles:false,
minSize: [ 50, 50 ]
});
document.getElementById('changePPBtn').value = 'Finished Cropping';
$('#changePPBtn').on('click',function(){
window.alert("save new profile pic");
});
}else{
var err_msg = data_type[1];
document.getElementById('npp_err_msg').innerHTML = '<h3 style="text-align:left">'+data+'</h2>';
}
},
error: function(){
alert("There has been an internal server error. Please try again.");
},
cache: false,
contentType: false,
processData: false
});
}
PHP: -in case it helps but does work fine as a basic start
<?php
include '../constant/connect.php';
$row_count = mysql_num_rows(mysql_query("SELECT * FROM profile_pics"));
if(isset($_POST)){
$user_email = $_POST['user'];
$file = $_FILES['image'];
if($_FILES['image']['error'] > 0){
echo '0:php server error adjust php.ini file, then change this error message.';
}else{
$file_type = $_FILES['image']['type'];
$file_name = $_FILES['image']['name'];
$extention = explode('.',$file_name);
$extention = $extention[1];
if($extention == 'jpeg' || $extention == 'png' || $extention == 'gif'){
$path = '../images/user_profile_pictures';
$new_file_name = md5($file_name.$row_count).".".$extention;
move_uploaded_file($_FILES["image"]["tmp_name"], "../images/user_profile_pictures/" . $new_file_name);
$query = mysql_query("INSERT INTO profile_pics (pp_src,pp_owner) VALUES ('".$path."/".$new_file_name."','$user_email')")or die(mysql_error());
echo '4:images/user_profile_pictures/'.$new_file_name;
}else{
echo '1:Wrong type of file, use jpg, jpeg, png or gif. No animated Gifs.';
}
}
}else{
echo 'data not passed';
}
?>
It looks like it should work but there may be something I have missed and can't spot that somebody else can. So if anybody can help it would be greatly appreciated.
getElementById('thumb').style.height = 'auto';
document.getElementById('ppufh').style.overflow = 'scroll';
$('#thumb').JCrop({
aspectRatio: 1,
onChange: updateCoords,
onSelect: updateCoords,
bgColor: 'blue',
bgOpacity: .5,
sideHandles:false,
minSize: [ 50, 50 ]
});
document.getElementById('changePPBtn').value = 'Finished Cropping';
$('#changePPBtn').on('click',function(){
window.alert("save new profile pic");
});
}else{
var err_msg = data_type[1];
document.getElementById('npp_err_msg').innerHTML = '<h3 style="text-align:left">'+data+'</h2>';
}
},
error: function(){
alert("There has been an internal

Categories

Resources