I've downloaded an image uploading script with Ajax from this Link
The codes are:
index.php
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, str){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + str+'<label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
//-->
</script>
</head>
<body>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's AJAX File Uploader</div><div id="header_right"></div></div>
<div id="content">
<form action="upload.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
<p id="f1_upload_form" align="center"><br/>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
<div id="footer">Powered by AJAX F1</div>
</div>
</body>
Uploader.php
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
// echo $target_path;
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result.",".$target_path; ?>);</script>
I want to show the url of uploaded image. So that it can be use instantly.
I've a little knowledge about ajex. I tried by writing two three of codes but it's not working.
Anyone can help to show the file url.
Thanks in advance.
Hope this helps...
index.php
<html>
<head>
<script src="js/jquery-2.1.4.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<script language="javascript" type="text/javascript">
<!--
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success, str, filename){
var result = '';
var file_link = '';
var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
file_link = "<br/><a href='"+directoryPath+"/"+filename +"'>"+filename+"</a><br/>";
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + file_link +'<br/><br/><label>File: <input name="myfile" type="file" size="30" /><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
//-->
</script>
</head>
<body>
<div id="container">
<div id="header"><div id="header_left"></div>
<div id="header_main">Max's AJAX File Uploader</div><div id="header_right"></div></div>
<div id="content">
<form action="ajax-uploader.php" method="post" enctype="multipart/form-data" target="upload_target" onsubmit="startUpload();" >
<p id="f1_upload_process">Loading...<br/><img src="loader.gif" /><br/></p>
<p id="f1_upload_form" align="center"><br/>
<label>File:
<input name="myfile" type="file" size="30" />
</label>
<label>
<input type="submit" name="submitBtn" class="sbtn" value="Upload" />
</label>
</p>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
</div>
<div id="footer">Powered by AJAX F1</div>
</div>
</body>
</body>
</html>
ajax-uploader.php
<?php
// Edit upload location here
$destination_path = getcwd().DIRECTORY_SEPARATOR;
$result = 0;
$target_path = $destination_path . basename( $_FILES['myfile']['name']);
$actual_name = basename( $_FILES['myfile']['name']);
if(#move_uploaded_file($_FILES['myfile']['tmp_name'], $target_path)) {
$result = 1;
// echo $target_path;
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.stopUpload(<?php echo "$result, '$target_path','$actual_name' "; ?>);</script>
change Uploader.php to upload.php.
Add php code after sleep as follows..
sleep(1);
$target_path = str_replace('\\', '/', $target_path);
$spath = "http://".$_SERVER['HTTP_HOST'].dirname($_SERVER['REQUEST_URI'])."/".$_FILES['myfile']['name'];
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo "'".$result."','".$target_path.',img url :'.$spath."'";?>);</script>
Related
This is more of a question to gain a more clear understanding. If I insert from a form like:
<form action="upload.php" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
into the DB for a link and it's successful:
$file = "INSERT INTO ('foo') VALUES ('FOO', NOW())";
just an example:
yet in the php script:
$_FILE['fileToUpload']['name'];
$_FILE['fileToUpload']['tmp_name'];
since the tmp_name folder only holds upload files in an array, which than I would have to use either a foreach or for loop search the loop of files, this than makes the INSERT INTO db difficult.
Question is how can I separate the search results from the array and than insert each one into the database?
HERE"S THE CODE:
<?php
$con = mysqli_connect("localhost","root","","acc1");
if(mysqli_connect_errno()){
echo 'Failed to connect to MySQL:' . mysqli_connect_error();
}else{
echo 'Connected!';
}
if(isset($_POST['submit']) && !empty($_FILES['fileBC']['name'] && !empty($_FILES['fileB']['name'] && !empty($_FILES['fileBR']['name']) ))){
$file = "image/";
$name = $_FILES['fileBC']['name'];
$data = $_FILES['fileBC']['tmp_name'];
$fileV = "video/";
$nameV = $_FILES['fileBR']['name'];
$dataV = $_FILES['fileBR']['tmp_name'];
$fileB = "book/";
$nameB = $_FILES['fileB']['name'];
$dataB = $_FILES['fileB']['tmp_name'];
if(move_uploaded_file($data,$file.$name)){
$ins_name = $con->query("INSERT INTO fileimages (fileBC, fileBR, fileB) VALUES ('$name','$nameB', '$nameV')");
}if($ins_name){
echo 'success!';
}else{
echo 'error';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/fontawesome.css">
<script src="js/jquery.js"></script>
<script src="js/bootstrap.js"></script>
</head>
<script>
function mymodal(){
$('#myModal').modal('show');
}
</script>
<body>
<form method="post" action="index.php" enctype="multipart/form-data">
<div class="form-group">
<label class="text-primary">Book Cover:</label>
<input class="form-control" type="file" name="fileBC" accept="image/*" >
</div>
<div class="form-group">
<label class="text-primary">Book:</label>
<input class="form-control" type="file" name="fileB" accept=".epub, .mobi, .pdf, .prc, .azw, .bbeb" >
</div>
<div class="form-group">
<label class="text-primary">Book Reading:</label>
<input class="form-control" type="file" name="fileBR" accept="video/*" >
</div>
<button name="submit">upload</button>
</form>
<p></p>
<ol>
</ol>
</body>
</html>
This is an example you can adept it as per your need.
<form action="file_reciever.php" enctype="multipart/form-data" method="post">
<input type="file" name="files[]" multiple/>
<input type="submit" name="submission" value="Upload"/>
</form>
PHP code is like
<?php
if (isset($_POST['submission'] && $_POST['submission'] != null) {
for ($i = 0; $i < count($_FILES['files']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['files']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//Setup our new file path
$newFilePath = "./uploadFiles/" . $_FILES['files']['name'][$i];
//Upload the file into the temp dir
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
//Your insert statement goes here
}
}
}
}
?>
I need to upload the image to a server and store to the directory created by PHP using current timestamp. Below is the relevant part of the code, but not working as expected, it's not creating a folder as well it's not printing to the console. What could be the issue?
Edit:
Modified php based on below comment
upload.php
<?php
//get unique id
$up_id = uniqid();
?>
<?php
//process the forms and upload the files
if ($_POST) {
//specify folder for file upload
$user = "user";
//console.log("debug.......");
echo "debug.......";
if (!file_exists("/var/www/Scan")) {
mkdir("/var/www/Scan", 0777, true);
}
$folderName = date("Y-m-d") . "_" . date("h_i_sa") . "_" . $user;
if (!file_exists("/var/www/Scan/$folderName")) {
mkdir("/var/www/Scan/$folderName", 0777, true);
}
$folder = "/var/www/Scan/$folderName";
//specify redirect URL
$redirect = "upload.php?success";
//upload the file
move_uploaded_file($_FILES["file"]["tmp_name"], "$folder" . $_FILES["file"]["name"]);
//do whatever else needs to be done (insert information into database, etc...)
//redirect user
header('Location: '.$redirect); die;
}
//
?>
<!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=iso-8859-1" />
<title>Upload your file</title>
<!--Progress Bar and iframe Styling-->
<link href="style_progress.css" rel="stylesheet" type="text/css" />
<!--Get jQuery-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.js" type="text/javascript"></script>
<!--display bar only if file is chosen-->
<script>
$(document).ready(function() {
//
//show the progress bar only if a file field was clicked
var show_bar = 0;
$('input[type="file"]').click(function(){
show_bar = 1;
});
//show iframe on form submit
$("#form1").submit(function(){
if (show_bar === 1) {
$('#upload_frame').show();
function set () {
$('#upload_frame').attr('src','upload_frame.php?up_id=<?php echo $up_id; ?>');
}
setTimeout(set);
}
//document.getElementById("message").innerHTML = "";
});
//
});
</script>
</head>
<body>
<div id="outPopUp">
<h1 >Upload your file </h1>
<form action="" method="post" enctype="multipart/form-data" name="form1" id="form1">
<br />
<br />
<!--Choose a file to upload<br />-->
<!--APC hidden field-->
<input type="hidden" name="APC_UPLOAD_PROGRESS" id="progress_key" value="<?php echo $up_id; ?>"/>
<!---->
<!-- <input name="file" type="file" id="file" size="30"/>-->
<label class="custom-file-upload">
<input name="file" type="file" id="file" onclick="myFunction()" />
Choose Video
</label>
<!--Include the iframe-->
<br />
<br />
<iframe id="upload_frame" name="upload_frame" color= black frameborder="0" border="0" src="" scrolling="no" scrollbar="no" > </iframe>
<br />
<!---->
<br />
<input class="btn btn-blue" name="Submit" type="submit" id="submit" value="Submit" />
<br />
<br />
<?php if (isset($_GET['success'])) { ?>
<span style="color:#FFFFFF;" id="message" class="notice">Your file has been uploaded.</span>
<?php } ?>
</form>
</div>
<script>
function myFunction() {
document.getElementById("message").innerHTML = "";
}
/*document.getElementById('file').onchange = function () {
//alert('Selected file: ' + this.value);
var path = this.value;
var fileName = path.replace(/.*(\/|\\)/, '');
alert('Selected file: ' + fileName);
//myFunction(fileName);
};*/
</script>
</body>
</html>
try a simple example for understanding:
<?php
//php content
if ($_POST) { //here we are checking $_POST values that $_POST has some values.
//specify folder for file upload
$tempDir = __DIR__ . DIRECTORY_SEPARATOR . 'upload'; //it means make a directory uploads where this php file is kept.
if (!file_exists($tempDir)) { // if $tempDir is not there, so it will create that directory.
mkdir($tempDir);
}
if(!empty($_FILES))//now checking your uploaded file is not empty
{
$nm=$_FILES['file']['name']; //here $nm get the name of the file
$tmp=$_FILES['file']['tmp_name'];//$tmp get the temporary file stored path
$mDir = __DIR__ . DIRECTORY_SEPARATOR . 'uploads'. DIRECTORY_SEPARATOR .time().$nm; //this your destination path with time+nameof file as a name of file.
if(move_uploaded_file($tmp,$mDir)) //uploading file to your destination path, if uploaded then it will go in the if scope and echo.
{
echo "file uploaded with timestamp in uploads folder";
//now redirect from here any where
}
else
{
echo "fail to upload a file";
}
}
}
?>
How to display images right after they clicked the upload button?
Here is my HTML Code:
form.php
<html>
<body>
<form action="uploadFile.php" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
</body>
</html>
And here is my uploadFile.php code:(updated, but still not getting any result)
<?php
// prevent timezone warnings
date_default_timezone_set('Philippines/Manila');
// set the upload location
$UPLOADDIR = "images/";
// if the form has been submitted then save and display the image(s)
if(isset($_POST['Submit'])){
// loop through the uploaded files
foreach ($_FILES as $key => $value){
$image_tmp = $value['tmp_name'];
$image_type=$value['type'];
$image = $value['name'];
$image_file = "{$UPLOADDIR}{$image}";
//check if there's existing file name
if ($image != 0){
echo 'File Already Exists!';
}
else {
// move the file to the permanent location
if(move_uploaded_file($image_tmp,$image_file)){
// this is where the displaying part goes
echo <<<HEREDOC
<div style="float:left;margin-right:10px">
<img src="$editedShear" alt="This is your image" height=200 width=200/></br>
</div>
HEREDOC;
}
else{
echo "<h1>image file upload failed, image too big after compression</h1>";
}
}
}}
else{
?>
<?php
}
?>
To do that you need to upload the image using some kind of ajax upload. if you don't know what is that, please read here http://en.wikipedia.org/wiki/Ajax_%28programming%29. You can find some free solutions and examples online. Here I found a stack overflow question that might help you with links to such a solutions
Ajax file upload
Upload your image in a folder which contains your php/html file,
and in img tag write the img name:
<img src="<?php echo $img;?>" width="400" height="600"/>
/* i put image so that it has default
<img id="blah" src="images/male.png" alt="your image" style="width:250px;height:200px;" />
/*put accept and its format so that you can only choose the image only
<input type='file' name="image" onchange="readURL(this);" accept="image/gif,image/png,image/jpg,image/jpeg" />
/*changing the url of an image you can do it in jquery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
/*set the width and height of an image
.width(250)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
after that do your upload code
What is the easiest way to upload images and display the uploaded images on same page?
page "index.php"
<body>
<div id="body">
<form action="upload.php" name="img_compress" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<button type="submit" name="btn-upload">upload</button>
</form>
<br /><br />
<?php
if(isset($_GET['success']))
{
?><br><br><br>
<?php
$sql="SELECT * FROM tbl_uploads ORDER BY id DESC";
$result_set=mysql_query($sql);
while($row=mysql_fetch_array($result_set))
{
?>
<img src="uploads/<?php echo $row['file'] ?>" width="100%" height="100%">
<?php
}
?>
<?php
}
else if(isset($_GET['fail']))
{
?>
<label>Problem While File Uploading !</label>
<?php
}
else
{
?>
<label>Try to upload any files(PDF, DOC, EXE, VIDEO, MP3, ZIP,etc...)</label>
<?php
}
?>
</div>
</body>
code for upload "upload.php"
<?php
include_once 'dbconfig.php';
if(isset($_POST['btn-upload']))
{
$file = $_FILES['file']['name'];
$file_loc = $_FILES['file']['tmp_name'];
$file_size = $_FILES['file']['size'];
$file_type = $_FILES['file']['type'];
$folder="uploads/";
$new_size = $file_size/1024;
$new_file_name = strtolower($file);
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($file_loc,$folder.$final_file))
{
$sql="INSERT INTO tbl_uploads(file,type,size) VALUES('$final_file','$file_type','$new_size')";
mysql_query($sql);
?>
<script>
window.location.href='index.php?success';
</script>
<?php
}
else
{
?>
<script>
alert('error while uploading file');
window.location.href='index.php?fail';
</script>
<?php
}
}
?>
below one is fields for storing images
enter image description here
Add an iframe after your form:
<iframe name="resultFrame" width="500" height="300"></iframe>
And add the target="resultFrame" attribute in your form like this:
<html>
<body>
<form action="uploadFile.php" method="post"
enctype="multipart/form-data" target="resultFrame">
<label for="file">Filename:</label>
<input type="file" name="file" id="file"><br>
<input type="submit" name="submit" value="Submit">
</form>
<iframe name="resultFrame" width="500" height="300"></iframe>
</body>
</html>
i am uploading the files to PHP script. it process and give response. i want to load that response in the div or frame on same web page. now the following script giving response in the blank web page. please help me to solve this.
php:
<html>
<head>
<script type="text/javascript">
function init() {
if(top.uploadDone) top.uploadDone();
}
window.onload=init;
</script>
<body>
<?php
$fn = (isset($_SERVER['HTTP_X_FILENAME']) ? $_SERVER['HTTP_X_FILENAME'] : false);
if ($fn) {
file_put_contents(
'uploads/' . $fn,
file_get_contents('php://input')
);
echo "$fn uploaded";
exit();
}
else {
// form submit
$files = $_FILES['fileselect'];
//print $files['name'];
foreach ($files['error'] as $id => $err) {
if ($err == UPLOAD_ERR_OK) {
$fn = $files['name'][$id];
move_uploaded_file(
$files['tmp_name'][$id],
'uploads/' . $fn
);
if($id==1)
{
$filename = 'uploads/' . $fn;
$fp = fopen( $filename, "r" ) or die("Couldn't open $filename");
$line = fgets($fp);
fclose($fp);
$arr = split(",",$line);
for($i=2;$i< count($arr);$i++)
{
print '<input type="checkbox" name="traits" value="1">'.$arr[$i]."<br>";
}
}
}
}
}
?>
</body>
</html>
Jquery:
function init() {
document.getElementById("upload").onsubmit=function() {
document.getElementById("upload").target = "Analysis";
document.getElementById("Analysis").onload = uploadDone; }
}
function uploadDone() { //Function will be called when iframe is loaded
var ret = frames['Analysis'].document.getElementsByTagName("body")[0].innerHTML;
}
HTML script:
<div id="content_column">
<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data">
<fieldset>
<div id="Geno" style="display:none">
<strong>Select Genotypic File</strong>
<input type="hidden" id="MAX_FILE_SIZE" name="MAX_FILE_SIZE" value="300000" />
<div>
<input type="file" id="fileselect" name="fileselect[]" />
</div>
</div>
<P>
<div id="Peno" style="display:none">
<strong>Select Penotypic File</strong>
<div>
<input type="file" id="fileselect1" name="fileselect[]" />
</div>
</div>
<P>
<div id="Other" style="display:none">
<strong>Select Other Files*</strong>
<div>
<input type="file" id="fileselect2" name="fileselect[]" multiple="multiple" />
</div>
</div>
<div id="submitbutton" style="display:none">
<INPUT TYPE="Submit" VALUE="Upload" />
</div>
</fieldset>
</form>
<iframe id="Analysis" name="Analysis" src="" ></iframe>
</div>
Thank you in adavance. .
I'm doing data entry program based on PHP every thing is working no issue (still under construction) but there is a problem that I can't find a solution. The issue is when the database doesn't have any data the image path wont get registered.
Now I'm using uplodify to upload an image file at the same moment I'm sending some data as well. The data contains a name, contact details and description this will directly be inserted to the DB and I also upload image which will get saved in to a folder and the name get saved in the database. But this processes are handled by two different PHP files one is AddPOIPro.PHP which handles the data adding and the uplodify.php to handle file upload and the updating of the file name.
The first issue I had was uplodify was not adding the file name in the same row as the submitted data so what I did was to get the last ID and decrement it by one and the updated the row that works when there is data but when theirs no data it fails. So what should I do to over come this. Below is my complete scripts thank you for your time.
Form
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('lId.php');
?>
<!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" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
$(function() {
$('#imgUpload').uploadify({
'auto' : false,
'swf' : 'Upl/uploadify.swf',
'uploader' : 'Upl/uploadify.php',
'height' : 20,
'width' : 200,
}
// Put your options here
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#sendData").click(function(){
var name = document.getElementById("Name").value;
var desc = document.getElementById("Descrip").value;
var con = document.getElementById("ConInfo").value;
var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;
$.ajax({
type:'POST',
data:dataString,
url:'AddPoiPro.php',
success:function(data){
if(data="Data inserted") {
//alert("Data Success");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
$('#msg').delay(1500).fadeOut();
} else {
//alert("Not Inserted");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
}
}
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image</label>
<input type="file" name="imgUpload" id="imgUpload" />
</p>
<p><div id="msg"></div></p>
<p>
<div align="center">
<input type="button" name="Submit" id="sendData" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
Process PHP
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM poiinfo");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
if($row['ID']== 1){
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
uplodify php
<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');
// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root
/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $fName;
echo '1';
} else {
echo 'Invalid file type.';
}
}*/
//if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = $targetPath . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$tId = $tId--;
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
$fName = $_FILES['Filedata']['name'];
$imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
mysql_query($imgPath);
echo '1';
} else {
echo 'Invalid file type.';
}
?>
Please help.
To get Last id you can do Query As Like Following
SELECT `ID`
FROM `poiinfo`
ORDER BY `ID` DESC
LIMIT 0 , 1
If you face any more problem then you can knock me..
I think this would be a better approach
$("#sendData").click(function(){
//upload the file programatically (Method Call'upload')[http://www.uploadify.com/documentation/uploadify/upload/]
// echo the name of the uploaded file (make sure to rename the file for uniquiness)
// create a hidden element with the filename as the value inside the form
// call the ajax submit and submit the form. You can use (onuploadsuccess)[http://www.uploadify.com/documentation/uploadify/onuploadsuccess/] to trigger the element creation and ajax submit functions
});
You current implementation can cause issues consider,
Request 1 : ID 10
Upload 1 : ID 10
Request 2 : ID 11
Request 3 : ID 12
Upload 2 : ID 12
Upload 3 : ID 12
I found the Solution to my problem had some help form the guys in StackOverflow Below is my full code is any one is having the same problem similar to me you can use this code. And if it works for you pls put a vote for me thank you.
My Data Entry Form
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('lId.php');
?>
<!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" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript" src="Upl/jquery.uploadify.min.js"></script>
<script type="text/javascript">
$(function() {
$(function() {
$('#imgUpload').uploadify({
'auto' : false,
'swf' : 'Upl/uploadify.swf',
'uploader' : 'Upl/uploadify.php',
'height' : 20,
'width' : 200,
'fileTypeDesc' : 'Image Files',
'fileTypeExts' : '*.gif; *.jpg; *.png'
});
// Put your options here
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#save_data").click(function(){
var name = document.getElementById("Name").value;
var desc = document.getElementById("Descrip").value;
var con = document.getElementById("ConInfo").value;
var dataString = 'Name='+name+'&Descrip='+desc+'&ConInfo='+con;
$.ajax({
type:'POST',
data:dataString,
url:'AddPoiPro.php',
success:function(data){
if(data="Data inserted") {
//alert("Data Success");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: #060\">Data Saved</dive>";
$('#msg').delay(1500).fadeOut();
} else {
//alert("Not Inserted");
document.getElementById('msg').innerHTML= "<div style=\"background-color:#0F0; text-align:center; color: red\">Data Not Saved</div>";
$('#msg').delay(1500).fadeOut();
}
}
});
});
});
</script>
<link rel="stylesheet" type="text/css" href="Upl/uploadify.css" />
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image</label>
<input type="file" name="imgUpload" id="imgUpload" />
</p>
<p><div id="msg"></div></p>
<p>
<div align="center">
<input type="button" name="Submit" id="save_data" value="Submit" onclick="$('#imgUpload').uploadify('upload','*');" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
My DataProcess PHP
<?php
/**
* #author SiNUX
* #copyright 2013
*/
include ('connect.php');
$getId = mysql_query("SELECT ID FROM dbname");
$row = mysql_fetch_array($getId);
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
if($row['ID']== 1){
$updLn = "UPDATE `poiinfo` SET `Name`='$poiName',`Des.`='$poiDes',`Contact`='$poiCon' WHERE 1";
$updDone = mysql_query($updLn);
if ($updDone){
echo "Data inserted";
}else {
echo "Not Done";
}
}else {
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
}
?>
This was really tricky the uploadify PHP but got it to work the way I want.
Uplodify PHP (My Version)
<?php
/*
Uploadify
Copyright (c) 2012 Reactive Apps, Ronnie Garcia
Released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/
include ('../../POIWeb/connect.php');
include ('../../POIWeb/lId.php');
// Define a destination
$path = 'POIWeb/img/';
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $path ; // Relative to the root
/*$verifyToken = md5('unique_salt' . $_POST['timestamp']);
if (!empty($_FILES) && $_POST['token'] == $verifyToken) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetPath = $_SERVER['DOCUMENT_ROOT'] . $targetFolder;
$targetFile = rtrim($targetPath,'/') . '/' . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
echo $fName;
echo '1';
} else {
echo 'Invalid file type.';
}
}*/
//if (!empty($_FILES)) {
$tempFile = $_FILES['Filedata']['tmp_name'];
$targetFile = $targetPath . $_FILES['Filedata']['name'];
// Validate the file type
$fileTypes = array('jpg','jpeg','gif','png'); // File extensions
$fileParts = pathinfo($_FILES['Filedata']['name']);
$tId = $tId--;
if (in_array($fileParts['extension'],$fileTypes)) {
move_uploaded_file($tempFile,$targetFile);
$fName = $_FILES['Filedata']['name'];
$imgPath = "UPDATE poiinfo SET Img = '$fName' WHERE ID = '$tId'";
mysql_query($imgPath);
echo '1';
} else {
echo 'Invalid file type.';
}
?>
This script is working flawlessly now if some face the same situation which I faced use this and see if it works for you and you're allowed to make any changes as well.
Thank you.