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
Related
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 am trying to upload an image using ajax form. Image upload is success. But the ajax response getting alerted automatically with a blank popup saying 'The page at www.xxx.com says'.
Here is my jQuery code
$('#profileImg').die('click').live('change', function()
{
$("#profileform").ajaxForm({target: '#preview_profile',
beforeSubmit:function(){
$("#profileloadstatus").show();
$("#profileloadbutton").hide();
},
success:function(s){
$("#profileloadstatus").hide();
$("#profileloadbutton").show();
},
error:function(){
$("#profileloadstatus").hide();
$("#profileloadbutton").show();
$('#profileform').reset();
} }).submit();
if(!s)
{
$("#profileform")[0].reset();
}
});
HTML FORM
<div id="preview_profile"></div><form id="profileform" method="post" enctype="multipart/form-data" action='message_profile_ajax.php'>
<div id="preview_prof"></div>
<div id="profileloadstatus" style="display:none; text-align:center;">
<img src='images/wall_icons/ajaxloader.gif'/> Uploading....
</div>
<div id="profileloadbutton">
<input type="file" id="profileImg" name="profileImg">
</div>
<input type="hidden" id="profvalues" value="" />
</form>
Php code
<?php
include_once 'includes.php';
function getExtension($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
function getImangeName($str)
{
$i = strrpos($str,".");
if (!$i) { return ""; }
$l = strlen($str) - $i;
$ext = substr($str,0,$i-1);
return $ext;
}
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['profileImg']['name'];
$size = $_FILES['profileImg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
$imageName = getImangeName($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = $imageName.time().$uid.".".$ext;
$tmp = $_FILES['profileImg']['tmp_name'];
if(move_uploaded_file($tmp, $profile_path.$actual_image_name))
{
$data=$Wall->Profile_Image_Upload($uid,$actual_image_name);
if($data)
{
echo '<img src="'.$profile_path.$actual_image_name.'" class="img-circle" alt="User Image" />';
}
}
else
{
echo '<b>Sorry, </b>Falied to upload your file!';
}
}
else
echo '<b>Sorry, </b>Image file size must be less than 1 MB!';
}
else
echo '<b>Sorry, </b>Invalid file format!';
}
else
echo '<b>Sorry, </b>Please select image..!';
exit;
}
?>
Please help,
Thank you
Check jquery.wallform.js
//return data;
// Modification www.9lessons.info
var exp = /<img[^>]+>/i;
expResult = data.match(exp);
if(expResult == null) {
alert(data);
} else {
$(options.target).prepend(data);
}
$("#photoimg").val('');
// Modification End www.9lessons.info
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();
I'm trying to use jquery to submit my form like so but it's not triggering anything in the functions.php file. Do I need to do anything special with a multipart/form-data? Am I missing something?
HTML:
<form id="process_image_form" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER['PHP_SELF'], ENT_QUOTES); ?>" method="post" >
<input type="hidden" name="image_id1" id="image_id1" />
<table class="bordered-table">
<tbody>
<tr>
<td><input name="file" type="file" id="file"/></td>
</tr>
<tr>
<td><button type="submit" class="btn primary" data-loading-text="Uploading..." id="upload_profile_photo" name="upload_profile_photo">Upload</button></td>
</tr>
</tbody>
</table>
</form>
Jquery call:
$('#upload_profile_photo').click(function(e) {
e.preventDefault();
$.post('gallery/functions.php', $("#process_image_form").serialize(), function(status) {
if (status.st) {
alert("Photo Uploaded");
}
}, "json");
});
functions.php:
if (isset($_POST['upload_profile_photo'])) {
if (isset($_FILES['file']) && $_FILES['file']['size'] > 0) {
//handle file upload
$size = filesize($_FILES['file']['tmp_name']);
if ($size > $max_file_size * 1024 * 1024) {
$res->error = '<div class="alert-message error">Your image file is too large. Reduce its size and try uploading again.</div>';
echo json_encode($res);
exit();
}
if ($res->error == "") {
//process image
$res = uploadImage($_FILES['file']['tmp_name'], $user_id);
if ($res->st) {
unlink($_FILES['file']['tmp_name']);
$res->msg = '<div class="alert-message success">Your profile photo was uploaded successfully!</div>';
echo json_encode($res);
exit();
}
}
}
else {
$res->error = '<div class="alert-message error">Please select a photo to upload.</div>';
echo json_encode($res);
exit();
}
}
jquery serialize method will not work on file inputs. Look here please: How can I upload files asynchronously?
I have a great experience with jquery file upload plugin for this purpose.