So im trying to have an upload with a progress bar, i installed uploadprogress pecl, and the upload worked perfectly if the action in the form leads to upload.php, any other name, and it stops working.
If the name is not upload.php the output is simply "100" (which can be seen why below with the getprogress.php file)
this is the form: (this versions works, as the file is upload.php)
<form method="post" action="/test/upload.php" enctype="multipart/form-data" id="upload-form" target="upload-frame">
<input type="hidden" id="uid" name="UPLOAD_IDENTIFIER" value="<?php echo $uid; ?>">
<input type="file" name="file">
<input type="submit" name="submit" value="Upload!">
</form>
</div>
<div style="float:left;width:100%;">
<div id="progress-bar"></div>
</div>
<iframe id="upload-frame" name="upload-frame"></iframe>
this is the jquery:
<script>
(function ($) {
var pbar;
var started = false;
$(function () {
$('#upload-form').submit(function() {
pbar = $('#progress-bar');
pbar.show().progressbar();
$('#upload-frame').load(function () {
started = true;
});
setTimeout(function () {
updateProgress($('#uid').val());
}, 1000);
});
});
function updateProgress(id) {
var time = new Date().getTime();
$.get('../uploadprogress/getprogress.php', { uid: id, t: time }, function (data) {
var progress = parseInt(data, 10);
if (progress < 100 || !started) {
started = progress < 100;
updateProgress(id);
}
started && pbar.progressbar('value', progress);
});
}
}(jQuery));
</script>
this is the file getprogress.php
<?php
if (isset($_GET['uid'])) {
// Fetch the upload progress data
$status = uploadprogress_get_info($_GET['uid']);
if ($status) {
// Calculate the current percentage
echo round($status['bytes_uploaded']/$status['bytes_total']*100, 1);
}
else {
// If there is no data, assume it's done
echo 100;
}
}
?>
ive spent about 5 hours on this trying to figure out why, and i cant. help would be greatly appreciated.
You can use this class, without using jquery:
<?php
/**
* Progress bar for a lengthy PHP process
* http://spidgorny.blogspot.com/2012/02/progress-bar-for-lengthy-php-process.html
*/
class ProgressBar {
var $percentDone = 0;
var $pbid;
var $pbarid;
var $tbarid;
var $textid;
var $decimals = 1;
function __construct($percentDone = 0) {
$this->pbid = 'pb';
$this->pbarid = 'progress-bar';
$this->tbarid = 'transparent-bar';
$this->textid = 'pb_text';
$this->percentDone = $percentDone;
}
function render() {
//print ($GLOBALS['CONTENT']);
//$GLOBALS['CONTENT'] = '';
print($this->getContent());
$this->flush();
//$this->setProgressBarProgress(0);
}
function getContent() {
$this->percentDone = floatval($this->percentDone);
$percentDone = number_format($this->percentDone, $this->decimals, '.', '') .'%';
$content .= '<div id="'.$this->pbid.'" class="pb_container">
<div id="'.$this->textid.'" class="'.$this->textid.'">'.$percentDone.'</div>
<div class="pb_bar">
<div id="'.$this->pbarid.'" class="pb_before"
style="width: '.$percentDone.';"></div>
<div id="'.$this->tbarid.'" class="pb_after"></div>
</div>
<br style="height: 1px; font-size: 1px;"/>
</div>
<style>
.pb_container {
position: relative;
}
.pb_bar {
width: 100%;
height: 1.3em;
border: 1px solid silver;
-moz-border-radius-topleft: 5px;
-moz-border-radius-topright: 5px;
-moz-border-radius-bottomleft: 5px;
-moz-border-radius-bottomright: 5px;
-webkit-border-top-left-radius: 5px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
}
.pb_before {
float: left;
height: 1.3em;
background-color: #43b6df;
-moz-border-radius-topleft: 5px;
-moz-border-radius-bottomleft: 5px;
-webkit-border-top-left-radius: 5px;
-webkit-border-bottom-left-radius: 5px;
}
.pb_after {
float: left;
background-color: #FEFEFE;
-moz-border-radius-topright: 5px;
-moz-border-radius-bottomright: 5px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 5px;
}
.pb_text {
padding-top: 0.1em;
position: absolute;
left: 48%;
}
</style>'."\r\n";
return $content;
}
function setProgressBarProgress($percentDone, $text = '') {
$this->percentDone = $percentDone;
$text = $text ? $text : number_format($this->percentDone, $this->decimals, '.', '').'%';
print('
<script type="text/javascript">
if (document.getElementById("'.$this->pbarid.'")) {
document.getElementById("'.$this->pbarid.'").style.width = "'.$percentDone.'%";');
if ($percentDone == 100) {
print('document.getElementById("'.$this->pbid.'").style.display = "none";');
} else {
print('document.getElementById("'.$this->tbarid.'").style.width = "'.(100-$percentDone).'%";');
}
if ($text) {
print('document.getElementById("'.$this->textid.'").innerHTML = "'.htmlspecialchars($text).'";');
}
print('}</script>'."\n");
$this->flush();
}
function flush() {
print str_pad('', intval(ini_get('output_buffering')))."\n";
//ob_end_flush();
flush();
}
}
echo 'Starting…<br />';
$p = new ProgressBar();
echo '<div style="width: 300px;">';
$p->render();
echo '</div>';
for ($i = 0; $i < ($size = 100); $i++) {
$p->setProgressBarProgress($i*100/$size);
usleep(1000000*0.1);
}
$p->setProgressBarProgress(100);
echo 'Done.<br />';
?>
You can call the setProgressBarProgress function inside a while process, depending on your needs!!! It's great!.
Related
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>
I can upload the image to a new folder, but the main things is need to display it out from that folder to PDF. Then I am using FDPF, but then I get an error message when displaying:
"Uncaught Exception: FPDF error: Can't open image file: Tulips.jpg "
But when i echo the $img it display. Then i add on $img in pdf->Image($img) it wont work it appear above message error.
Here is what I have try to code htmltopdf.html
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
function ValidateSingleInput(oInput) {
if (oInput.type == "file") {
var sFileName = oInput.value;
if (sFileName.length > 0) {
var blnValid = false;
for (var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if (!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
oInput.value = "";
return false;
}
}
}
return true;
}
function handleFileSelect(event)
{
console.log(event)
var input = this;
if (input.files)
{
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++)
{
var reader = new FileReader();
console.log(reader)
reader.onload = (function (e)
{
var span = document.createElement('span');
span.innerHTML = ['<img class="thumb" src="',e.target.result, '" title="', escape(e.name), '"/><span class="remove_img_preview"></span>'].join('');
document.getElementById('preview').insertBefore(span, null);
});
reader.readAsDataURL(input.files[i]);
}
}
}
$(document).ready(function(){
// Listen to click event on the submit button
$('#submit').click(function (e) {
e.preventDefault();
var myform = document.getElementById("form");
var fd = new FormData(myform);
$.ajax({
url:"upload1.php",
type:"POST",
data:fd,
//dataType: 'json',
processData: false,
contentType: false,
cache: false,
success:function(data){
alert("Success Insert!");
},
});
});
$('#fileToUpload').change(handleFileSelect);
//preview image and remove
$('#preview').on('click', '.remove_img_preview',function ()
{
$(this).parent('span').remove();
$("#fileToUpload").val("");
});
});
</script>
<style>
div.relative {
position: relative;
top: -300px;
}
#bottom{
position: relative;
right: 0;
bottom: 0;
}
.thumb
{
width: 100px;
height: 100px;
margin: 0.2em -0.7em 0 0;
}
.remove_img_preview
{
position:relative;
top:-25px;
right:5px;
background:black;
color:white;
border-radius:50px;
font-size:0.9em;
padding: 0 0.3em 0;
text-align:center;
cursor:pointer;
}
.remove_img_preview:before
{
content: "×";
}
table,th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
textarea {
width: 100%;
height: 300px;
padding: 12px 20px;
box-sizing: border-box;
border: 2px solid #ccc;
border-radius: 4px;
background-color: #f8f8f8;
font-size: 16px;
resize:none;
}
table.menu {
border: 1px solid black;
border-collapse: collapse;
width: 10%;
float:right;
}
</style>
<body>
<form action="generate_pdf.php" method="POST" id="form">
<input type="submit" value="Send" id="submit" name="submit"><input type="reset" value="Clear">
<input type="file" name="fileToUpload[]" id="fileToUpload" onchange="ValidateSingleInput(this);" multiple = "multiple" style="display: none;">
<input type="button" value="Browse..." onclick="document.getElementById('fileToUpload').click();" />
<input type="submit" value="PDF">
<div id="preview"></div>
</form>
</body>
</html>
Here is the upload1.php
<?php
require 'config.php';
$year = date("yy");
$year = substr($year, -2);
$month = date("m");
$key = "KM".$year.$month;
$total = count($_FILES['fileToUpload']['name']);
$sql = "SELECT * FROM images WHERE id LIKE '$key%' ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
//GET NEW RUNNING NUMBER BY CHECKING DATABASE
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$number = sprintf('%03d',substr($row['id'], -3)+ 1) ;
$ans = $key.$number;
}
}
else
{
$ans = $key."001";
}
$target_dir = "D:/XAMPP/htdocs/new3/new3/uploads/" . $ans;
if(!file_exists($target_dir))
{
mkdir($target_dir,0777,true);
}
$sql = $conn->query ("INSERT INTO images (id) VALUES ('$ans')");
$allowed = array('gif', 'png', 'jpg','xlsx','pdf','doc');
$ext = pathinfo($total, PATHINFO_EXTENSION);
if (!in_array($ext, $allowed)) {
echo 'error';
}
for( $i=0 ; $i < $total ; $i++ )
{
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"][$i], $target_dir."/".$ans."-".$_FILES["fileToUpload"]["name"][$i]))
{
echo "The file ". basename( $_FILES["fileToUpload"]["name"][$i]). " has been uploaded."."<br>";
}
else
{
echo "Sorry, there was an error uploading your file.";
}
}
?>
Here is the generate_pdf.php that i have try:
<?php
$img=$_FILES["fileToUpload"]["name"][0];
echo $img;
require 'fpdf181/fpdf.php';
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',10);
$pdf->Image($img,NULL,NULL,0,0,'PNG');
$pdf->Output();
?>
I don't know whether I wrote it correctly or not? Or just need to call back the path where image is stored and display it out? Myself already brainstorming, don't know how it works. Can anyone help? Maybe this is a duplicate questions but I can't even find any related things, just can found how to retrieve from database.
First problem is that your <form> tag is missing the enctype="multipart/form-data" attribute.
As for the PHP error, $_FILES["fileToUpload"] is an array, so $image=$_FILES["fileToUpload"]["name"] should change to $_FILES["fileToUpload"]["name"][0] (assuming you want the first file). So generate_pdf.php should start with:
$image=$_FILES["fileToUpload"]["name"][0];
After i have amend some of it the error come out is "Fatal error: Uncaught Exception: FPDF error: Can't open image file"
This is the code file i have amend call generate_pdf.php
$image=$_FILES["fileToUpload"]["name"][0];
$img="C:/xampp/htdocs/test/uploads/".$image;
require 'fpdf181/fpdf.php';
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',10);
$pdf->Image($img, NULL, NULL, 0, 0, 'png');
$pdf->Output();
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!
I'm making live chatter for my project, and I need this script to recognize this:
If clientmsg is empty, it will call out an error and won't post the
message.
If clientmsg has more than 3 or 4 chars (letters) - it will post the message.
The code:
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post3.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
I can't find out how this works.
Here you can see the whole code for it.
index.php
<?php
/*****************************
File: index.php
Written by: exZerry development crew
******************************/
session_start();
if (isset($_SESSION['loggedin']) && $_SESSION['loggedin'] == true) {
echo "";
} else {
header ("Location: login.php");
}
require('includes/config.php');
echo $sOutput;
if(isset($_POST['enter'])){
if($_POST['username'] != ""){
$_SESSION['username'] = stripslashes(htmlspecialchars($_POST['username']));
}
else{
echo '<span class="error">Please type in a name</span>';
}
}
?>
<style type="text/css">
input {
font: 12px;
}
.loginbox {
background-image: url(bar.png);
width: 100%;
height: 100%;
margin-top: -38;
}
#loginform {
font:16px dinpro;
color: #ffffff;
margin-top: 100;
}
#hedthe {
background-image: url(spacer.png);
font-family: bank-gt, sans-serif;
font-size: 34;
width: 830;
height: 34;
font-weight: normal;
}
#thereis {
magrin-top: -20;
}
#chatbox {
text-align: justify;
height: 70%;
width: 100%;
overflow: auto;
opacity: 0.91;
}
#usermsg {
width: 100%;
font-family: Play, sans-serif;
font-size: 14;
font-weight: normal;
color: #ffffff;
border: 0px solid black;
text-indent: 5px;
height: 32;
margin-top: 5px;
border: 0px solid black;
color: #ffffff;
background-image: url(chatinp.png);
}
input {
opacity: 0.7;
}
#submitmsg {
background-color: #48513e;
width: 0;
height: 0;
font-size: 20;
font-weight: normal;
color: #ffffff;
text-align: left;
border: 0px solid black;
}
.error {
color: #000000;
}
#menu {
margin-right: 0;
}
.welcome {
float:left;
}
.logout {
float:right;
}
.msgln {
margin-right: 0;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="modules/chatbox.js"></script>
<!-- Actual chat -->
<div id="chatbox">
<?php
if(file_exists("tmp/log.html") && filesize("tmp/log.html") > 0){
$handle = fopen("tmp/log.html", "r");
$contents = fread($handle, filesize("tmp/log.html"));
fclose($handle);
echo $contents;
}
?>
</div>
<form name="message" action="" id="sender" class="sender">
<input name="usermsg" id="usermsg" class="required" type="text" placeholder="Your message here" maxlength="60"/>
<input name="submitmsg" type="submit" id="submitmsg" width="0" height="0"/>
</form>
chatbox.js file
// jQuery Document
$(document).ready(function(){
//If user submits the form
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
$.post("post3.php", {text: clientmsg});
$("#usermsg").attr("value", "");
return false;
});
//Load the file containing the chat log
function loadLog(){
var oldscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
$.ajax({
url: "tmp/log.html",
cache: false,
success: function(html){
$("#chatbox").html(html); //Insert chat log into the #chatbox div
var newscrollHeight = $("#chatbox").attr("scrollHeight") - 20;
if(newscrollHeight > oldscrollHeight){
$("#chatbox").animate({ scrollTop: newscrollHeight }, 'normal'); //Autoscroll to bottom of div
}
},
});
}
setInterval (loadLog, 2000); //Reload file every 3 seconds
});
post3.php file
<?
session_start();
if(isset($_SESSION['username'])){
$text = $_POST['text'];
$fp = fopen("tmp/log.html", 'a');
fwrite($fp, "<div class='msgln'> <b>".$_SESSION['username']."</b>: ".stripslashes(htmlspecialchars($text))."<br></div>");
fclose($fp);
}
?>
This is full js + php chatter.
Like this?
$("#submitmsg").click(function(){
var clientmsg = $.trim($("#usermsg").val());
if(clientmsg.length >= 3){
$.post("post3.php", {text: clientmsg});
$("#usermsg").val("");
}else{
alert('error');
}
return false;
});
$("#submitmsg").click(function(){
var clientmsg = $("#usermsg").val();
// check if the length of the string is greater than 3 letters
if(clientmsg.length > 3)
$.post("post3.php", {text: clientmsg});
else
alert("Error");
$("#usermsg").attr("value", "");
return false;
});
I created a custom gallery and it works perfectly in internet explorer however in firefox and chrome it doesn't work like it should. The lightbox doesn't pop up on the clicking the thumbnail link, you have to click it twice, when clicked once the backdrop comes up but not the lightbox, but then on clicking the thumbnail twice it centers and pops up. And I have no clue why, please help.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Album</title>
<script type="text/javascript" src="hftpnyc/js/jquery-1.7.1.min.js"></script>
<link href="albums.css" rel="stylesheet" type="text/css" media="screen"/>
<link href="Website/print.css" rel="stylesheet" type="text/css" media="print"/>
<style type="text/css">
body {
}
.backdrop
{ position:fixed;
top:0px;
left:0px;
width:100%;
height:100%;
background:black;
z-index:50;
display:none;
}
.smllpic a {text-decoration:none;}
.box
{margin:auto;
clear:both;
position:fixed;
max-height:705px;
max-width:905px;
background:black;
z-index:52;
padding:0px;
border:black 1.2px solid;
overflow:hidden;
}
.close
{
position:absolute;
right:6px;
margin-top:3px;
cursor:pointer;
font-size:20px;
font-family:acens;
font-weight:700px;
font-stretch:narrower;
opacity: .3;
}
.smllpic img{cursor:pointer; opacity:0.7; filter:progid:DXImageTransform.Microsoft.Alpha(opacity=70); };
}
</style>
</head>
<body>
<div id="contentcontainer" style="width:100%;clear:both;">
<div id="wrapper" style="width:981px; height:100%; margin:0px auto;">
<div style="margin:0px auto;width:979px;">
<h2 style="font-family:Tahoma, Geneva, sans-serif; color:#333;border-bottom:#A3308E solid 1px; background-color: #E6E6E6;"> Album </h2> </div>
<div style="float:right; margin-right:3px;">
<form action="" method="post">
<a href="Albums.php">
<input type="button" name="Uploadmre" value="Upload more" style="border: 1px solid #d0ccc9;right:0px;background: #fff;color: #5f95ef;font-size: 11px;font-weight: 700;height:22px; margin-right:7px;">
</a>
</form>
</div>
<div id="page-wrap" style=" width:918px; margin: 0px auto;clear:both;">
<?php
error_reporting(0);
/* function: returns files from dir */
function get_files($images_dir,$exts = array('jpeg','gif','png','jpg')) {
$files = array();
if($handle = opendir($images_dir)) {
while(false !== ($file = readdir($handle))) {
$extension = strtolower(get_file_extension($file));
if($extension && in_array($extension,$exts)) {
$files[] = $file;
}
}
closedir($handle);
}
return $files;
}
/* function: returns a file's extension */
function get_file_extension($file_name) {
return substr(strrchr($file_name,'.'),1);
}
$images_dir = 'hftpnyc/thumbs/';
$thumbs_dir = 'hftpnyc/thumbs/thumbnails/';
$thumbs_width = 100;
$images_per_row = 11;
$string = "";
/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
$index++;
$thumbnail_image = $thumbs_dir.$file;
//if(!file_exists($thumbnail_image)) {
//$extension = get_file_extension($thumbnail_image);
//if($extension) {
//make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
//}
//}
error_reporting(0);
echo '<div class="smllpic" style=" padding: 0px; margin: 0px; border: 1px solid black; display: block; width: 100px; height:100px; float: left; "> <img id="thumbs" src="',$thumbnail_image,'" width="100px"/></div>';
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
}
}
else {
echo '<p>There are no images in this gallery.</p>';
}
?>
</div>
</div>
</div>
<script type="text/javascript">
$(document).height();
$('.backdrop').height($(document).height());
$(document).ready(function(){
$('.smllpic img').hover(function () {
var $this = $(this);
$this.stop().animate({'opacity':'1.0'},200);
},function () {
var $this = $(this);
$this.stop().animate({'opacity':'0.7'},200);
});});
$(window).bind("load", function() {
var preload = new Array();
$(".box").each(function() {
s = $(this).attr("src").replace(/\.(.+)$/i, "_on.$1");
preload.push(s)
});
var img = document.createElement('img');
$(img).bind('load', function() {
if(preload[0]) {
this.src = preload.shift();
}
}).trigger('load');
});
$(document).ready(function(){
function centreit(){
//get the height and width of the modal
var modal_height = $('.box').height();
var modal_width = $('.box').width();
//get the height and width of the page
var window_width = $(window).width();
var window_height = $(window).height();
//calculate top and left offset needed for centering
var topp = (window_height - modal_height)/2;
var left = (window_width - modal_width)/2;
//apply new top and left css values
$('.box').css({'top' : topp+'px' , 'left' : left+'px', 'right': left+'px','bottom':topp+'px'}); };
$('.lightbox').click(function(e) {
e.preventDefault(); // keeps new page from loading
var thisPicture = $(this).attr('href'); // path to full sized picture,
function getit(){
$('body').append('<div class="backdrop" label="click to close"></div><div class="box" id="centre" ><div class="close">x</div><div style="cursor:pointer; opacity:1;font-family:Agency FB;margin-top:50%; right:-20px;position:fixed;color:white;font-size:50px; z-index:50;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;-moz-box-shadow:0px 0px 5px #444444;-webkit-box-shadow:0px 0px 5px #444444;box-shadow:0px 0px 5px #444444;">></div><div style="cursor:pointer; opacity:.35;font-family:Agency FB;margin-top:50%; left:-20px; position:absolute; font-size:50px;color:white; z-index:70;-webkit-border-radius:5px;-moz-border-radius: 5px; border-radius:5px;-moz-box-shadow:0px 0px 5px #444444; -webkit-box-shadow:0px 0px 5px #444444; box-shadow:0px 0px 5px #444444;"><</div><img class="motown" src="'+thisPicture+'" style="max-height:705px;max-width:905px;z-index:50;"/></div>');
};
$(window).resize(function(){
$('.box').resize();
$('.motown').resize();
centreit();
});
getit();
centreit();
$("html").css("overflow", "hidden");
$('.backdrop').fadeTo(500,0.9);
$('.box').children().fadeIn(1000);
//$('.backdrop').css({ 'display' : 'block', opacity : 0});
$('.close').click(function(){
close_box();});
$('.backdrop').click(function(){
close_box();});
function close_box(){
$('.backdrop').remove();
$('.box').remove();
$("html").css("overflow", "");};
});});
</script>
</body>
</html>
You should try:
margin: 0 auto 0;
left: 0;
right: 0;
To fix the centering. So that would leave you with:
.box
{
margin:0 auto 0;
left: 0;
right: 0;
clear:both;
position:fixed;
max-height:705px;
max-width:905px;
background:black;
z-index:52;
padding:0px;
border:black 1.2px solid;
overflow:hidden;
}