Can't retrieve variable from php - php

PHP FILE:
<?php
#Communication with the API
require_once 'api.php';
$cloudkey = new CloudKey($user_id, $api_key);
if(isset($_FILES["FileInput"]) && $_FILES["FileInput"]["error"]== UPLOAD_ERR_OK)
{
//Deleted Code: putting the uploaded files in my server.
if(move_uploaded_file($_FILES['FileInput']['tmp_name'], $UploadDirectory.$NewFileName ))
{
$video_file = "/home/george/public_html/q/";
$video_file = $video_file . $NewFileName;
#Sending the video from my server to the cloud server
$res = $cloudkey->file->upload_file($video_file);
#The cloud server will create a link
$source_url = $res->url;
#The cloud server will convert the video very fastly
while(1) {
#Deleted Code: Conversion
if ($asset->status == 'ready') {
# A lot of code. It will convert the videos here and if it succeeds it will stop.
break;
# If the conversion fails, display error
} else if ($asset->status == 'error') {
echo "Error while transcoding the media\n";
}
sleep(1);
}
# Getting the URL of a thumbnail
echo $thumb = $cloudkey->media->get_stream_url(array('id' => $media_id, 'asset_name' => 'jpeg_thumbnail_source'));
}else{
die('error uploading File!');
}
}
else
{
die('Something went wrong!');
}
?>
HTML FILE:
{literal}
<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#output', // target element(s) to be updated with server response
beforeSubmit: beforeSubmit, // pre-submit callback
success: afterSuccess, // post-submit callback
uploadProgress: OnProgress, //upload progress callback
resetForm: true // reset the form after successful submit
};
//function after succesful file upload (when server response)
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
}
//progress bar function
function OnProgress(event, position, total, percentComplete)
{
//DOES NOT INTEREST YOU
});
</script>
{/literal}
<div id="output"></div>
I am using smarty template engine. I have an html upload form that will communicate with a php file progressupload.php where the php file will convert the video (using API services) and brings back a response when it finishes.
When the user uploads the video file, ajax will take over show the percentage (in html), and it will send the file to progressupload.php and when the progressupload.php finishes the conversion it will output everything echoed in the php by simply putting this in the html file (I don't know why): <div id="output"></div>.
WHAT I WANT:
When progressupload.php finishes the conversion, it will generate a thumbnail (screenshot) and store its link in $thumb. I want to retrieve $thumb and show it to the user using jquery.
Now if you look at the HTML Code, afterSuccess() is the function where I want to show the thumbnail to the user:
function afterSuccess()
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO SHOW THE THUMBNAIL HERE.
}
I deleted a lot of unnecessary code that could've distracted you. Remember that I am using smarty template engine, my html file does not end with .php, I cannot echo the variable directly. How can I retrieve the php variable and put it in a jquery method after the variable is created.
I have a suspicion that if you retrieve the variable directly on page load, it will not succeed in getting $thumb since the link needs time to be created (uploading, conversion). How can I retrieve that $thumb?

Assuming that you are using jQuery.ajax();
First parameter in the $.ajax 'success' callback is what returned from the server side.
function afterSuccess( response /** this is what returned from your server **/ )
{
$('#loading-img').hide(); //hide submit button
$('#progressbox').fadeOut(); //hide progress bar
//I WANT TO INSERT SOMETHING HERE.
console.log(response); // here you can access your $thumbnail
// below code is untested but it should work
// $("#output").html("<img src='"+response+"' class='thumbnail' />");
}

Related

Save images in XAMPP server from Cordova with PHP

My requirement is to save the images taken from Camera of Cordova plugin and save the image in a server . I have used below code and achieved getting the image , but how do i save in a server using PHP
// Code to capture photo from camera and show gps co ordinates
<!DOCTYPE html>
<html>
<head>
<title>Capture Photo</title>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script type="text/javascript" charset="utf-8">
var pictureSource; // picture source
var destinationType; // sets the format of returned value
// Wait for device API libraries to load
document.addEventListener("deviceready",onDeviceReady,false);
// device APIs are available
function onDeviceReady() {
pictureSource=navigator.camera.PictureSourceType;
destinationType=navigator.camera.DestinationType;
}
// Called when a photo is successfully retrieved
//
function onPhotoDataSuccess(imageData) {
// Uncomment to view the base64-encoded image data
// console.log(imageData);
// Get image handle
//
var smallImage = document.getElementById('smallImage');
// Unhide image elements
//
smallImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
smallImage.src = "data:image/jpeg;base64," + imageData;
}
// Called when a photo is successfully retrieved
//
function onPhotoURISuccess(imageURI) {
// Uncomment to view the image file URI
// console.log(imageURI);
// Get image handle
//
var largeImage = document.getElementById('largeImage');
// Unhide image elements
//
largeImage.style.display = 'block';
// Show the captured photo
// The in-line CSS rules are used to resize the image
//
largeImage.src = imageURI;
}
// A button will call this function
//
function capturePhoto() {
// Take picture using device camera and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 50,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function capturePhotoEdit() {
// Take picture using device camera, allow edit, and retrieve image as base64-encoded string
navigator.camera.getPicture(onPhotoDataSuccess, onFail, { quality: 20, allowEdit: true,
destinationType: destinationType.DATA_URL });
}
// A button will call this function
//
function getPhoto(source) {
// Retrieve image file location from specified source
navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50,
destinationType: destinationType.FILE_URI,
sourceType: source });
}
// Called if something bad happens.
//
function onFail(message) {
alert('Failed because: ' + message);
}
</script>
</head>
<body>
// button to capture photo
<button onclick="capturePhoto();">Capture Photo</button> <br>
// button to capture editable photo
<button onclick="capturePhotoEdit();">Capture Editable Photo</button> <br>
//button to select images from library
<button onclick="getPhoto(pictureSource.PHOTOLIBRARY);">From Photo Library</button><br>
<button onclick="getPhoto(pictureSource.SAVEDPHOTOALBUM);">From Photo Album</button><br>
<img style="display:none;width:60px;height:60px;" id="smallImage" src="" />
<img style="display:none;" id="largeImage" src="" />
</body>
</html>
PHP Code (upload.php):
<?php
print_r($_FILES);
move_uploaded_file($_FILES["file"]["tmp_name"], "192.168.3.153/uploads/".$_FILES["file"]["name"]);
?>
The only way to do this is to get the image as a Base64 encoded string, send that back to the server and then save it into the DB, either in encoded form, or decode it and then save it as a file on the server or a blob in a database.
I don't know the exact implementation procedure as I'm not a Cordova dev, I just sit next to one at work who was tearing his hair out over something similar recently.
In cordova we have plugin file transfer which is used to download / upload files from server. You have to use this plugin to upload image taken from camera.
Check following link that details how to upload file to server
Following is a Javascript function that picks a file stored in mobile device and send it to server
function uploadfiletoserver(filename){ // where filename is the file store in device
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
//The folder is created if doesn't exist
fileSys.root.getDirectory( 'APP STORAGE FOLDER', {create:true, exclusive: false},
function(directory) {
//find the file
directory.getFile(filename, {create: false, exclusive: false},
function(file){
var imageURI = file.toInternalURL();
var options = new FileUploadOptions();
options.fileKey = "uploadfile"; //this is the value use to refer the file uploaded to server e.g. $_FILES['uploadfile']
options.fileName = file.name;
var ft = new FileTransfer();
ft.upload(imageURI, encodeURI('http://www.yourdomain.com/upload.php'), function (r) {
console.log("Code = " + r.responseCode);
console.log("Response = " + r.response);
console.log("Sent = " + r.bytesSent);
}, function (error) {
console.log("upload error source " + error.source);
console.log("upload error target " + error.target);
}, options);
console.log("upload file: "+imageURI);
},
function(error){
console.log("Error "+error);
}
);
},
resOnError);
},
resOnError);
}
In server PHP file,
<?php
$tmpName = $_FILES['uploadfile']['tmp_name'];
$fileName = $_FILES['uploadfile']['name'];
$fileDestPath = 'YOUR_UPLOAD_FOLDER_IN_SERVER'.$fileName;
if($tmpName != 'none') {
move_uploaded_file($tmpName, $fileDestPath);
}
?>

jquery AJAX function issue

I'm trying to run a function that executes a spinner while a PHP script is loading and also refreshes a PHP file that counts the number of rows inserted to show the script's progress.
This is what I have so far:
<script type="text/javascript" language="javascript">
// start spinner on button click
$(document).ajaxSend(function(spinner) {
$("#spinner").show();
});
// refresh progress script and output to #content div
function updateProgress(){
$('#content').load('progress.php');
}
myTimer = setInterval( "updateProgress()", 2000 );
// Execute the primary function
$(document).ready(function() {
$("#driver").click(function(event){
$('#stage').load('execute.php');
});
});
// hide spinner and content div when finished
$(document).ajaxStop(function(spinner) {
clearInterval(myTimer);
$("#spinner").fadeOut("fast");
$("#content").fadeOut("fast");
});
</script>
Right now the updateProgress() function starts after the first interval is over even if the button hasn't been pushed, so I'm assuming I have to tie it in with the spinner function but I'm just not entirely sure how to make that work.
EDIT: Here's the HTML that displays the button and the div's:
<div id="stage">
Click to Import New Data into AssetData Table
<p>
<div id="spinner"><img src="/images/spinner.gif" alt="Loading..."></div>
<div id="content"></div>
<p>
<input type="button" id="driver" value="Load Data" onClick="this.disabled=true;"></div>
You need:
Load page with button. When you push button file execute.php should upload.
After user push button, spinner appearing and browser starts make ajax request to progress.php.
When execute.php uploaded, spinner disappears, progress results disappears.
jQuery code below doing this:
var myTimer;
$(document).ready(function () {
// Execute the primary function
$("#driver").click(function (event) {
$.ajax({
url: 'http://api.openweathermap.org/data/2.5/forecast?lat=35&lon=139',
success: function (data) {
//$("#someField").html(data); // you put result of executting `execute.php` into #someField field by uncommenting this string
$("#spinner").toggle();
$("#content").fadeOut("fast");
clearInterval(myTimer);
},
error: function (bob) {
// show error
console.log('get error');
clearInterval(myTimer);
},
beforeSend: function () {
myTimer = setInterval(function () {
/* // uncomment this when you will use it with real files and server
$.ajax({
url: 'progress.php',
success: function (data) {
$("#content").html(data);
}
});
*/
$("#content").append("progress data<br>");
console.log('progress executed');
}, 1); // change delay, when you work with real files and server
$("#spinner").toggle();
console.log('ajaxSend handler executed');
}
});
console.log('main function executed');
});
});
Look this example (this example for code above), please.
Now, this code do all what you need. Right?
Don't forget to uncomment some lines (ajax requests), change intervals, remove debug outputs (line 29, for example) etc.
Notice (and change it, when you will use my code) url field of execute.php ajax-requst. I had used weather api (just for example, you musth change it to progress.php because download this data takes some time, so you can see results. Remove weather url and put url to progress.php.
Also, you can check this example. Code is tided up and this version allows to load file and after that load another. And after that load another. + now myTimer+setInterval+function progress synergizes better, I suppose.
Hope, this will help you.

TCPDF Progress Bar

I am using php and TCPDF to generate a custom PDF file from several MySQL queries. Once the user clicks the "Generate PDF" button a new tab opens and the PDF process starts. It takes, on average, about 10 seconds to build the PDF. Once the file is ready the browser closes the blank page and displays the save as dialog window.
I'd like to display some type of message to the user while the PDF is creating. I am somewhat of a noob when it comes to AJAX/JQUERY, but have tried to implement several solutions without success.
Things to note:
The backend is Joomla!
Using $pdf->Output('example.pdf','D') to generate the pdf
Using ob_end_clean prior to $pdf-Output to avoid the "TCPDF: Data already output" error.
I have tried the method that adds a <div> to the end of my page as well as some jQuery/CSS that would show an animated gif while the page is loading. It did not work, and I somehow get the feeling this is either caused by the ob_end_clean or the Joomla! framework.
1) for progress bar you must run the script via ajax
2)you have pdf page count...on each page creating you can change progress bar value
3)you must use php output control function for each pages of pdf created
php have a list of good function for this
i dont see your code but you must do some thing like this
$i = 1;
while($i< PDF_PAGE_COUNT){
ob_start();
pdf_create_page($i);
echo $i/PDF_PAGE_COUNT;
ob_flush();
flush();
$i++;
}
p.s : for better answer please paste your code here!
$(document).ready(function(){
$("#PDF").click(function(){
/*-------------- validate filters -------------------------------*/
if(!(validarFecha(fecha_ymd(rj.Get('#TxtFechaIni').value())))){Warn2.show();return false; }
if(!(validarFecha(fecha_ymd(rj.Get('#TxtFechaFin').value())))){Warn3.show();return false; }
if(Date.parse(fecha_ymd(rj.Get('#TxtFechaIni').value()))>=Date.parse(fecha_ymd(rj.Get('#TxtFechaFin').value()))){Warn.show();return false; }
/* is alll right */
else {
/* show a message while generating report*/
WinSnd.Message({type:'info', title:'generating report', value:'Please, wait ...', buttons:' '}).show();
/* url with params to send */
var url="report.php?&slash="+'<?php echo(isset($_POST['slash'])?#$_POST['slash']:#$_GET['slash']);?>'+"&module="+'<?php echo (isset($_POST['module'])?#$_POST['module']:#$_GET['module']);?>'
+"&TxtCheck=excel"
+"&TxtFechaIni="+rj.Get('#TxtFechaIni').value()
+"&TxtFechaFin="+rj.Get('#TxtFechaFin').value()
+"&LkpTdoc="+rj.Get('#LkpTdoc').value();
var filename = <?php echo '"'.$gSave.'"';?>; /* name for report, i set*/
var xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.onload = function(){
WinSnd.hide(); /* hide message */
var a = document.createElement('a');
a.href = window.URL.createObjectURL(xhr.response); // xhr.response es un blob file
a.target = '_blank';
a.download = filename; // file name
a.style.display = 'none';
document.body.appendChild(a);
a.click(); // action
delete a; //
};
xhr.open('GET', url);
xhr.send();
}// fin validaciones
});//fin function
});// fin

Jquery upload function doesn't work for multiple images on 1 page

How it works:
I'm trying to create an instant upload function with Jquery/Ajax. When a user double-clicks an image, a Fancybox shows up with the upload field. After choosing an image, the image is uploaded and the source of the clicked image is changed immediately.
The problem:
When having multiple images on one page, sometimes another image gets replaced by the new image (randomly).
The code:
function uploader(thumb) {
new AjaxUpload('imageUpload', {
action: 'uploader.php',
name: 'file',
onComplete: function(file, response) {
thumb.attr('src', response);
$.fancybox.close();
}
});
}
$("img").dblclick(function(){
var img = $(this);
$.fancybox({
href: '#imageUpload',
overlayShow: true
});
uploader(img);
return false;
});
What I've tried:
When I alert the ID of the image that should be replaced, it always alerts the correct ID of the image. And still it replaces another image instead.
Regards,
Bo
The way you're getting a reference to the clicked image is not good. You should extract the clicked element from the event object passed to the handler.
$('img').dblclick(function(event) {
var img = $(event.target);
...
});

HTML5 drag and drop question

I'm trying to implement HTML5 drag and drop to upload a file. When the file is dropped, I want to call the php file to handle the dropped file. How can I call the php file and access the dragged file in php file. Also, I want to send the success or error message back from php file.
I'm unable to figure out how can I post the file to php and get the response from there.
My code so far is:
function drop(evt) {
evt.stopPropagation();
evt.preventDefault();
var files = evt.dataTransfer.files;
handleFiles(files);
}
function handleFiles(files) {
var file = files[0];
var reader = new FileReader();
reader.onload = uploadFile; //main function
reader.onloadend = uploadComplete;
reader.readAsDataURL(file);
}
function uploadFile(evt)
{
//call upload.php
//get success msg or error msg
//alert(success) or alert(error)
}
Here's example upload.php file:
<?php
$dropped_file //how to get the file
if (filesize($dropped_file) > 1024)
{
echo "size error" //how to send this error
}
else
{
echo "success" //how to send this success msg.
}
?>
This should help - http://www.thebuzzmedia.com/html5-drag-and-drop-and-file-api-tutorial/
You can use jQuery, upon the drop callback perform an AJAX call.
$("body").droppable({
accept: "img", //Your element type goes here e.g. img
drop: function(event, ui){
//Perform an AJAX call here. You can access the current dropped item through
//ui.draggable
}
)}
Use jQuery UI will give you the ability to drag and drop in the most easy way

Categories