Im using a script to out put uploaded image preview. It works fine. i just like to show the image in one div and error or success massage in another div. is there any chance to do this? Here is the code.
Java script
<script type="text/javascript">
$(document).ready(function(){
$('#photoimg').live('change', function(){
$("#preview").html('');
$("#preview").html('<img src="loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm(
{
target: '#preview'
}).submit();
});
});
</script>
HTML Code
<?php
include('db.php');
session_start();
$session_id='1'; // User login session value
?>
<div id="output"></div>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload image <input type="file" name="photoimg" id="photoimg" />
</form>
<div id='preview'>
</div>
PHP Code
include('db.php');
session_start();
$session_id='1'; // User session id
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024)) // Image size max 1 MB
{
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
mysql_query("UPDATE users SET profile_image='$actual_image_name' WHERE uid='$session_id'");
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
echo "<span class=ok-msg">Image has been uploaded..!</span>";
}
else
echo "<span class=error-msg">failed<span>";
}
else
echo "<span class=error-msg">Image file size max 1 MB</span>";
}
else
echo "<span class=error-msg">Invalid file format..</span>";
}
else
echo "<span class=error-msg">Please select image..!</span>";
exit;
}
I like to show all the massages (error-msg, ok-msg) and in the div output and image in the same place div preview. can anyone tell me how to do this. thanks in advance.
Use json dataType and success callback function like,
$("#imageform").ajaxForm(
{
dataType:'json',
success:function(json){
$('#output').html(json.img);
$('#preview').html(json.msg);
}
}).submit();
In PHP
Return data like
echo json_encode(array('img'=>"<img src='...' />",'msg'=>"Message goes here"));
return;
you can use the -success: and the error: eventListner
$("#imageform").ajaxForm(
{
dataType:'json',
success:function(json){
write the success msg
}
error: function() {
write the error msg
}
}).submit();
Related
I have created a jQuery/AJAX script for file uploading and I handle the upload with PHP. It works perfectly with a progress bar and validations. There is one issue however, I cannot get any response text that I have set in PHP and encoded it using json_encode();, but don't get any response and get this instead:
<div class="upload-div">
<form method="post" enctype="multipart/form-data" class="upload_form" >
<label for="file" id="file_label" class="file-label"><i class="fa fa-plus"></i> إضافة صور<input type="file" name="files[]" id="file" multiple="" accept="image/*" /></label>
<input type="submit" id="upload_files" name="submitUpload" value="رفع الصور" />
</form>
<div class="progress">
<div class="bar"></div>
</div>
<div class="status-message"></div>
<div class="images-previews"></div>
<div id="next_step"></div>
<span class="submit-buttons">
<i class="fa fa-arrow-right"></i> الرجوع
<form method="post"><input type="submit" name="submitNoPics" value="التقدم بدون صورة" /></form>
</span>
</div>
<script src="js/upload.js"></script>
<script src="js/jquery.form.min.js"></script>
{"message":"Successfully uploaded 1 files!"}
As you can see the message I want to display is on the last line of code but it doesn't show alone. It shows with the whole HTML document. I will post my HTML and PHP code below, because I am new to Ajax and I am struggling. Please help me if you can and explain because I don't just want to get it done, I want to actually understand how and why this is not working. Thank you.
PHP:
<?php
//file upload
$extensions = array('jpeg', 'jpg', 'png', 'gif');
$dir = 'user-uploads/';
$count = 0;
$imgCounter = 1;
if ($_SERVER['REQUEST_METHOD'] == 'POST' and isset($_FILES['files'])){
for($x = 1; $x <= 8; $x++){
unlink('user-uploads/img'.$listingID.'-'.$x.'.jpg');
unlink('user-uploads/img'.$listingID.'-'.$x.'.png');
unlink('user-uploads/img'.$listingID.'-'.$x.'.gif');
}
mysqli_query($connectionDB, "DELETE FROM ad_image_tbl WHERE ad_id = $listingID");
// loop all files
foreach ( $_FILES['files']['name'] as $i => $name ){
// if file not uploaded then skip it
if ( !is_uploaded_file($_FILES['files']['tmp_name'][$i]) )
continue;
/* skip unprotected files
if( !in_array(pathinfo($name, PATHINFO_EXTENSION), $extensions) )
continue;
*/
switch($_FILES['files']['type'][$i]){
case 'image/jpeg' : $ext = '.jpg'; break;
case 'image/png' : $ext = '.png'; break;
case 'image/gif' : $ext = '.gif'; break;
default : $ext = '';
}
if($ext == ''){
echo errorMessage('<li>الملف المرفق لا يعتبر صورة</li>');
$error_message = 'الملف المرفق لا يعتبر صورة';
$message = array('message'=>'Attached file is not a valid image file.');
exit();
}
else{
// now we can move uploaded files
if($count <= 7 ){
$listingImage = $dir.'img'.$listingID.'-'.$imgCounter.$ext;
if( move_uploaded_file($_FILES["files"]["tmp_name"][$i], $listingImage))
mysqli_query($connectionDB, "INSERT INTO ad_image_tbl VALUES('$imgCounter', '$listingID', '$listingImage')");
$imgCounter++;
$count++;
}
}
}
$message = array('message'=>'Successfully uploaded '.$count.' files!');
echo json_encode($message);
}
?>
jQuery/AJAX:
$(function() {
/* variables */
var fileInput = document.getElementById('file');
var fileCount = fileInput.files.length;
if(fileCount > 8){
fileCount = 8;
}
var bar = $('.bar');
var progress = $('.progress');
/* submit form with ajax request using jQuery.form plugin */
$('.upload_form').ajaxForm({
/* set data type json */
dataType:'JSON',
/* reset before submitting */
beforeSend: function() {
bar.width('0%');
progress.css('display', 'block');
},
/* progress bar call back*/
uploadProgress: function(event, position, total, percentComplete) {
var pVel = percentComplete + '%';
bar.width(pVel);
},
/* complete call back */
complete: function(message){
// var responseMessage = $.parseJSON(data.responseText);
progress.css('display', 'none');
document.getElementById('next_step').innerHTML = '<form method="post"><input type="submit" name="uploadSubmit" value="الانتهاء" /></form>';
console.log(message)
}
});
});
Why could you use a plugin to handle upload.
dropzone.js
You can get response as below
$(function() {
Dropzone.options.uiDZResume = {
success: function(file, response){
alert(response);
}
};
});
Here is a code for uploading image using ajax. I have added jQuery library and jQuery form as well but this code neither gives me any error nor uploads image just uploading goes on and upload image starts running never to stop. Can't find whats wrong with this code.
upload.php
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').live('change', function() {
$("#preview").html('');
$("#preview").html('<img src="./img/loader.gif" alt="Uploading...."/>');
$("#imageform").ajaxForm({
target: '#preview'
}).submit();
});
});
</script>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajaximage.php'>
Upload your image <input type="file" name="photoimg" id="photoimg" />
</form>
ajaximage.php
<?php
include("/inc/connect.php");
if(isset($_SESSION['username'])) {
$username = $_SESSION['username'];
}
else if(isset($_COOKIE['username'])){
$username = $_COOKIE['username'];
}
else
{
//invalid ---
}
$path = "uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$sql=$db->prepare("UPDATE table SET profile_pic=:image_name WHERE username=:username");
$sql->execute(array(':image_name'=>$actual_image_name,':username'=>$username));
echo "<img src='uploads/".$actual_image_name."' class='preview'>";
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
?>
I have an ajax upload script which i will post below. It will upload any file with any extention. I want it to only upload .png files but i dont know how to do that.
Here are my files:
<h1>Ajax File Upload Demo</h1>
<form id="myForm" action="upload.php" method="post" enctype="multipart/form-data">
Name it:
<input type="text" name="upload_name">
<br>
<input type="file" size="60" name="myfile">
<input type="submit" value="Ajax File Upload">
</form>
<div id="progress">
<div id="bar"></div>
<div id="percent">0%</div >
</div>
<br/>
<div id="message"></div>
<script>
$(document).ready(function()
{
var options = {
beforeSend: function()
{
$("#progress").show();
//clear everything
$("#bar").width('0%');
$("#message").html("");
$("#percent").html("0%");
},
uploadProgress: function(event, position, total, percentComplete)
{
$("#bar").width(percentComplete+'%');
$("#percent").html(percentComplete+'%');
},
success: function()
{
$("#bar").width('100%');
$("#percent").html('100%');
},
complete: function(response)
{
$("#message").html("<font color='green'>"+response.responseText+"</font>");
},
error: function()
{
$("#message").html("<font color='red'> ERROR: unable to upload files</font>");
}
};
$("#myForm").ajaxForm(options);
});
</script>
PHP:
<?php
$upload_name = $_POST['upload_name'];
$idx = strpos($_FILES['myfile']['name'],'.');
$ext = substr($_FILES['myfile']['name'],$idx);
$file_name = $upload_name . $ext;
$output_dir = "uploads/";
if(isset($_FILES["myfile"]))
{
//Filter the file types , if you want.
if ($_FILES["myfile"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
//move the uploaded file to uploads folder;
// move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir. $_FILES["myfile"]["name"]);
// echo "Uploaded File :".$_FILES["myfile"]["name"];
move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$file_name);
echo "Uploaded File :" . $file_name;
}
}
?>
Sorry, i'm new and code blocks wont work for me. If someone could update, that would be great.
Client side
change your input file field this only works for modern browsers IE10+
Google Chrome 8.0+ and Firefox 4.0+
<input type="file" size="60" name="myfile" accept="image/png" />
PHP
$ext = pathinfo( $file_name , PATHINFO_EXTENSION );
if(strtolower($ext) == 'png' && $_FILES["file"]['type'] == "image/png")
{
// upload file
} else{
// not allowed
}
You can check file extension or mime type at server side.
// check extension
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
// return error
}
// or check file mime type
if (mime_content_type($_FILES['myfile']['name']) !== 'image/png') {
// return error
}
Example php:
$output_dir = "uploads/";
$upload_name = $_POST['upload_name'];
if(isset($_FILES["myfile"])) {
// Check upload errors
if ($_FILES["myfile"]["error"] > 0) {
echo "Error: " . $_FILES["file"]["error"] . "<br>";
return;
}
// Check extensions
$info = new SplFileInfo($_FILES['myfile']['name']);
if ($info->getExtension() !== 'png') {
echo "Error: Only .png files are allowed";
return;
}
// Upload file
$file_name = $upload_name . $info->getExtension();
move_uploaded_file($_FILES["myfile"]["tmp_name"], $output_dir . $file_name);
echo "Uploaded File :" . $file_name;
}
I've html form. Now i'm trying to upload file using php with ajax request. But I'm getting following error message when I upload the file by php with ajax request. is it my ajax request problem or anything ?
Notice: Undefined index: file in D:\Software Installed\xampp\htdocs\wix\users\insert_galary.php on line 16
html form:
<p>Add more</p>
<div id="dialog-modal2" title="Upload your galary image" style="display: none;">
<form method="post" action="insert_galary.php" id="myForm2" enctype="multipart/form-data" >
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>Upload image</td>
<td><input type="file" name="file" class="tr"/></td>
</tr>
</table>
</form>
<span id="result2"></span>
<script type="text/javascript">
$("#sub2").click( function() {
$.post( $("#myForm2").attr("action"),
$("#myForm2 :input").serializeArray(),
function(info){ $("#result2").html(info);
});
clearInput();
});
$("#myForm2").submit( function() {
return false;
});
</script>
</div>
function showDialog2()
{
$("#dialog-modal2").dialog(
{
width: 610,
height: 350,
open: function(event, ui)
{
var textarea = $('<textarea style="height: 276px;">');
$(textarea).redactor({
focus: true,
autoresize: false,
initCallback: function()
{
this.set('<p>Lorem...</p>');
}
});
}
});
}
Php form:
$gid = mt_rand(100000, 999999);
$file = $_FILES["file"]["name"];
$type = $_FILES["file"]["type"];
$size = ($_FILES["file"]["size"] / 1024);
$temp = $_FILES["file"]["tmp_name"];
$allowedExts = array("gif", "jpeg", "jpg", "png");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
$galary_pic = $gid.".".$extension;
$galary_directory = "../galary_images/";
$err = array();
if(isset($file))
{
if(empty($file))
$err[] = "Upload your picture";
elseif(!in_array($extension, $allowedExts))
$err[] = "Uploaded file must be gif, jpeg, jpg, png format";
elseif($size > 500)
$err[] = "Uploaded file must be within 500kb";
}
if(!empty($err))
{
echo "<div class='error'>";
foreach($err as $er)
{
echo "<font color=red>$er.</font><br/>";
}
echo "</div>";
echo "<br/>";
}
else
{
echo "sql query";
}
Note: I already submit this question last day but I can't get any proper answer. Sorry about it
You're not uploading a file but just making a POST request without any file attached. If you're looking for an ajax file uploader, try jquery file upload here
http://blueimp.github.io/jQuery-File-Upload
Am trying to upload an image to images folder using ajax but its not working
when i choose an image then the image should upload to my folder in local hard drive and further i will use that.
Please help me
My Code is :
SCRIPT
$(document).ready(function() {
$('#pathAbout,#path,#pathWork').change(function(){
if($(this).val() !=""){
$.ajax({
type: "POST",
url: "imageLoad.php",
data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",
success: function(msg){
alert(msg);
}
});
}
});
});
</script>
HTML
<form method="POST" action="tabs.php?page=HOME" enctype="multipart/form-data">
<table>
<tr>
<td><label>Choose Image</label></td>
<td><input type="file" id ="pathAbout" name="imgPath" /></td>
</tr>
</table>
</form>
PHP
if(!empty($_POST)) {
if((isset($_POST['name']) && $_POST['name'] != '') || (isset($_POST['type']) && $_POST['type'] != '') ||(isset($_POST['tmp_name']) && $_POST['tmp_name'] != ''))
{
$name = $_POST['name'];
$type = $_POST['type'];
$tmp_name = $_POST['tmp_name'];
$extension = strtolower(substr($name, strpos($name , '.') +1));
if(($extension == 'png' || $extension == 'jpeg' || $extension == "jpg")&&($type == "image/png" || $type == "image/jpeg" || $type == "image/jpg"))
{
$location = 'images/';
if(move_uploaded_file($tmp_name,$location."$name"))
{
echo "Loaded";
} else {
echo "Error occured";
}
} else {
echo "Unsupported file format";
}
} else {
echo "Please choose a file";
}
} else {
echo "No Information found";
}
This is my code but nothing is happening when i choose a file
If you want you can use Uploadify here you can also see demo and for sample code for eg-
$(function() {
$("#file_upload").uploadify({
'formData' : {'someKey' : 'someValue', 'someOtherKey' : 1},
'swf' : '/uploadify/uploadify.swf',
'uploader' : '/uploadify/uploadify.php',
'onUploadStart' : function(file) {
$("#file_upload").uploadify("settings", "someOtherKey", 2);
}
});
});
$("#image_upload2").uploadify(uploadifyBasicSettingsObj);
uploadifyBasicSettingsObj.onUploadSuccess = function(file, data, response)
{
$('.tempImageContainer2').find('.uploadify-overlay').show();
/* Here you actually show your uploaded image.In my case im showing in Div */
$('.tempImageContainer2').attr('style','background- image:url("../resources/temp/thumbnail/'+data+'")');
$('#hidden_img_value2').attr('value',data);
}
The HTML code:
<div class="boxWrapper tempImageContainer2" data-image-container-id="2">
<input type="file" accept="gif|jpg" name="image2" style="" id="image_upload2"/>
<input type="hidden" value="" name="image[]" id="hidden_img_value2">
<input type="hidden" name="upload_path" value="" id="upload_path2" class="upload_path">
<div class="uploadify-overlay">Change</div>
<a class="remove-pic-link" href="javascript:void(0)" style="display:none">Remove</a>
</div>
It is not possible to upload an image directly using AJAX, but there are some libraries that create dynamic iframes to accomplish this.
Check out this one, which I have used in several projects: valums.com/ajax-upload. It even comes with example serverside code for several PHP application frameworks.
You can't upload file using AJAX , you need to use a trick consisting a 'iframe' and the web form , also some javascript.
This link may help you.
HTML
<div class="field">
<label class="w15 left" for="txtURL">Logo:</label>
<img id="logoPreview" width="150px" height="150px" src='default.jpg' />
<input class="w60" type="file" name="txtURL" id="txtURL" />
</div>
JQuery
$('#txtURL').on('change', function(){
$.ajaxFileUpload({
type : "POST",
url : "ajax/uploadImage",
dataType : "json",
fileElementId: 'txtURL',
data : {'title':'Image Uploading'},
success : function(data){
$('#logoPreview').attr('src', data['path']);
},
error : function(data, status, e){
alert(e);
}
});
});
Ajax controller:
public function uploadImage()
{
$status = "";
$msg = "";
$filename='';
$file_element_name = 'txtURL';//Name of input field
if (empty($_POST['title'])){
$status = "error";
$msg = "Please enter a title";
}
if ($status != "error"){
$targetPath = ''.date('Y').'/'.date('m').'/';
if(!file_exists(str_replace('//','/',$targetPath))){
mkdir(str_replace('//','/',$targetPath), 0777, true);
}
$config['upload_path'] = $targetPath;
$config['allowed_types'] = 'jpg|png|jpeg';
$config['max_size'] = 150000;
$config['file_name']=time(); //File name you want
$config['encrypt_name'] = FALSE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
if(!$this->upload->do_upload($file_element_name)){
$status = 'error';
$msg = $this->upload->display_errors('', '');
}
else{
$data = $this->upload->data();
$filename = $targetPath.$data['file_name'];
}
//#unlink($_FILES[$file_element_name]);
}
echo json_encode(array('status' => $status, 'msg' => $msg,'path'=>$filename));
}
Add Ajaxfileupload.js
You can't upload an image directly using AJAX
The answer is in response to this:
data: "name = <?php echo $_FILES['imgPath']['name']; ?>&type=<?php echo $_FILES['imgPath']['type']; ?>&tmp_name=<?php echo $_FILES['imgPath']['tmp_name']; ?>",