Upload image from client to server using PHP - php

I'm using the jquery cropbox plugin:
https://github.com/hongkhanh/cropbox
With this source code:
http://cssdeck.com/labs/t8bdodvj
This plugin crops the image, and generates a new one on the client side.
The cropbox api provides 2 methods for accessing the image:
1) getDataURL()
2) getBlob()
My question is, how can I upload the new generated image from the client side to the server, with PHP:
- using getDataURL()?
- using getBlob()?
Code:
HTML
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Crop Box</title>
<link rel="stylesheet" href="style.css" type="text/css" />
<style>
.container
{
position: absolute;
top: 10%; left: 10%; right: 0; bottom: 0;
}
.action
{
width: 400px;
height: 30px;
margin: 10px 0;
}
.cropped>img
{
margin-right: 10px;
}
</style>
</head>
<body>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="../cropbox.js"></script>
<div class="container">
<div class="imageBox">
<div class="thumbBox"></div>
<div class="spinner" style="display: none">Loading...</div>
</div>
<div class="action">
<input type="file" id="file" style="float:left; width: 250px">
<input type="button" id="btnCrop" value="Crop" style="float: right">
<input type="button" id="btnZoomIn" value="+" style="float: right">
<input type="button" id="btnZoomOut" value="-" style="float: right">
</div>
<div class="cropped">
</div>
</div>
<script type="text/javascript">
$(window).load(function() {
var options =
{
thumbBox: '.thumbBox',
spinner: '.spinner',
imgSrc: 'avatar.png'
}
var cropper;
$('#file').on('change', function(){
var reader = new FileReader();
reader.onload = function(e) {
options.imgSrc = e.target.result;
cropper = $('.imageBox').cropbox(options);
}
reader.readAsDataURL(this.files[0]);
this.files = [];
})
$('#btnCrop').on('click', function(){
var img = cropper.getDataURL()
$('.cropped').append('<img src="'+img+'">');
})
$('#btnZoomIn').on('click', function(){
cropper.zoomIn();
})
$('#btnZoomOut').on('click', function(){
cropper.zoomOut();
})
});
</script>
</body>
</html>
CSS
.imageBox
{
position: relative;
height: 400px;
width: 400px;
border:1px solid #aaa;
background: #fff;
overflow: hidden;
background-repeat: no-repeat;
cursor:move;
}
.imageBox .thumbBox
{
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 200px;
margin-top: -100px;
margin-left: -100px;
border: 1px solid rgb(102, 102, 102);
box-shadow: 0 0 0 1000px rgba(0, 0, 0, 0.5);
background: none repeat scroll 0% 0% transparent;
}
.imageBox .spinner
{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
text-align: center;
line-height: 400px;
background: rgba(0,0,0,0.7);
}
JS
/**
* Created by ezgoing on 14/9/2014.
*/
"use strict";
(function (factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(jQuery);
}
}(function ($) {
var cropbox = function(options, el){
var el = el || $(options.imageBox),
obj =
{
state : {},
ratio : 1,
options : options,
imageBox : el,
thumbBox : el.find(options.thumbBox),
spinner : el.find(options.spinner),
image : new Image(),
getDataURL: function ()
{
var width = this.thumbBox.width(),
height = this.thumbBox.height(),
canvas = document.createElement("canvas"),
dim = el.css('background-position').split(' '),
size = el.css('background-size').split(' '),
dx = parseInt(dim[0]) - el.width()/2 + width/2,
dy = parseInt(dim[1]) - el.height()/2 + height/2,
dw = parseInt(size[0]),
dh = parseInt(size[1]),
sh = parseInt(this.image.height),
sw = parseInt(this.image.width);
canvas.width = width;
canvas.height = height;
var context = canvas.getContext("2d");
context.drawImage(this.image, 0, 0, sw, sh, dx, dy, dw, dh);
var imageData = canvas.toDataURL('image/png');
return imageData;
},
getBlob: function()
{
var imageData = this.getDataURL();
var b64 = imageData.replace('data:image/png;base64,','');
var binary = atob(b64);
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {type: 'image/png'});
},
zoomIn: function ()
{
this.ratio*=1.1;
setBackground();
},
zoomOut: function ()
{
this.ratio*=0.9;
setBackground();
}
},
setBackground = function()
{
var w = parseInt(obj.image.width)*obj.ratio;
var h = parseInt(obj.image.height)*obj.ratio;
var pw = (el.width() - w) / 2;
var ph = (el.height() - h) / 2;
el.css({
'background-image': 'url(' + obj.image.src + ')',
'background-size': w +'px ' + h + 'px',
'background-position': pw + 'px ' + ph + 'px',
'background-repeat': 'no-repeat'});
},
imgMouseDown = function(e)
{
e.stopImmediatePropagation();
obj.state.dragable = true;
obj.state.mouseX = e.clientX;
obj.state.mouseY = e.clientY;
},
imgMouseMove = function(e)
{
e.stopImmediatePropagation();
if (obj.state.dragable)
{
var x = e.clientX - obj.state.mouseX;
var y = e.clientY - obj.state.mouseY;
var bg = el.css('background-position').split(' ');
var bgX = x + parseInt(bg[0]);
var bgY = y + parseInt(bg[1]);
el.css('background-position', bgX +'px ' + bgY + 'px');
obj.state.mouseX = e.clientX;
obj.state.mouseY = e.clientY;
}
},
imgMouseUp = function(e)
{
e.stopImmediatePropagation();
obj.state.dragable = false;
},
zoomImage = function(e)
{
e.originalEvent.wheelDelta > 0 || e.originalEvent.detail < 0 ? obj.ratio*=1.1 : obj.ratio*=0.9;
setBackground();
}
obj.spinner.show();
obj.image.onload = function() {
obj.spinner.hide();
setBackground();
el.bind('mousedown', imgMouseDown);
el.bind('mousemove', imgMouseMove);
$(window).bind('mouseup', imgMouseUp);
el.bind('mousewheel DOMMouseScroll', zoomImage);
};
obj.image.src = options.imgSrc;
el.on('remove', function(){$(window).unbind('mouseup', imgMouseUp)});
return obj;
};
jQuery.fn.cropbox = function(options){
return new cropbox(options, this);
};
}));
Thanks in advance!

Related

Multiple photos and text via ajax in php

I edit multiple image upload scripts.
I added the features of uploading up to 3 photos and not uploading files larger than 5mb. It works successfully.
-- But I couldn't figure out how to define the text fields I added on js and how to send it to php document with post action.
Could you help?
I am posting the codes below.
php code:
<?php
$dts = $_POST['dts'];
$ttt = explode(',',$dts);
$others_image_last='';
$image_link="/upload_img/"; //folder name
for($i=0; $i<sizeof($_FILES['upload_files']['name']); $i++) {
if (in_array($i+1, $ttt)){}else{
$new_file = md5(microtime());
$image_type = $_FILES["upload_files"]["type"][$i];
$image_name = $_FILES["upload_files"]["name"][$i];
$image_error = $_FILES["upload_files"]["error"][$i];
$image_temp_name = $_FILES["upload_files"]["tmp_name"][$i];
print_r($image_temp_name);
if (($image_type == "image/jpeg") || ($image_type == "image/png") || ($image_type == "image/pjpeg") || ($image_type == "image/jpg")) {
$test = explode('.', $image_name);
$name = $new_file.'.'.end($test);
$url = '.'.$image_link. $name;
$info = getimagesize($image_temp_name);
if ($info['mime'] == 'image/jpeg') $image = imagecreatefromjpeg($image_temp_name);
elseif ($info['mime'] == 'image/gif') $image = imagecreatefromgif($image_temp_name);
elseif ($info['mime'] == 'image/png') $image = imagecreatefrompng($image_temp_name);
imagejpeg($image,$url,80);
}
echo $name;
/****** insert query here ******/
}
}?>
Html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<title>Multiple Photo Upload</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<style>
.suggested-posts-article{
background: white;
-moz-box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
-webkit-box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
box-shadow: rgba(0,0,0,0.0666) 0 3px 10px;
display: inline-block;
margin: 5px;
width: 23%;
}
article, aside, details, figcaption, figure, footer, header, main, nav, section {
display: block;
}
article, aside, footer, header, hgroup, main, nav, section {
display: block;
}
.suggested-posts-articlees {
display: inline-block;
width: 49.5%;
}
#media screen and (max-width:450px) {
.suggested-posts-article {
width:40% !important;
}
}
.more-photos:after{ right: 3px !important;
bottom: 0px !important;}
article, aside, details, figcaption, figure, footer, header, main, nav, section {
display: block;
}
.posts_article {
background-color: #333;
background-position: 50%;
background-size: cover;
margin-bottom: 2px;
padding-bottom: 63.5%;
}
#media screen and (max-width:450px) {
.suggested-posts-article {
width:40% !important;
}
}
.more-photos:after{ right: 3px !important;
bottom: 0px !important;}
.more-photos{
cursor:pointer !important;
}
.bluess {
width:100%;
margin:10px;
}
.btn-group-sm>.btn, .btn-sm {
padding: .25rem .5rem;
font-size: .875rem;
line-height: 1.5;
border-radius: .2rem;
}
.btn-outline-secondary {
color: #868e96;
background-color: transparent;
background-image: none;
border-color: #868e96;
}
.btnxc {
display: inline-block;
padding: .5rem .75rem;
border:1px solid #868e96;
margin:3px;
padding: .25rem .5rem;
font-size: .875rem;
line-height: 1.5;
border-radius: .2rem;
color:#868e96;
}
.rrrr{
color:red;
fill:red;
}
.rrrr2{
background-color: red;
}
.datepost{
margin-top:-15px;
}
.anther_ma
{
margin:1px;
}
.set_process
{
margin: 0px 7px 0px 0px;
}
.messaf{display:none;}
.progress{
width:80%;
}
.success_msg{
color:green;
display:none;
}
#post_send{
margin:8px 0 8px 0;
}
.fa_p{
margin-right:20px;
margin-top:10px;
border:0px;
z-index:9999
}
.p_run_div{
margin-top:-7px;
border-radius:0px;
padding:0px;
margin-bottom:8px;
display:none;
}
.btnxc{
margin-left:15px;
cursor:pointer;
}
.btnxc_r{
margin-left:15px;
display:none;
}
</style>
<div class="container">
<div class="row">
<div class="col-md-8">
<h2>Multiple Photo Upload</h2>
<div class="form-group">
<label for="examplename">Name</label>
<input type="text" class="form-control" id="examplename" placeholder="First Name">
</div>
<div class="form-group">
<label for="examplesurname">First Name</label>
<input type="text" class="form-control" id="examplesurname" placeholder="Last Name">
</div>
<div><button class="imgbuts btn btn-success" style='float:left'>Choose Photo...</button> <div id="uyari" style='float:left'>You can upload 3 photos.<br>
Each photo should not be larger than 5 mb.</b></div></div>
<div style="clear:both"></div>
<form action="method" name="upload-file" class="main_form" id="form-upload-file" enctype="multipart/form-data">
<div class="ui-block">
<aside class="suggested-posts">
<div class="suggested-posts-container">
<div class="row" id="message_box"></div>
</div>
</aside>
</div>
</form>
<button class="btn btn-primary btn-md-2 " id='post_send' onclick="save_muliple_image()">Upload</button>
<div class="progress">
<div class="progress-bar" role="progressbar" style="width:0%">
<span class="sr-only">0</span>
</div>
</div>
<h2 class="success_msg">Photo upload completed.</h2>
</div>
</div>
</div>
<script>
var xp = 0;
var input_btn = 0;
var dts = [];
$(document).on("click", ".imgbuts", function (e) {
if(xp < 3){
input_btn++;
$("#form-upload-file").append(
"<input type='file' style='display:none;' name='upload_files[]' id='filenumber" +
input_btn +
"' class='img_file upload_files' accept='.gif,.jpg,.jpeg,.png,' multiple/>"
);
$("#filenumber" + input_btn).click();
} else {
uyari.innerHTML = ' You can upload up to 3 photos.';
}
});
$(document).on("change", ".upload_files", function (e){
files = e.target.files;
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
xp++;
var f = files[i];
var boyut = f.size;
var res_ext = files[i].name.split(".");
var img_or_video = res_ext[res_ext.length - 1];
var fileReader = new FileReader();
var yuvarlama = (boyut / (1024*1024)).toFixed(2) + ' mb';
uyari.innerHTML = '';
if (boyut > 5000000) {uyari.innerHTML = ' File size larger than 5mb'; xp--; return;}
fileReader.name = f.name;
fileReader.onload = function (e) {
var file = e.target;
$("#message_box").append(
"<article class='suggested-posts-article remove_artical" +
xp +
"' data-file='" +
file.name +
"'><div class='posts_article background_v" +
xp +
"' style='background-image: url(" +
e.target.result +
")'></div><div class='p_run_div'><span class='pp_run progress_run" +
xp +
"' style='opacity: 1;'></span></div><p class='fa_p p_for_fa" +
xp +
"'><span class='cancel_mutile_image btnxc cancel_fa" +
xp +
"' deltsid='"+0+"'><b>✖ SİL</b></span><span class='btnxc btnxc_r' >✔</span><span style='float:right'>"+ yuvarlama +"</span></p></article>"
);
};
fileReader.readAsDataURL(f);
}
});
function save_muliple_image() {
suggested = $(".suggested-posts-article").length;
if (suggested > 0) {
$(".cancel_mutile_image").prop("disabled", true);
$("#post_send").prop("disabled", true);
var formData = new FormData(document.getElementById("form-upload-file"));
formData.append("dts", dts);
var xhr = new window.XMLHttpRequest();
$.ajax({
url: 'upload_ajax.php',
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function (data) {
$(".main-content").find(".message-loading-overlay2").remove();
},
error: function (e) {
$("#preview_file_div ul").html(
"<li class='text-danger'>Something wrong! Please try again.</li>"
);
},
xhr: function (e) {
xhr.upload.addEventListener(
"progress",
function (e) {
console.log(e);
if (e.lengthComputable) {
var percentComplete = ((e.loaded || e.position) * 100) / e.total;
if(percentComplete==100){
$(".progress-bar").width(percentComplete + "%").html('99' + "%");
}else{
var yuzde = Math.floor(percentComplete);
$(".progress-bar").width(percentComplete + "%").html(yuzde + "%"); }
}
},
false
);
xhr.addEventListener("load", function (e) {
$('.progress-bar').css("background","#5cb85c").html('100' + "%");
$(".btnxc_r").show();
$(".success_msg").show();
$(".cancel_mutile_image").remove();
});
return xhr;
},
});
} else {
$(".messaf").show();
}
}
var rty=0;
$(document).on("click", ".cancel_mutile_image", function (e) {
$('.cancel_mutile_image').each(function(){
chk_id = $(this).attr('deltsid');
if(chk_id==0){ rty++; $(this).attr('deltsid',rty); }
});
deltsid = $(this).attr('deltsid');
dts.push(deltsid);
$(this).parents(".suggested-posts-article").remove();
xp--;
});
</script>
</body>
</html>
Uploading multiple files in php can be tricky but the trick you need to use here is that instead of using name="upload" in input filed use name="upload[]" it returns an array so it makes the code much cleaner ... And to upload files use loops ( I used for loop in to see demonstrate how to upload different files here ) you can write some js and before uploading add some validations as per your needs !
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
$path = "./"; // Specifiy the path where uploaded files goes
// Count # of uploaded files in array
$total = count($_FILES['upload']['name']);
// Loop through each file
for ($i = 0; $i < $total; $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['upload']['tmp_name'][$i];
//Make sure we have a file path
if ($tmpFilePath != "") {
$target_path = $path;
$target_path = $target_path.basename($_FILES['upload']['name'][$i]);
// Upload files (YOUR IMAGES) into desired directory !
if (move_uploaded_file($tmpFilePath, $target_path)) {
$success = "success";
}
}
}
}
?>
<form action="index.php" method="POST" accept-charset="utf-8" enctype="multipart/form-data">
<input type="file" name="upload[]" multiple />
<button type="submit">Submit</button>
</form>

Authorize.net Hosted Form stuck on "processing", no response via communicator file

I am trying to follow this example by authorize.net on a simple page for testing purposes
https://developer.authorize.net/api/reference/features/accept_hosted.html#Integrating_the_Form_Using_Iframes_and_Lightboxes
I am using the iFrame/ Lightbox variation, and am creating the Form Token with this PHP SDK snippet:
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName(\CodeConstants::MERCHANT_LOGIN_ID);
$merchantAuthentication->setTransactionKey(\CodeConstants::MERCHANT_TRANSACTION_KEY);
// Set the transaction's refId
$refId = 'ref' . time();
//create a transaction
$transactionRequestType = new AnetAPI\TransactionRequestType();
$transactionRequestType->setTransactionType("authCaptureTransaction");
$transactionRequestType->setAmount($amount);
// Set Hosted Form options
$setting1 = new AnetAPI\SettingType();
$setting1->setSettingName("hostedPaymentButtonOptions");
$setting1->setSettingValue("{\"text\": \"Pay now\"}");
$setting2 = new AnetAPI\SettingType();
$setting2->setSettingName("hostedPaymentOrderOptions");
$setting2->setSettingValue("{\"show\": false}");
$setting3 = new AnetAPI\SettingType();
$setting3->setSettingName("hostedPaymentReturnOptions");
$setting3->setSettingValue("{\"showReceipt\": false, \"url\" : \"https://website.com/communicator.html\"}");
$setting4 = new AnetAPI\SettingType();
$setting4->setSettingName("hostedPaymentBillingAddressOptions");
$setting4->setSettingValue("{\"show\": false, \"required\": false}");
$setting5 = new AnetAPI\SettingType();
$setting5->setSettingName("hostedPaymentIFrameCommunicatorUrl");
$setting5->setSettingValue("{\"url\": \"https://website.com/communicator.html\"}");
$setting6 = new AnetAPI\SettingType();
$setting6->setSettingName("hostedPaymentPaymentOptions");
$setting6->setSettingValue("{\"cardCodeRequired\": true, \"showBankAccount\": false}");
// Build transaction request
$request = new AnetAPI\GetHostedPaymentPageRequest();
$request->setMerchantAuthentication($merchantAuthentication);
$request->setRefId($refId);
$request->setTransactionRequest($transactionRequestType);
$request->addToHostedPaymentSettings($setting1);
$request->addToHostedPaymentSettings($setting2);
$request->addToHostedPaymentSettings($setting3);
$request->addToHostedPaymentSettings($setting4);
$request->addToHostedPaymentSettings($setting5);
$request->addToHostedPaymentSettings($setting6);
//execute request
$controller = new AnetController\GetHostedPaymentPageController($request);
$response = $controller->executeWithApiResponse(\net\authorize\api\constants\ANetEnvironment::SANDBOX);
if (($response != null) && ($response->getMessages()->getResultCode() == "Ok")) {
return $response->getToken()."\n";
} else {
echo "ERROR : Failed to get hosted payment page token\n";
$errorMessages = $response->getMessages()->getMessage();
echo "RESPONSE : " . $errorMessages[0]->getCode() . " " .$errorMessages[0]->getText() . "\n";
return FALSE;
}
which is working fine, I get a token and can proceed with this code to have on the webpage (copied from the authorize.net tutorial)
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<script src="scripts/jquery.min.js"></script>
<script src="scripts/bootstrap.min.js"></script>
<title>HostedPayment Test Page</title>
<style type="text/css">
body {
margin: 0px;
padding: 0px;
}
#divAuthorizeNetPopupScreen {
left: 0px;
top: 0px;
width: 100%;
height: 100%;
z-index: 1;
background-color: #808080;
opacity: 0.5;
-ms-filter: 'progid:DXImageTransform.Microsoft.Alpha(Opacity=50)';
filter: alpha(opacity=50);
}
#divAuthorizeNetPopup {
position: absolute;
left: 50%;
top: 50%;
margin-left: -200px;
margin-top: -200px;
z-index: 2;
overflow: visible;
}
.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupOuter {
background-color: #dddddd;
border-width: 1px;
border-style: solid;
border-color: #a0a0a0 #909090 #909090 #a0a0a0;
padding: 4px;
}
.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupTop {
height: 23px;
}
.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupClose {
position: absolute;
right: 7px;
top: 7px;
}
.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupClose a {
background-image: url('content/closeButton1.png');
background-repeat: no-repeat;
height: 16px;
width: 16px;
display: inline-block;
}
.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupClose a:hover {
background-image: url('content/closeButton1h.png');
}
.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupClose a:active {
background-image: url('content/closeButton1a.png');
}
.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupInner {
background-color: #ffffff;
border-width: 2px;
border-style: solid;
border-color: #cfcfcf #ebebeb #ebebeb #cfcfcf;
}
.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupBottom {
height: 30px;
}
.AuthorizeNetPopupGrayFrameTheme .AuthorizeNetPopupLogo {
position: absolute;
right: 9px;
bottom: 4px;
width: 200px;
height: 25px;
background-image: url('content/powered_simple.png');
}
.AuthorizeNetPopupSimpleTheme .AuthorizeNetPopupOuter {
border: 1px solid #585858;
background-color: #ffffff;
}
</style>
</head>
<body>
<form method="post" action="https://test.authorize.net/payment/payment" id="formAuthorizeNetPopup" name="formAuthorizeNetPopup" target="iframeAuthorizeNet" style="display:none;">
<input type="hidden" id="popupToken" name="token" value="Replace with form token from getHostedPaymentPageResponse" />
</form>
<input type="text" id="inputtoken" value="" />
<br />
<div>
Trigger Accept Transaction
<button id="btnOpenAuthorizeNetPopup" onclick="AuthorizeNetPopup.openPopup()">Open AuthorizeNetPopup</button>
</div>
<div id="divAuthorizeNetPopup" style="display:none;" class="AuthorizeNetPopupGrayFrameTheme">
<div class="AuthorizeNetPopupOuter">
<div class="AuthorizeNetPopupTop">
<div class="AuthorizeNetPopupClose">
</div>
</div>
<div class="AuthorizeNetPopupInner">
<iframe name="iframeAuthorizeNet" id="iframeAuthorizeNet" src="empty.html" frameborder="0" scrolling="no"></iframe>
</div>
<div class="AuthorizeNetPopupBottom">
<div class="AuthorizeNetPopupLogo" title="Powered by Authorize.Net"></div>
</div>
<div id="divAuthorizeNetPopupScreen" style="display:none;"></div>
</div>
</div>
<script type="text/javascript">
(function () {
if (!window.AuthorizeNetPopup) window.AuthorizeNetPopup = {};
if (!AuthorizeNetPopup.options) AuthorizeNetPopup.options = {
onPopupClosed: null
};
AuthorizeNetPopup.closePopup = function () {
document.getElementById("divAuthorizeNetPopupScreen").style.display = "none";
document.getElementById("divAuthorizeNetPopup").style.display = "none";
document.getElementById("iframeAuthorizeNet").src = "empty.html";
document.getElementById("btnOpenAuthorizeNetPopup").disabled = false;
if (AuthorizeNetPopup.options.onPopupClosed) AuthorizeNetPopup.options.onPopupClosed();
};
AuthorizeNetPopup.openPopup = function () {
var popup = document.getElementById("divAuthorizeNetPopup");
var popupScreen = document.getElementById("divAuthorizeNetPopupScreen");
var ifrm = document.getElementById("iframeAuthorizeNet");
var form = document.forms["formAuthorizeNetPopup"];
$("#popupToken").val($("#inputtoken").val());
form.action = "https://test.authorize.net/payment/payment";
ifrm.style.width = "442px";
ifrm.style.height = "1000px";
form.submit();
popup.style.display = "";
popupScreen.style.display = "";
centerPopup();
};
AuthorizeNetPopup.onReceiveCommunication = function (querystr) {
var params = parseQueryString(querystr);
switch (params["action"]) {
case "successfulSave":
AuthorizeNetPopup.closePopup();
break;
case "cancel":
AuthorizeNetPopup.closePopup();
break;
case "transactResponse":
var response = params["response"];
document.getElementById("token").value = response;
AuthorizeNetPopup.closePopup();
break;
case "resizeWindow":
var w = parseInt(params["width"]);
var h = parseInt(params["height"]);
var ifrm = document.getElementById("iframeAuthorizeNet");
ifrm.style.width = w.toString() + "px";
ifrm.style.height = h.toString() + "px";
centerPopup();
break;
}
};
function centerPopup() {
var d = document.getElementById("divAuthorizeNetPopup");
d.style.left = "50%";
d.style.top = "50%";
var left = -Math.floor(d.clientWidth / 2);
var top = -Math.floor(d.clientHeight / 2);
d.style.marginLeft = left.toString() + "px";
d.style.marginTop = top.toString() + "px";
d.style.zIndex = "2";
if (d.offsetLeft < 16) {
d.style.left = "16px";
d.style.marginLeft = "0px";
}
if (d.offsetTop < 16) {
d.style.top = "16px";
d.style.marginTop = "0px";
}
}
function parseQueryString(str) {
var vars = [];
var arr = str.split('&');
var pair;
for (var i = 0; i < arr.length; i++) {
pair = arr[i].split('=');
vars.push(pair[0]);
vars[pair[0]] = unescape(pair[1]);
}
return vars;
}
}());
</script>
</body>
</html>
Basically I just followed the tutorial... but when i click on "pay", the form gets stuck at "processing" and I do not seem to get any response via the communicator.
I even added:
AuthorizeNetPopup.onReceiveCommunication = function (querystr) {
console.log(querystr);
To log any communication, but there is never anything logged...
What am I doing wrong here, I feel like I just copy pasted but i do not get it to work...
Thanks for any help!

to upload croped image into database

I want to upload cropped image into database. I am using jquery canvas crop so I can crop the image properly but it is not uploading into database. I tried lots of ways but didn't get success. Please help me out. Give me php code for uploading cropped image. Also i want to resize the image using jquery how can i fullfill this need? please guide me
$(function(){
var rot = 0,ratio = 1;
var CanvasCrop = $.CanvasCrop({
cropBox : ".imageBox",
imgSrc : "images/avatar.jpg",
limitOver : 2
});
$('#upload-file').on('change', function(){
var reader = new FileReader();
reader.onload = function(e) {
CanvasCrop = $.CanvasCrop({
cropBox : ".imageBox",
imgSrc : e.target.result,
limitOver : 2
});
rot =0 ;
ratio = 0;
}
reader.readAsDataURL(this.files[0]);
this.files = [];
});
$("#rotateLeft").on("click",function(){
rot -= 90;
rot = rot<0?270:rot;
CanvasCrop.rotate(rot);
});
$("#rotateRight").on("click",function(){
rot += 90;
rot = rot>360?90:rot;
CanvasCrop.rotate(rot);
});
$("#zoomIn").on("click",function(){
ratio =ratio*0.9;
CanvasCrop.scale(ratio);
});
$("#zoomOut").on("click",function(){
ratio =ratio*1.1;
CanvasCrop.scale(ratio);
});
$("#alertInfo").on("click",function(){
var canvas = document.getElementById("visbleCanvas");
var context = canvas.getContext("2d");
context.clearRect(0,0,canvas.width,canvas.height);
});
$("#crop").on("click",function(){
var src = CanvasCrop.getDataURL("jpeg");
//$("body").append("<div style='word-break: break-all;'>"+src+"</div>");
$(".container").append("<img class='img1'name='image' src='"+src+"' />");
});
console.log("ontouchend" in document);
})
$().cropper('getCroppedCanvas').toBlob(function (blob) {
var formData = new FormData();
formData.append('croppedImage', blob);
$.ajax('index.php', {
method: "POST",
data: formData,
processData: false,
contentType: false,
success: function () {
console.log('Upload success');
},
error: function () {
console.log('Upload error');
}
});
});
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-36251023-1']);
_gaq.push(['_setDomainName', 'jqueryscript.net']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
<style>
.tools{
margin-top: 20px;
}
.tools span{
float: left;
display: inline-block;
padding: 5px 20px;
background-color: #f40;
color: #fff;
cursor: pointer;
margin-bottom: 5px;
margin-right: 5px;
}
.clearfix {
*zoom: 1;
}
.clearfix:before{
content: " ";
display: table;
}
.clearfix:after{
content: " ";
display: table;
clear: both;
}
.cropPoint{
position: absolute;
height: 8px;
width: 8px;
background-color: rgba(255,255,255,0.7);
cursor: pointer;
}
.upload-wapper{
position: relative;
float: left;
height: 26px;
line-height: 26px;
width: 132px;
background-color: #f40;
color: #fff;
text-align: center;
overflow: hidden;
cursor: pointer;
}
#upload-file{
position: absolute;
left: 0;
top: 0;
opacity: 0;
filter: alpha(opacity=0);
width: 132px;
height: 26px;
cursor: pointer;
}
</style>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery.CanvasCrop.js DEMO演示</title>
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link href='http://fonts.googleapis.com/css?family=Open+Sans' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<link rel="stylesheet" href="css/canvasCrop.css" />
</head>
<body>
<div id="jquery-script-menu">
<div class="jquery-script-center">
<div class="jquery-script-clear"></div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script type="text/javascript" src="js/jquery.canvasCrop.js" ></script>
<div class="container">
<form action=""role="form" method="post" enctype="multipart/form-data">
<div class="imageBox" >
<!--<div id="img" ></div>-->
<!--<img class="cropImg" id="img" style="display: none;" src="images/avatar.jpg" />-->
<div class="mask"></div>
<div class="thumbBox"></div>
<div class="spinner" style="display: none">Loading...</div>
</div>
<div class="tools clearfix">
<span id="rotateLeft" >rotateLeft</span>
<span id="rotateRight" >rotateRight</span>
<span id="zoomIn" >zoomIn</span>
<span id="zoomOut" >zoomOut</span>
<span id="crop" >Crop</span>
<span id="alertInfo" >alert</span>
<div class="upload-wapper">
Select An Image
<input type="file" name="upload" id="upload-file" value="Upload" />
</div>
<input type="submit"name="submit"></input>
</div>
</form>
<!---<img height="50%" width="50%" src="<?php echo $fet[1];?>"class="img-responsive;"/>-->
</div>
</body>
</html>

Update when dragged and resized Jquery

I got the jquery variables to update the height width and positions when the divs are dragged but I need them to do the same when they are resized....how can I do this? Here is my code that I'm using right now to get the variables and send them to the php document:
<?
$query = mysql_query("SELECT * FROM users WHERE username='derekshull'");
$rows = mysql_fetch_array($query);
$googlewebx = $rows['googlewebx'];
$googleweby = $rows['googleweby'];
$googlewebh = $rows['googlewebh'];
$googlewebw = $rows['googlewebw'];
$googleimagex = $rows['googleimagex'];
$googleimagey = $rows['googleimagey'];
$googleimageh = $rows['googleimageh'];
$googleimagew = $rows['googleimagew'];
$googlenewsx = $rows['googlenewsx'];
$googlenewsy = $rows['googlenewsy'];
$googlenewsh = $rows['googlenewsh'];
$googlenewsw = $rows['googlenewsw'];
$wikix = $rows['wikix'];
$wikiy = $rows['wikiy'];
$wikih = $rows['wikih'];
$wikiw = $rows['wikiw'];
$wolfx = $rows['wolfx'];
$wolfy = $rows['wolfy'];
$wolfh = $rows['wolfh'];
$wolfw = $rows['wolfw'];
$twitterx = $rows['twitterx'];
$twittery = $rows['twittery'];
$twitterh = $rows['twitterh'];
$twitterw = $rows['twitterw'];
?>
<html>
<head>
<style>
.resizable { color: white; width: 1px; height: 1px; padding: 0.1em; bottom: 0; left: 0; }
.resizable h3 { text-align: center; margin: 0; }
</style>
<style>
#set div.resizable {
background: rgba(0, 157, 255, 0.9);
color: black;
float: left;
margin: 0 10px 10px 0;
padding: 0.5em;
}
#set { clear:both; float:left; width: 368px;}
p { clear:both; margin:0; padding:1em 0; }
</style>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<script>
function stop(ui, type) {
var pos_x;
var pos_y;
var window_width;
var window_height;
var need;
if (type == 'draggable') {
pos_x = ui.offset.left;
pos_y = ui.offset.top;
window_width = window.innerWidth;
window_height = window.innerHeight;
need = ui.helper.data("need");
} else if (type == 'resizable') {
pos_x = $(ui.element).offset().left;
pos_y = $(ui.element).offset().top;
window_width = window.innerWidth;
window_height = window.innerHeight;
need = ui.helper.data("need");
}
var width;
var height;
if (need == 1) {
width = $("#web").width();
height = $("#web").height();
}
if (need == 2) {
width = $("#image").width();
height = $("#image").height();
}
if (need == 3) {
width = $("#wiki").width();
height = $("#wiki").height();
}
if (need == 4) {
width = $("#twitter").width();
height = $("#twitter").height();
}
if (need == 5) {
width = $("#googlenews").width();
height = $("#googlenews").height();
}
if (need == 6) {
width = $("#wolf").width();
height = $("#wolf").height();
}
console.log(pos_x);
console.log(pos_y);
console.log(width);
console.log(window_width);
console.log(need);
//Do the ajax call to the server
alert(' x:' + pos_x +
' y:' + pos_y +
' ned_id:' + need +
' width:' + width +
' height:' + height +
' window_width:' + window_width +
' window_height:' + window_height);
}
$("#set div").draggable({
stack: "#set div",
preventCollision: true,
containment: $('#main_content'),
stop: function (event, ui) {
stop(ui, 'draggable');
}
});
$(".resizable").resizable({
stop: function (event, ui) {
stop(ui, 'resizable');
}
});
</script>
<meta http-equiv='Content-type' content='text/html;charset=UTF-8'>
<title>15:11 Project | You • Your Community • Your World</title>
</head>
<body>
<form action='' method='post'>
<fieldset><center>
<input type='search' name='q' /><input type='submit' value='Search' name='submit' />
</fieldset></center>
</form>
<div id="main_content" style="position: fixed; bottom: 0; left: 0; width:100.8%; margin:0 auto; height:95.1%; background-color: #ffffff; color: #000000;">
<div id="set">
<?
if(isset($_POST['q'])){
?>
<div id='web' style='overflow:hidden; left: 5%; top: 5%; width: 20%; height: 15%; position:fixed !important;' class='resizable ui-widget-content' data-need='1'>
<?php
enter code here for div 1.
echo "</div>";
}
?>
<?
if(isset($_POST['q'])){
?>
<div id='image' style='overflow:hidden; height: 19%; width: 32%; left: 60%; top: 12%; position:fixed !important;' class='resizable ui-widget-content' data-need='2'><center>
<?php
Enter code here for div 2
echo "</center></div>";
}
?>
<?
if(isset($_POST['q'])){
?>
<div id='wiki' style='overflow:hidden; left: 5%; top: 36%; height: 17%; width: 25%; position:fixed !important;' class='resizable ui-widget-content' data-need='3'>
<?php
Enter div 3.
}
?>
</div>
</div>
</div>
You can attach a function to the stop event...
$(function() {
$( ".resizable" ).resizable({
stop: function(){
// Do your updates here
}
});
});
Working fiddle:
http://jsfiddle.net/zkDHJ/
Resizable function has the same event stop and you can create a function to do what you are doing in draggable stop and call it from resizable stop
http://api.jqueryui.com/resizable/#event-stop
$(function() {
$( ".resizable" ).resizable({
stop: function() {
// call the same function as in draggable event stop
}
});
});
I would recommend creating a function to call from both events such as
function stop(ui, type) {
// your code
}
And then call it from both events:
$( ".resizable" ).resizable({
stop: function(event, ui) {
stop(ui, 'resizable');
)};
$( ".draggable" ).resizable({
stop: function(event, ui) {
stop(ui, 'draggable');
}
)};
EDIT: You see can see this jsfiddle showing you code working:
http://jsfiddle.net/v8efG/1/
There's a difference from the objects returned by draggable and resizable.
Draggable contains an offset property you can just use. Take a look at the wiki:
http://api.jqueryui.com/draggable/#event-stop
And Resizable does not contain offset but it contains element and you can obtain the offset from it. Take a look at the wiki:
http://api.jqueryui.com/resizable/#event-stop
When draggable
pos_x = ui.offset.left;
When resizable
pos_x = $(ui.element).offset().left;

how to replace any progress bar with jqueryui.com's custom label progress bar?

i have a multiple file upload code below. What i want to do is I want to replace the progress bar in this code with the custom label progress bar from jqueryui.com .I really dont have any idea how do i do it. can anyone help?
Here's the code:
<!doctype html>
<head>
<title>File Upload Progress Demo #2</title>
<style>
body { padding: 30px }
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>File Upload Progress Demo #2</h1>
<code><input type="file" name="myfile[]" multiple></code>
<form action="file-echo2.php" method="post" enctype="multipart/form-data">
<input type="file" name="myfile[]" multiple><br>
<input type="submit" value="Upload File to Server">
</form>
<div class="progress">
<div class="bar"></div >
<div class="percent">0%</div >
</div>
<div id="status"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function() {
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
$('form').ajaxForm({
beforeSend: function() {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
//console.log(percentVal, position, total);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
<script src="http://www.google-analytics.com/urchin.js" type="text/javascript"></script>
<script type="text/javascript">
_uacct = "UA-850242-2";
urchinTracker();
</script>
Here's PHP script to upload files:
<?php
foreach($_FILES as $file) {
$n = $file['name'];
$s = $file['size'];
if (is_array($n)) {
$c = count($n);
for ($i=0; $i < $c; $i++) {
echo "<br>uploaded: " . $n[$i] . " (" . $s[$i] . " bytes)";
}
}
else
echo "<br>uploaded: $n ($s bytes)";
}
?>
Here's the code for Custom Label Progress bar :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Progressbar - Custom Label</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
.progress-label {
float: left;
margin-left: 50%;
margin-top: 5px;
font-weight: bold;
text-shadow: 1px 1px 0 #fff;
}
</style>
<script>
$(function() {
var progressbar = $( "#progressbar" ),
progressLabel = $( ".progress-label" );
progressbar.progressbar({
value: false,
change: function() {
progressLabel.text( progressbar.progressbar( "value" ) + "%" );
},
complete: function() {
progressLabel.text( "Complete!" );
}
});
function progress() {
var val = progressbar.progressbar( "value" ) || 0;
progressbar.progressbar( "value", val + 1 );
if ( val < 99 ) {
setTimeout( progress, 100 );
}
}
setTimeout( progress, 3000 );
});
</script>
</head>
<body>
<div id="progressbar"><div class="progress-label">Loading...</div></div>
</body>
</html>
you can try the "if".
if(percentVal == 50);){
percent.html("you´re text here.");
}
you can create another HTML tag and do the same of the percent var.
var uploadText = document.getElementById(".newTag") or $('.newTag');
if(percentVal == 50);){
uploadText.html("you´re text here.");
}

Categories