UPDATE CODE BELOW
I found some code that is able to upload an image and display its thumbnail. However, I would like to save the images to a particular folder as well.
What jQuery code or ajax code can I use to save the original image to a folder of my choice?
Here is the live demo: http://jsfiddle.net/dn9Sr/2/
Here is the full code:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.js" type="text/javascript"></script>
<style>
.input-file-row-1:after {
content: ".";
display: block;
clear: both;
visibility: hidden;
line-height: 0;
height: 0;
}
.input-file-row-1{
display: inline-block;
margin-top: 25px;
position: relative;
}
#preview_image {
display: none;
width: 90px;
height: 90px;
margin: 2px 0px 0px 5px;
border-radius: 10px;
}
.upload-file-container {
position: relative;
width: 100px;
height: 137px;
overflow: hidden;
background: url(http://i.imgur.com/AeUEdJb.png) top center no-repeat;
float: left;
margin-left: 23px;
}
.upload-file-container-text{
font-family: Arial, sans-serif;
font-size: 12px;
color: #719d2b;
line-height: 17px;
text-align: center;
display: block;
position: absolute;
left: 0;
bottom: 0;
width: 100px;
height: 35px;
}
.upload-file-container-text > span{
border-bottom: 1px solid #719d2b;
cursor: pointer;
}
.one_opacity_0 {
opacity: 0;
height: 0;
width: 1px;
float: left;
}
</style>
<script>
$( document ).ready(function() {
function readURL(input, target) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var image_target = $(target);
reader.onload = function (e) {
image_target.attr('src', e.target.result).show();
};
reader.readAsDataURL(input.files[0]);
}
}
$("#patient_pic").live("change",function(){
readURL(this, "#preview_image")
});
});
</script>
</head>
<body>
<form name="" method="post" action="#" class="feedback-form-1">
<fieldset>
<div class="input-file-row-1">
<div class="upload-file-container">
<img id="preview_image" src="#" alt="" />
<div class="upload-file-container-text">
<div class = 'one_opacity_0'>
<input type="file" id="patient_pic" label = "add" />
</div>
<span> Add Photo </span>
</div>
</div>
</div>
</fieldset>
</form>
</body>
</html>
UPDATE: I think I am on the right track. I am close but I don't know what data to send from the jQuery. I added a php scrit and its getting a call back as success but I am not sending the right var. I think if I just send the right val I can get it.
CODE:
<script>
$( document ).ready(function() {
function readURL(input, target) {
if (input.files && input.files[0]) {
var reader = new FileReader();
var image_target = $(target);
reader.onload = function (e) {
image_target.attr('src', e.target.result).show();
$.ajax({
type:'POST',
url: 'theUpload.php',
data: input.files[0],
success:function(data){
console.log("success");
console.log(data);
alert(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
};
reader.readAsDataURL(input.files[0]);
}
}
$("#patient_pic").live("change",function(){
readURL(this, "#preview_image")
});
});
</script>
Try this one.
Script:
function uploadFile(){
var input = document.getElementById("file");
file = input.files[0];
if(file != undefined){
formData= new FormData();
if(!!file.type.match(/image.*/)){
formData.append("image", file);
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false,
contentType: false,
success: function(data){
alert('success');
}
});
}else{
alert('Not a valid image!');
}
}else{
alert('Input something!');
}
}
HTML:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
</head>
<body>
<input type="file" id="file" />
<button onclick="uploadFile();">Upload</button>
</body>
</html>
upload.php:
<?php
$dir = "image/";
move_uploaded_file($_FILES["image"]["tmp_name"], $dir. $_FILES["image"]["name"]);
?>
John's answer is good but file = input.files[0] doesn't work for me
file = input[0].files[0]
works.
You need a server side language to store the uploaded image to specified folder. PHP is one of them, so I highly recommend to take a look of it.
AJAX is just for executing server side calls without refreshing the page.
Related
Hiii Everyone.
Below is my HTML.
<!DOCTYPE html>
<html>
<head>
<script src="src/recorder.js"></script>
<script src="src/Fr.voice.js"></script>
<script src="js/jquery.js"></script>
<script src="js/app.js"></script>
</head>
<body>
<div class="center_div">
<span class="recording_label">Please wait...</span>
<span class="loader_bg"></span>
<span class="loader_bg1"></span>
<br/>
<audio controls id="audio"></audio>
</div>
<style>
.center_div {
width: 500px;
height: 150px;
background-color: #f5f5f5;
border: 1px solid #808080;
position:absolute;
top:50%;
left:50%;
margin-left:-250px;/* half width*/
margin-top:-75px;/* half height*/
padding:25px;
}
.recording_label {
display: block;
text-align: center;
padding: 10px;
font-family: sans-serif;
font-size: 1.1em;
margin-bottom: 25px;
}
.loader_bg {
min-width: 100%;
background: #c5c5c5;
min-height: 20px;
display: block;
}
.loader_bg1 {
min-width: 90%;
background: grey;
min-height: 20px;
display: inline-block;
position: relative;
top: -20px;
}
audio {
}
</style>
</body>
</html>
In the above code I had tried to record and preview the audio once record complete processing. I want to upload that preview audio in folder using PHP. Can anyone help me in AJAX part how to send mp3 file. I had referred so many links but I couldn't get solution for this part. Kindly anyone help me. Thanks in advance. Please refer my working fiddle here.
Getting Source file like this:
<audio controls="" id="audio" src="blob:null/b63e868d-1628-4836-85da-90cf1b5b65c3"></audio>
How can I get this blob and convert it to mp3 and store in folder?
Change the code in app.js as below, Set the url in ajax call
$(function(){
var max = 40;
var count = max + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording...");
$('.loader_bg1').css({'min-width':''+(100)+'%'})
Fr.voice.record(false, function(){});
Fr.voice.stopRecordingAfter(40000, function(){
//alert("Recording stopped after 40 seconds");
Fr.voice.export(function(url){
$("#audio").attr("src", url);
$("#audio")[0].play();
}, "URL");
});
recordingSec(40);
return;
}
$(".recording_label").html("Recording will begin in " + count + " sec.");
var percent = (count / max ) * 100 ;
$('.loader_bg1').css({'min-width':''+(100 - percent)+'%'})
}
});
function uploadAudio(){
Fr.voice.exportMP3(function(blob){
var data = new FormData();
data.append('file', blob);
$.ajax({
url: "server.php",
type: 'POST',
data: data,
contentType: false,
processData: false,
success: function(data) {
// Sent to Server
}
});
}, "blob");
}
function recordingSec(sec){
var count = sec + 1;
var counter = setInterval(timer, 1000);
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
$(".recording_label").html("Recording stopped...Playing");
$('.loader_bg1').css({'min-width':''+(100)+'%'})
//stopRecording();
return;
}
$(".recording_label").html("Recording started [ " + (sec - count) + " / " + sec + " ] sec.");
var percent = (count / sec ) * 100 ;
$('.loader_bg1').css({'min-width':''+(100 - percent)+'%'})
}
}
Refer this Documentation
Check this file for reference
Server.php sample
<?php
$path = 'audio/';
$location = $path . $_FILES['file']['name'] . ".mp3";
move_uploaded_file($_FILES['file']['tmp_name'], $location);
?>
Here is my main html file;
<!DOCTYPE html>
<html lang="en">
<head>
<title>Create Template</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<link rel = "stylesheet"
type = "text/css"
href = "jquery-ui-1.11.4.custom/jquery-ui.css " />
<style type = "text/css">
.dragMe {
width: auto;
height: auto;
/* border: 1px solid blue; */
text-align: center;
background-color: white;
position: absolute;
display:inline-block;
z-index: 100;
}
.dragMeImage {
width: 180px;
height: 55px;
border: 1px solid blue;
text-align: center;
background-color: white;
position: absolute;
z-index: 100;
}
#target {
width: 400px;
height: 600px;
border: 1px solid red;
text-align: center;
position: absolute;
left: 400px;
top: 100px;
z-index: 0;
}
</style>
<script type = "text/javascript"
src = "jquery-1.12.4.min.js">
</script>
<script type = "text/javascript"
src = "jquery-ui-1.11.4.custom/jquery-ui.min.js">
</script>
<script type = "text/javascript" src="ajaxshow.js">
</script>
<script type = "text/javascript">
$(init);
function init(){
//make all drag me elements draggable
$(".dragMe").draggable();
$(".dragMeImage").resizable({
//aspectRatio: 3.2
});
//set target as droppable
$("#target").droppable();
//bind events to target
$("#target").bind("drop", changeTarget);
$("#target").bind("dropout", resetTarget);
} // end init
function changeTarget(event, ui){
$("#target").addClass("ui-state-highlight")
.html("Dropped ")
.append(ui.draggable.text());
} // end changeTarget
function resetTarget(event, ui){
$("#target").removeClass("ui-state-highlight")
.html("Drop on me");
} // end reset
</script>
</head>
<body id="page2">
<form id=form enctype="multipart/form-data" method="post" action="show_images.php">
<input type="submit" value="Continue"/>
</form>
<div id="preview"></div>
<div id="err"></div>
<!-- <h2>Create an Invitation Template to be Sent to the List Owners</h2>
<div class = "dragMe">
<img class = "dragMeImage" src="garbo.png" alt="Garbo Logo" style="width:180px;height:120px;">
</div>
<div class = "dragMe">
<img class = "dragMeImage" src="CA.png" alt="Garbo Logo" style="width:180px;height:55px;">
</div>
<div class = "dragMe">
<img class = "dragMeImage" src="CA1.png" alt="Garbo Logo" style="width:180px;height:55px;">
</div>
<div id = "target">
Drop on this template
</div> -->
</body>
</html>
Here is ajaxshow.js;
$(document).ready(function (e) {
$("#form").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "http://localhost/phpexamples/show_images.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function()
{
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data)
{
if(data=='invalid file')
{
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
}
else
{
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e)
{
$("#err").html(e).fadeIn();
}
});
}));
});
and here is the PHP file;
<?php
$folder = "uploads/";
if(is_dir($folder)){
if($handle = opendir($folder)){
while(($file=readdir($handle)) != false){
if($file==='.' || $file==='..') continue;
list($width, $height) = getimagesize("uploads/$file");
$h=150/$width*$height;
$aspect = $height / $width;
if ($aspect >= 1) $mode = "vertical";
else $mode = "horizontal";
echo '<div class = "dragMe">';
echo '<img class = "dragMeImage" src="uploads/'.$file.'" width="150" height="$h" alt="">';
echo '</div>';
}
closedir($handle);
}
}
?>
When I load the images in static HTML (commented out) it works fine. When I run the code above it loads the first image in the directory but it's not draggable or resizable. When I take the class ID's out of the echo part of the PHP file. It loads the images OK but of course they are not draggable or resizable. Can anyone help. Many thanks. Neil.
Since you are adding content dynamically after the image has been uploaded, you will need to call .draggable() on the new elements.
I would advise doing this once your AJAX completes:
$.ajax({
url: "http://localhost/phpexamples/show_images.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
beforeSend : function() {
$("#err").fadeOut();
},
success: function(data) {
if(data=='invalid file') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
$("#preview").find(".dragMe").draggable();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
Well I am not able to send form multiple times. The initial part of the code of AjaxForm is working fine whereas the FormData is not working. Instead it send the data in the url without the page like
index.php?photos[]=&username=dfdfdf. The Earlier part is used for image storage and second part is used for user data storage. My requirement is to use single form to send data to different table in database. When the user click submit the data is stored in the data table and the uploaded image also gets updated with that user ID.
Hope You will solve the problem!
<?php
session_start();
include("db.php");
$str = "select * from fileupload order by id DESC";
$res = mysql_query($str);
?>
<!DOCTYPE html>
<html>
<head>
<title>Upload</title>
<script src="js/jquery.min.js"></script>
<script src="js/jquery.wallform.js"></script>
<script>
$(document).ready(function() {
$('#photoimg').die('click').live('change', function() {
$("#imageform").ajaxForm({
url : 'ajaxImageUpload.php',
target: '#preview',
beforeSubmit:function(){
console.log('ttest');
$("#imageloadstatus").show();
$("#imageloadbutton").hide();
},
success:function(){
console.log('test');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
},
error:function(){
console.log('xtest');
$("#imageloadstatus").hide();
$("#imageloadbutton").show();
} }).submit();
});
$(".del-pic").live("click", function(){
var sel1 = $(this).closest('.imgList');
var del_id = $(this).attr('id');
$.post("deleteimage.php", {
del_id : del_id
},
function(data, txtStatus) {
sel1.fadeOut('slow', function()
{
sel1.remove();
});
});
});
$("#uploadTrigger").click(function(){
$("#photoimg").click();
});
$("#upbutton").live("click", function(){
$("#imageform").bind('submit',function(e){
if(window.FormData !== undefined) // for HTML5 browsers
{
var formdata = new FormData(this);
$.post({
url : "insertuser.php",
type : "POST",
data : formdata,
mimeType : "multipart/form-data",
contentType : false,
cache : false,
processData: false,
success: function(data, txtstatus, jqXHR)
{
alert('success');
},
error: function(data, txtstatus, errorthrown)
{
alert('error');
}
});
}
else
{
alert('HTML5 not supporting in your browser');
}
});
});
});
</script>
<style>
#preview
{
color:#cc0000;
font-size:12px;
background: #066;
}
.imgList
{
max-height:100px;
margin-left:10px;
border:1px solid #dedede;
padding:4px;
float:left;
}
.hidden
{
display: none;
}
#uploadTrigger
{
cursor: pointer;
border: 1px solid #333;
padding: 10px;
margin: 5px 5px 5px 5px;
background: #777;
color: #fff;
width:75px;
border-radius: 20px;
font-family:arial;
}
.del-pic
{
background-image:url(../../Krishna/images2/closebox.png);
width:30px;
height:30px;
display:block;
position: absolute;
margin:-10px 0 0 85px;
}
</style>
</head>
<body>
<div>
<div id='preview' style="">
<?
while($row = mysql_fetch_array($res))
{
echo "<div class='imgList'><div class='del-pic' id='".$row['id']."'></div><img src='".$row['filename']."' width='100px' height='100px' ></div>";
}
?>
</div>
<form id="imageform" name="imageform" enctype="multipart/form-data" style="clear:both">
<div id='imageloadstatus' style='display:none'><img src="loader.gif" alt="Uploading...."/></div>
<div id='imageloadbutton'>
<div id="uploadTrigger">Add Photo</div>
<input type="file" name="photos[]" id="photoimg" class="hidden" multiple="true" />
<input name="username" type="text" id="username" />
<input type="submit" value="Upload" id="upbutton" />
</div>
</form>
</div>
</body>
</html>
<html>
<head>
<style>
.messboxcontent { display:none; background: rgba(0,0,0,.4); width: 400px; height: 100px; margin: 50px auto; padding: 15px;}
.mess_name {display: inline-block; cursor: pointer ; vertical-align: middle; width:165px; height:35px; background:blue; bottom:0px; left:144px; margin-right: 16px}
#msg_holder {overflow-x:scroll ;overflow-y: hidden; white-space: nowrap; position:fixed;height:110px; width:100%; background-color:yellow; bottom:0px;}
</style>
<script type="text/javascript" src="jquery.js" ></script>
<script>
$(document).ready( function() {
done();
});
function done() {
setTimeout( function() {
update();
done();
}, 20000);
}
function update() {
$.getJSON("fetch.php", function(data) {
$.each(data.result, function(){
var message = this['message'];
var name = this['name'];
call(name, message);
});
});
};
function call(name, message){
$("#msg_holder").append("<div class='mess_name'>" + name + "<div>");
$(".mess_test").click( function() {
$('div.messboxcontent').html(' name : '+ name + ' Message : ' + message);
$('div.messboxcontent').fadeIn();
return false;
});
}
</script>
</head>
<body>
<div class="messboxcontent"></div>
<div id="msg_holder"></div>
</doby>
</html>
and this is fetch.php file
{"result":[{"message":"this is haha","name":"haha"},{"message":"this is koka","name":"koka"}]}
when ever i click on a blue box that Contain any name, it show up the latest message and name. what i want is when i click on the box that contain haha as a name i want the box that contain message: this is haha,
You need to use append rather than html.
$('div.box').append( message );
Hi i'm using this code to fetch new images from a folder to populate an slideshow.
after each cycle ajax should check content of the folder to see if any there was any
changes(pictures added or removed) then on the next cycle it should make the new changes to
the slideshow
<html>
<meta http-equiv="refresh" content="1000"/>
<head>
<title>Slideshow</title>
<style type="text/css">
#slideshow
#slideshow img { padding: 15px; border: 1px solid #ccc; background-color: #eee; }
#slide {width: 370px; height: 220px; padding: 0; margin: 0 auto; }
#myslides {
width: 370px;
height: 220px;
padding: 0;
margin: 0 auto;
}
#myslides img {
padding: 10px;
border: 1px solid rgb(100,100,100);
background-color: rgb(230,230,230);
width: 350px;
height: 200px;
top: 0;
left: 0
}
</style>
</head>
<!-- include jQuery library -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<!-- include Cycle plugin -->
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#slideshow').cycle({
fx: 'fade',
speed: 700,
timeout: 8000
});
});
</script>
<body>
<div id="slideshow">
</body>
</html>
<script>
$(function(){
window.onload("fetchImages()", 2);
function fetchImages() {
$.ajax({
type: "GET",
url: "load.php"
}).done(function(response){
var curImgCount = $('#slideshow img').length;
if (response.length > curImgCount) {
for (var i = curImgCount; i < response.length; i++) {
$('#slideshow').append('<img src="images/' + response[i] + '"');
}
}
});
}
});
</script>
and content of php:
<?php
function returnimages($dirname="./images") {
$pattern="([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";
$files = array();
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(preg_match($pattern, $file)){ //if this file is a valid image
$files[] = $file;
}
}
closedir($handle);
}
//sort($files);
natcasesort($files);
return($files);
}
$images = returnimages();
foreach($images as $img)
{
echo json_encode($images);
}
?>
Change your PHP to:
<?php
function returnimages($dirname="./images") {
$pattern="([^\s]+(\.(?i)(jpg|png|gif|bmp))$)";
$files = array();
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(preg_match($pattern, $file)){ //if this file is a valid image
$files[] = $file;
}
}
closedir($handle);
}
//sort($files);
natcasesort($files);
return($files);
}
$images = returnimages();
echo json_encode($images);
?>
and your HTML to:
<html>
<head>
<meta http-equiv="refresh" content="1000"/>
<title>Slideshow</title>
<style type="text/css">
#slideshow {
position: relative;
}
#slideshow,
#slideshow img {
position: absolute;
top: 0px;
left: 0px;
padding: 15px;
border: 1px solid #ccc;
background-color: #eee;
}
#slide {
width: 370px;
height: 220px;
padding: 0;
margin: 0 auto;
}
#myslides {
width: 370px;
height: 220px;
padding: 0;
margin: 0 auto;
}
#myslides img {
padding: 10px;
border: 1px solid rgb(100,100,100);
background-color: rgb(230,230,230);
width: 350px;
height: 200px;
top: 0;
left: 0
}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js"></script>
<script type="text/javascript">
function loadSlides() {
$.ajax({
type: "GET",
url: "load.php"
}).done(function(response) {
var temp_images = eval("(" + response + ")");
for(ti in temp_images)
{
//alert(temp_images[ti]);
$('#slideshow').append('<img src="images/' + temp_images[ti] + '" alt="">');
}
startSlideshow();
});
}
function startSlideshow()
{
$('#slideshow').cycle({
fx: 'fade',
speed: 700,
timeout: 800
});
}
$(document).ready(function(){
loadSlides();
});
</script>
</head>
<body>
<div id="slideshow" />
</body>
</html>
I'm testing this code and it works fine but why the refresh meta tag? Isn't the point of AJAX to prevent this from happening and make it dynamic? Also, the biggest problem is that you need to set a meta refresh time that is not too long such that images don't take too long to reflect when added or deleted and not too short to prevent some images from showing at all (inevitable at some point).