Keeping Uploaded Images On Page After Refresh (PHP/HTML/JAVASCRIPT) - javascript

I'm doing a small project where I'm trying to create a continual gallery for a user; whereby, they upload a file, and it immediately appears on the same page. The one thing I can't manage to accomplish is to keep the files there on the page even if the page is refreshed. In other words, I want the user to return and see all of their uploaded files as if they never left, until they close the browser. I've tried using cookies and session variables but I'm confused on how to implement this. Here is my Code. I APOLOGIZE IN ADVANCE FOR BAD INDENTATION.
My index.php:
<?php
// Process image
$uploadName = 'uploaded/pic.jpg';
if (count($_FILES))
move_uploaded_file($_FILES['image']['tmp_name'], $uploadName);
?>
<!DOCTYPE html>
<html>
<head>
<style>
li { display: inline-block; padding: 200px; width: 200px;}
img { width: 100%; height:100%;}
</style>
<script type="text/javascript">
function iframeSubmit(formElem, action, callback) {
// name a callback that will be called from inside the iframe
var callbackName = 'iframe' + Math.ceil(Math.random() * 10000);
action = action + (action.indexOf('?') == -1 ? '?' : '&') + 'callback='+
callbackName;
// create an iframe and use the callback as its name
var iframe = document.createElement('iframe');
iframe.setAttribute('name', callbackName);
iframe.style.display = 'none';
// add the target and edit the action of the form
formElem.setAttribute('target', callbackName);
formElem.setAttribute('action', action);
// add the hidden iframe after the form
formElem.parentNode.appendChild(iframe);
window[callbackName] = callback;
}
;
</script>
</head>
<body onload="onload()">
Home
Schedule
<form method="post" action="index.php" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" value="upload"/>
</form>
<ul>
<?php if (count($_FILES)): ?>
<li><img src="<?php echo $uploadName ?>"/></li>
<?php endif; ?>
</ul>
<script type="text/javascript">
function onload() {
}
</script>
<script type="text/javascript">
function processResponse(response) {
if (!response.success) {
alert('woopsie');
return;
}
var newListItem = document.createElement('li');
newListItem.innerHTML = '<img src="' + response.path + '"/>';
document.getElementsByTagName('ul')[0].appendChild(newListItem);
}
function onload() {
iframeSubmit(document.getElementsByTagName('form')[0], 'upload.php',
processResponse);
}
</script>
</body>
</html>
Here is my upload.php:
<?php
enter code here
$imagePath = 'uploaded/pic.jpg';
setcookie("cookie", "stuff", time() + 3600, $uploadName);
move_uploaded_file($_FILES['image']['tmp_name'], $imagePath);
?>
<!DOCTYPE html>
<html>
<head>Iframe content</head>
<body>
<script type="text/javascript">
<?php
echo 'window.parent[\'' . $_GET['callback'] . '\']('
. json_encode(array('success' => true, 'path' => $imagePath)) . ')';
?>
</script>
</body>
</html>

Related

I'm getting corrupted image when converting base64 image using webcam.js

here's my html with javascript using webcam.js. I just followed the https://github.com/jhuckaby/webcamjs on how you will implement it using existing form.
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>WebcamJS Test Page</title>
<style type="text/css">
body { font-family: Helvetica, sans-serif; }
h2, h3 { margin-top:0; }
form { margin-top: 15px; }
form > input { margin-right: 15px; }
#results { float:right; margin:20px; padding:20px; border:1px solid; background:#ccc; }
</style>
</head>
<body>
<div id="results">Your captured image will appear here...</div>
<h1>WebcamJS Test Page</h1>
<h3>Demonstrates simple 320x240 capture & display</h3>
<div id="my_camera"></div>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="../webcam.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
Webcam.snap( function(data_uri) {
var raw_image_data = data_uri.replace(/^data\:image\/\w+\;base64\,/, '');
document.getElementById('mydata').value = raw_image_data;
document.getElementById('myform').submit();
} );
</script>
<!-- A button for taking snaps -->
<form id="myform" method="post" action="myscript.php">
<input id="mydata" type="hidden" name="mydata" value=""/>
<input type=button value="Take Snapshot" onClick="take_snapshot()">
<input type="submit" value="submit">
</form>
<!-- Code to handle taking the snapshot and displaying it locally -->
<script language="JavaScript">
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
} );
}
</script>
here's the myscript.php to save the image. I successfully save the PATH in the database but I'm getting a corrupted .jpg file (file size always in 7 bytes).
<?php
include 'connect.php';
$encoded_data = $_POST['mydata']; // to get the base 64 code image link
$name = base64_decode($encoded_data); // to convert base 64 code
$name = date('YmdHis');
$newname="images/".$name.".jpg";
$file = file_put_contents( $newname, file_get_contents('php://input') );
if (!$file) {
print "Error occured here";
exit();
}
else
{
$sql="INSERT INTO image (images) VALUES('$newname')";
$result=mysqli_query($con,$sql);
$value=mysqli_insert_id($con);
$_SESSION["myvalue"]=$value;
}
$url = 'http://' . $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']) . '/' . $newname;
print "$url\n";
?>
After all the trail and errors i found out you'll need to convert the base64 string to a blob and then attach to a file before sending.
var binaryImg = atob(base64string);
var length = binaryImg.length;
var ab = new ArrayBuffer(length);
var ua = new Uint8Array(ab);
for (var i = 0; i < length; i++) {
ua[i] = binaryImg.charCodeAt(i);
}
var blob = new Blob([ab], {
type: "image/jpeg"
});enter code here
var imgFile = new File([blob], 'photo.jpeg', {type: 'image/jpeg'});
Now you can use the imgFile to send across to a remote server.

How to store captured image path in mysql database using php.?

I want to capture image from webcam user image that image stored in specified folder and captured image path store into mysql using php. I have an problem with webcam captured image path is not stored in mysql database. so please help me...
<script src="webscript.js"></script>
<!-- First, include the Webcam.js JavaScript Library -->
<script type="text/javascript" src="webcam.min.js"></script>
<script type="text/javascript" src="script.js"></script>
<!-- Configure a few settings and attach camera -->
<script language="JavaScript">
Webcam.set({
width: 320,
height: 240,
image_format: 'jpeg',
jpeg_quality: 90
});
Webcam.attach( '#my_camera' );
var shutter = new Audio();
shutter.autoplay = false;
shutter.src = navigator.userAgent.match(/Firefox/) ? 'shutter.ogg' : 'shutter.mp3';
function take_snapshot() {
// take snapshot and get image data
Webcam.snap( function(data_uri) {
// display results in page
document.getElementById('results').innerHTML =
'<h2>Here is your image:</h2>' +
'<img src="'+data_uri+'"/>';
Webcam.upload( data_uri, 'upload.php', function(code, text) {
alert(data_uri);
});
} );
}
</script>
<?php
include 'connection.php';
// be aware of file / directory permissions on your server
$newname = move_uploaded_file($_FILES['webcam']['tmp_name'], 'uploads/webcam'.date('YmdHis').rand(383,1000).'.jpg');
$query = "INSERT INTO entry(name) VALUES('".$_GET['url']."')";
mysql_query($query)or die(mysql_error());
echo "<script>alert('successfully..');</script>";
?>
<!DOCTYPE html>
<html>
<head>
<title>Javascript Webcam</title>
<link href="font-awesome.min.css" rel="stylesheet"/>
<link href="bootstrap.min.css" rel="stylesheet"/>
</head>
<body>
<center>
<div class="row">
<div class="col-md-6">
<h3>Profile Picture</h3>
<div id="my_camera"></div>
<!-- A button for taking snaps -->
<form>
<input type=button class="btn btn-success" value="Take Snapshot" onClick="take_snapshot()">
</form>
<div id="results" class="well">Your captured image will appear here...</div>
</div>
</div>
</center>
</body>
</html>
Assuming $mysqli is a successfully connected [new Mysqli] object.
$query = "SELECT * FROM 'database.table' WHERE 'somecolumn'='someval' LIMIT= 5";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($name, $code);
/* fetch values */
while ($stmt->fetch()) {
printf ("%s (%s)\n", $name, $code);
}
/* close statement */
$stmt->close();

repeatedly poll database for pages, then output pages in sequence with slide effect

I have a client who needs to output pages that are referenced by ID in a database. The pages must be output one after another (like a slide show), and there must be a slider transition effect. To make it "fun", the database will be changing as new pages are added, so a portion of the script to do all this must be run repeatedly to check the database.
I've got the pages to load, and I've got the transition working. The problem is, I can't get the polling to work because there's such a mess. That is, if I add a new page, I must manually reload the script - I need the script to detect new pages added to the database. I know that all I really need to do is just re-run the database query to generate the array, but with all the other stuff going on, I'm lost. I've tried setInterval() and even a while loop to no avail. At this point I'm sure I'm just missing something (hopefully) trivial, so I humbly ask for help. My code is VERY sloppy as I test, but here it is:
<?php
$community_id = 89;
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
<?php
$con=mysqli_connect("localhost","username","password","db_name");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// get all the pages that pertain to the community
$uid_query = "SELECT uid FROM pages WHERE pid=" . $community_id;
// build the javascript array by grabbing all results from above query
$result = mysqli_query($con,$uid_query);
$counter = 0;
$baseURL = "http://www.website.com/index.php?id=";
echo "var frames = new Array;";
while($row = mysqli_fetch_array($result)) {
echo "frames[" . $counter . "]='" . $baseURL . $row['uid'] . "';";
$counter++;
echo "frames[" . $counter . "] = 5;";
$counter++;
}
mysqli_close($con);
?>
var i = 0, len = frames.length;
function ChangeSrc()
{
if (i >= len) { i = 0; } // start over
document.getElementById('frame').src = frames[i++];
setTimeout('ChangeSrc()', (frames[i++]*1000));
}
window.onload = ChangeSrc;
</script>
<style type="text/css">
body, html
{
margin: 0; padding: 0; height: 100%; overflow: hidden;
}
#iframe_container
{
position:absolute; left: 0; right: 0; bottom: 0; top: 0px;
}
</style>
</head>
<body>
<div id="iframe_container">
<iframe src="" name="frame" id="frame" width="100%" height="100%" frameborder="0"></iframe>
</div>
</body>
</html>
... and then any given page looks like this:
javascript:
$(document).ready(function(){
$('.hidden').slideDown(1000);
});
css:
.hidden{
display:none;
}
html:
<div class="hidden">
CONTENT GOES HERE
</div>

switch pages using AJAX PHP

Good day all, I'm working on a jquery game and I'm making a welcome screen. I'm using ajax to switch pages. So far the pages are switching exactly but the page index.php where game's elements are running has stopped working and no animation is working. Here are the codes:
welcome.php script:
<head>
<script src="js/jquery-1.9.1.min.js"></script>
<script>
function swapContent(cv) {
var url = "page-switch.php";
$.post(url, {contentVar: cv} ,function(data) {
$("#myDiv").html(data).show();
});
}
</script>
</head>
<body>
Play!
Scoreboard
<div id="myDiv"></div>
</body>
page-switch.php script:
<?php
$contentVar = $_POST['contentVar'];
if ($contentVar == "con1") {
header('Location: index.php');
} else if ($contentVar == "con2") {
header('Location: score-post.php');
}
?>
index.php script:
<head>
<title>Space Game Test 01</title>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/jquery-collision.js"></script>
<script src="js/core-animation.js"></script>
<link rel="stylesheet" href="css/jquery-ui.css">
<link rel="stylesheet" href="css/content-style.css">
</head>
<body onload="start()">
<div id="content">
<div id="galaxy"><img src="images/galaxy.png" /><img src="images/galaxy.png" /></div>
</div>
<div id="linkpanel"></div>
<div id="scoreboard">Score<br><div id="score">0</div><input type="button" id="pause" value="Pause" /><br>
<input type="button" id="resume" value="Resume" /></div>
<script>
var pause = null;
$("#resume").click(function () {
if(!pause)
{
pause = setInterval(scroll_ns, 50)
}
});
$("#pause").click(function () {
clearInterval(pause);
pause = null;
});
</script>
</body>
Am I doing wrong here? I'm pretty noob in ajax but I really need to learn. Please help! Tnx.
you can use load function also
<script>
function swapContent(page) {
jQuery( "#myDiv" ).load(page);
}
</script>
Play!
Scoreboard
<div id="myDiv"></div>
You may try something like this you have to redirect to the page after getting response from ajax.
<script>
function swapContent(cv) {
var url = "page-switch.php";
$.post(url, {contentVar: cv} ,function(data) {
//alert(data)
if(data="first"){
window.location.href = "index.php";
}
if(data="second"){
window.location.href = "score.php";
}
});
}
</script>
</head>
<body>
Play!
Scoreboard
<div id="myDiv"></div>
</body>
page-switch.php script:
<?php
$contentVar = $_POST['contentVar'];
if ($contentVar == "con1") {
echo "first";
} else if ($contentVar == "con2") {
echo "second";
}
?>

refreshing a <div> with ajax but passing along a counter variable

I have two .php files. The first one ajax_testing.php looks like this:
<!DOCTYPE html>
<html>
<?php
$index_local=1;
$_SESSION['global_index'] = $index_local;
?>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body>
<div id="main">Who is batman? click count=<?echo $_SESSION['global_index'] ?>
<button id="detailed">LINK</button>
</div>
</body>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait till page is loaded
$("button").click(function(){
<?php
$_SESSION['global_index']+=1;
?>
$('#main').load('property-detailed.php?global_index='
+ <?php echo $_SESSION['global_index']; ?>
+ ' #main', function() {});
});
}); //// End of Wait till page is loaded
</script>
</html>
Document number two is called property-detailed.php and looks like this:
<!DOCTYPE html>
<html>
<?php
$_SESSION['global_index'] = $_GET['global_index'];
?>
<head>
<script></script>
</head>
<body>
<div id="main">Who is batman? click count=<?php echo $_SESSION['global_index']; ?>
<button id="detailed">LINK</button>
</div>
</body>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait til page is loaded
$("button").click(function(){
<?php
$_SESSION['global_index']+=1;
?>
$('#main').load('property-detailed.php?global_index='
+ <?echo $_SESSION['global_index'] ?>
+ ' #main', function() {});
});
}); //// End of Wait till page is loaded
</script>
</html>
I load the first page, and it has a variable, $global_index, that is set to 1 and a button with an ajax command to reload the div with the new information found on the second page.
My goal is to have the variable $global_index carry over and increment each time I press the button. Is this possible with only ajax being implemented? If so, is there a way to make it happen with only the first page? Otherwise would it just be easier to have my database keep track of this number and increment that?
In your ajax_testing.php:
<?php session_start(); ?>
<script type="text/javascript" src="jquery.js"></script>
<?php
$_SESSION['counter'] = 1;
$count = $_SESSION['counter'];
?>
<div id="main">Batman<?php echo $count; ?></div>
<button id="detailed">Link</button>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','#detailed',function(){
var count = "<?php echo $count; ?>",
dataString = "counter=" + count;
$.ajax({
type: "POST",
url: "property-detaild.php",
data:dataString,
success:function(data){
$('#main').html(data);
console.log(data);
}
});
})
});
</script>
And in your property-detailed.php:
<?php
session_start();
$_SESSION['counter'] = $_SESSION['counter']+1;
echo $_SESSION['counter'];
?>

Categories