File upload using jquery form plugin failure - php

I am trying to upload an image along with other form data to my database. I now have the following form:
<form method="post" action="newproduct.php" id="newproduct" enctype="multipart/form-data" >
<table>
<tr>
<td><label for="productName">Product Name:</label></td>
<td>
<input type="text" name='productName' id='productName' />
</td>
</tr>
<tr>
<td><label for="productNumber">Product Number:</label></td>
<td>
<input type="text" name='productNumber' id='productNumber' />
</td>
</tr>
<tr>
<td><label for="sflf"> SF / LF: </label></td>
<td>
<input type="text" name="sflf" id="sflf" />
</td>
</tr>
<tr>
<td><label for="file" >Image:</label></td>
<td>
<input type="file" name="file" id="file" />
</td>
</tr>
</table>
</form>
I am using the following jquery script to send the data to my newproduct.php file:
var options = {
target: '#message',
url:'newproduct.php',
beforeSubmit: function() {$('#uploader').html('<img src="loader.gif" border="0" />');},
success: function() {$('#uploader').html('New Product Was Successfully Added');}
};
var newProductDialog = $("#addProductDiv").dialog({
autoOpen: false,
title: "Add New Product",
modal: true,
width: 500,
show: { effect: 'drop',direction:"up",duration:1000 },
hide: { effect: 'drop',direction:"down",duration:1000 },
buttons: {
'Add':function() {
//submitNewProduct($("#newproduct"));
$("#newproduct").ajaxSubmit(options);
return false;
},
'Cancel':function() {
$(this).dialog('close');
$("#container").fadeTo('slow',1);
}
}
});
$("#loadNewProduct").click(function() {
newProductDialog.dialog('open');
$("#container").fadeTo('slow',.4);
return false;
});
And here is how my newproduct.php looks like:
include("../includes/database.php");
$path = "../images/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST))
{
$productNo = isset($_POST['productNumber']) ? $_POST['productNumber'] : "";
$productName = isset($_POST['productName']) ? $_POST['productName'] : "";
$sflf = isset($_POST['sflf']) ? $_POST['sflf'] : "";
$name = $_FILES['file']['name'];
$size = $_FILES['file']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(2048*2048))
{
$tmp = $_FILES['file']['tmp_name'];
if(move_uploaded_file($tmp, $path.$name))
{
$sql= "insert into inventory (productName,sfLf,image,time,productNo) values
('{$productName}','{$sflf}','{$name}',now(),'{$productNo}')";
$database->query($sql) or die(mysql_error()."Database Failed")
}
else echo "There Was A Problem Adding Your Product. Please Try Again"
}
else echo "Size Cannot Exceed 2 MB";
}
else echo "Invalid File Format";
}
}
However, I keep getting a 500 Internal Server Error, so I know that my newproduct.php has some issues that I cannot work around.
EDIT:
After debugging my newproduct.php, I figured out that move_uploaded_file() function causes this error and it is unable too upload the file for some reason. What could be wrong now?

Related

How to make the code continue the process if the file upload section is empty PHP MYSQLi

I have a problem with 1 part of upload section, how to make the code continue the process if the upload section is empty? I already make the code, but everytime i skip the file button, it show echo 'ERROR: Ekstensi file tidak di izinkan!'
Here is my code:
insert_form
<form name="pegawai" action="insert-proses.php" method="post" enctype="multipart/form-data">
<table width="700px" align="left" cellpadding="2" cellspacing="0">
<tr>
<td><b>NOKOM</b></td>
<td><b>:</b></td>
<td><input type="text" name="nokom" size="40" required /></td>
</tr>
<tr>
<td><b>NIP</b></td>
<td><b>:</b></td>
<td><input type="text" name="nip" size="40" required /></td>
</tr>
<tr>
<td><b>Nama</b></td>
<td><b>:</b></td>
<td><input type="text" name="nama" size="40" required /></td>
</tr>
<tr>
<td><b>Foto</b></td>
<td><b>:</b></td>
<td><input name="file" type="file" id="file" /></td>
</tr>
<tr>
<td></td>
<td></td>
<td><hr/><input type="submit" name="upload" value="Upload" /></td>
</tr>
</table>
</form>
insert-proses
<?php session_start();
include "config.php";
if(ISSET($_SESSION['superadmin'])) {
if($_POST['upload']) {
$nokom = $_POST['nokom'];
$nip = $_POST['nip'];
$nama = $_POST['nama'];
// Proses upload file
$allowed_ext = array('jpg', 'jpeg', 'png', 'gif');
$file_name = $_FILES['file']['name']; // Nama File
$file_ext = strtolower(end(explode('.', $file_name))); // Merubah nama file
$file_size = $_FILES['file']['size']; // Size File
$file_tmp = $_FILES['file']['tmp_name']; // Temp File
// Proses pengecekan upload file
if(in_array($file_ext, $allowed_ext) === true) {
if($file_size < 5220350) // Max upload file 5 MB / 1MB = 1044070 {
$lokasi = 'files/'.$nama.'.'.$file_ext;
move_uploaded_file($file_tmp, $lokasi);
$sql = "INSERT INTO pegawai (nokom,nip,nama,fileext,filegambar)
VALUES('$nokom','$nip','$nama','$file_ext','$lokasi')";
if (mysqli_query($conn, $sql)) {
echo "<script>alert('Insert data berhasil! Klik ok untuk melanjutkan');location.replace('pegawai-list.php')</script>";
}
else {
echo "Error updating record: " . mysqli_error($conn);
}
} else
{
echo '<div class="error">ERROR: Besar ukuran file (file size) maksimal 1 Mb!</div>';
}
} else
{
echo '<div class="error">ERROR: Ekstensi file tidak di izinkan!</div>';
}
}
} else
{
echo '<script>alert("Anda bukan Superadmin! Silahkan login menjadi Superadminterlebih dahulu");location.replace("index.php")</script>';
}
?>
Any help will be so thankful. Thanks
Jump over the complete upload part if there is no file uploaded, or better, run the upload part in your script only IF a file is uploaded:
if(isset($_FILES['file']) && is_array($_FILES['file'])) {
// your code to upload and check the file
}

unable to insert image into database

Unable to upload image into database. After submitting the form, I am getting this error:
There was an error uploading the data, please try again!
My code is given below please help me regarding this.
<?php
extract($_POST);
extract($_GET);
error_reporting(0);
?>
<html>
<head>
<!-- Date Picker Starts -->
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="js/script.js"></script>
<script>
$(document).ready(function() {
$(function() {
$(".datepicker").datepicker({ dateFormat: 'dd-mm-yy' });
});
});
</script>
<!-- Date Picker Ends -->
<script>
function getccname(val)
{
if(val == 'company')
{
document.getElementById("colname").disabled= true;
document.getElementById("course").disabled = true;
document.getElementById("year").disabled = true;
}
else if(val == 'college')
{
document.getElementById("comname").disabled = true;
document.getElementsByName("doj")[0].disabled= true;
document.getElementById("colname").disabled = false;
document.getElementById("course").disabled = false;
document.getElementById("year").disabled = false;
}
else
{
document.getElementById("comname").disabled = false;
document.getElementsByName("doj")[0].disabled= false;
document.getElementById("colname").disabled = false;
document.getElementById("course").disabled = false;
document.getElementById("year").disabled = false;
}
}
</script>
<!-- nice editor -->
<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">bkLib.onDomLoaded(nicEditors.allTextAreas);</script>
<!-- nice editor end -->
</head>
<body>
<?php
include("menu.php");
?><br>
<?php
include("database.php");
if(isset($_POST['submit']))
{
$uploadpath= 'upload/'; // directory to store the uploaded files
$max_size = 2000; // maximum file size, in KiloBytes
$alwidth = 900; // maximum allowed width, in pixels
$alheight = 800; // maximum allowed height, in pixels
$allowtype = array('bmp', 'gif', 'jpg', 'jpe', 'jpeg', 'png'); // allowed extensions
if(isset($_FILES['fileup']) && strlen($_FILES['fileup']['name']) > 1)
{
$timestamp = time();
$uploadpath = $uploadpath . $timestamp . basename( $_FILES['fileup']['name']); // gets the file name
$sepext = explode('.', strtolower($_FILES['fileup']['name']));
$type = end($sepext); // gets extension
list($width, $height)= getimagesize($_FILES['fileup']['tmp_name']); // gets image width and height
$err = ''; // to store the errors
// Checks if the file has allowed type, size, width and height (for images)
if(!in_array($type, $allowtype)) $err .= 'The file: <b>'. $_FILES['fileup']['name']. '</b> not has the allowed extension type.';
if($_FILES['fileup']['size'] > $max_size*1000) $err .= '<br/>Maximum file size must be: '. $max_size. ' KB.';
if(isset($width) && isset($height) && ($width >= $alwidth || $height >= $alheight)) $err .= '<br/>The maximum Width x Height must be: '. $alwidth. ' x '. $alheight;
// If no errors, upload the image, else, output the errors
if(is_uploaded_file($_FILES['fileup']['name']))
{
move_uploaded_file( $_FILES['fileup']['tmp_name'], $uploadpath) ;
$file =$uploadpath;
$name =$_POST["name"];
$fname =$_POST["fname"];
$gender =$_POST["gender"];
$email =$_POST["email"];
$date =$_POST["date"];
$mn =$_POST["mn"];
$pn =$_POST["pn"];
$address=$_POST["address"];
$idnum =$_POST["idnum"];
$ccname =$_POST["ccname"];
$colname=$_POST["colname"];
$course =$_POST["course"];
$year =$_POST["year"];
$comname=$_POST["comname"];
$doj =$_POST["doj"];
$result=mysql_query("insert into registration(file,name,fname,gender,email,date,mn,pn,address,idnum,ccname,colname,course,year,comname,doj)
values('$uploadpath','$name','$fname','$gender','$email','$date','$mn','$pn','$address','$idnum','$ccname','$colname','$course','$year','$comname','$doj')");
print_r($result);
echo "Inserted Successfully";
}
}
else
{
echo "There was an error uploading the data, please try again!";
}
}
?>
<form name="form" method="post" action="" onSubmit="submit;">
<center><table border="1" cellspacing="0" style="width:500px">
<tr>
<td><b>Image</td> <td><input type="file" name="fileup" id="fileup" size="25" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td></tr>
<tr>
<td>Father Name</td>
<td><input type="text" name="fname"></td></tr>
<tr><td>Gender</td>
<td><select name="gender">
<option value ="na">Select</option>
<option value ="Male">Male</option>
<option value ="Female">Female</option>
</td></tr>
<tr>
<td>Email</td>
<td><input type="text" name="email"></td></tr>
<tr>
<td>Date Of Birth</td>
<td><input type="text" name="date" class="datepicker" required></td></tr>
<tr>
<td>Mobile Number</td>
<td><input type="text" name="mn"></td></tr>
<tr>
<td>Parent Number</td>
<td><input type="text" name="pn"></td></tr>
<tr>
<td>Address</td> <td><textarea name="address" rows="3" cols="50"></textarea></td>
</tr>
<tr>
<td>Coll/Comp ID Num</td>
<td><input type="text" name="idnum"></td></tr>
<tr><td>Company/College</td>
<td><select name="ccname" onchange="getccname(this.value);">
<option value ="na">Select</option>
<option value ="company">Company</option>
<option value ="college">College</option>
</td></tr>
<tr>
<td>College Name</td>
<td><input type="text" name="colname" id="colname"></td></tr>
<tr>
<td>Course</td>
<td><input type="text" name="course" id="course"></td></tr>
<tr>
<td>Year</td>
<td><input type="text" name="year" id="year"></td></tr>
<tr>
<td>Company Name</td>
<td><input type="text" name="comname" id="comname"></td></tr>
<tr>
<td>Date Of Join</td>
<td><input type="text" name="doj" class="datepicker"></td></tr>
<tr>
<td colspan="2" align="center"><input class="button" type="submit" name="submit" value="submit"/>
<input class="button" type="reset" name="Reset" value="Reset " /> </td>
</tr></center>
</table>
</form>
</body>
</html>
try this,Then include your insert query it will work enctype="multipart/form-data"
<form name="form" method="post" action="" onSubmit="submit;" enctype="multipart/form-data">
</form>
<?php
if(isset($_FILES['image']))
{
$errors= array();
$file_name = $_FILES['image']['name'];
$file_size =$_FILES['image']['size'];
$file_tmp =$_FILES['image']['tmp_name'];
$file_type=$_FILES['image']['type'];
$value = explode(".", $file_name);
$file_ext = strtolower(array_pop($value));
//$file_ext=strtolower(end(explode(".",$file_name))); -->this line wnt work bcoz only variable should be passed inside explode
$expensions= array("jpeg","jpg","png","csv");
if(in_array($file_ext,$expensions)== false)
{
$errors="Extension not allowed, please choose a JPEG or PNG file.";
}
if($file_size > 2097152)
{
$errors[]='File size must be excately 2 MB';
}
if(empty($errors)==true)
{
move_uploaded_file($file_tmp,"upload/".$file_name);
**//include here insert query**
echo "Success";
}else
{
print_r($errors);
}
}
?>
1st. do not use mysql_* functions, use mysqli_* instead.
2nd. This is a very big security hole, if accept any data.
3rd. Whay do you create variables like this? $name=$_POST["name"];
So, when you want to insert the $_POST["name"] do something like this:
EDIT:
Try this. It will die, and will print out the query string for you. Try to copy that directly into the mysql, and comment the result.
function dbEscape($str) {
return mysql_real_escape_string($str);
}
$sql = "INSERT INTO registration(file,name,fname,gender,email,date,mn,pn,address,idnum,ccname,colname,course,year,comname,doj)
VALUES ('".dbEscape($uploadpath)."','". dbEscape($_POST["name"])."','". dbEscape($_POST['fname'])."','". dbEscape($_POST['genred'])."','". dbEscape($_POST['email'])."','". dbEscape($_POST['date'])."','". dbEscape($_POST['mn'])."','". dbEscape($_POST['pn'])."','". dbEscape($_POST['address'])."','". dbEscape($_POST['idnum'])."','". dbEscape($_POST['ccname'])."','". dbEscape($_POST['colname'])."','". dbEscape($_POST['course'])."','". dbEscape($_POST['year'])."','". dbEscape($_POST['comname'])."','". dbEscape($_POST['doj'])."')";
die($sql);
$result = mysql_query($sql);
Your form does not contain enctype="multipart/form-data" and is an essential part of uploading files.
Modify your form to read as:
<form name="form" method="post" enctype="multipart/form-data" action="" onSubmit="submit;">
that is the reason why your upload does not work.

uploading two images simultaneously and in one row php pdo

<form method="POST" action="crud.php" enctype="multipart/form-data" >
<div style="background-color:#252323; color:#FFFFFF; "><b>Image Gallery</b></div>
<table>
<tr>
<td valign="top">
<label for="description">Big Image</label>
</td>
<td valign="top" style="text-align:right">
<input type="file" name="image" /></br>
</td>
</tr>
<tr>
<td valign="top">
<label for="description">Thumbnail Image</label>
</td>
<td valign="top" style="text-align:right">
<input type="file" name="image" /></br>
</td>
</tr>
</table>
<input id="button" type="submit" value="Add" name="imagegalleryadd"/>
</form>
This is my form it has two upload images with one button i want to upload two images at the same time and put them in two separate column in the datase because i will use these two images in a slider one for big image and other for thumbnail i tried upload only one images and it was good but how do you upload two images at the same time this is my code for adding images. This code only uploads one images how can it be changed to upload two?
function AddImageGallery(){
global $dbh;
if(is_uploaded_file($_FILES["image"]['tmp_name'])){
$folder = "images/imagegallery/";
$file = basename( $_FILES['image']['name']);
$full_path = $folder.$file;
if(move_uploaded_file($_FILES['image']['tmp_name'], $full_path)) {
echo "succesful upload, we have an image!";
$stmt = $dbh->prepare("INSERT INTO imagegallery (imggall_imageurl) VALUES (?)");
$stmt->bindValue(1,$full_path,PDO::PARAM_STR);
if($stmt->execute()){
echo "Image Recorded";
}else{
echo "Image was not Recorded";
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
}
database will look like this
$sql ="CREATE TABLE IF NOT EXISTS $imagegallery (
imggall_id int(40) NOT NULL AUTO_INCREMENT PRIMARY KEY,
imggall_imageurl VARCHAR(1000) NOT NULL,
imggall_thumnailurl VARCHAR(1000) NOT NULL);" ;
$dbh->exec($sql);
UPDATE
new code i tried
function AddImageGallery(){
global $dbh;
if(is_uploaded_file($_FILES["bigimage"]['tmp_name'] && $_FILES["thumbnailimage"]['tmp_name'] )){
$folder = "images/imagegallery/";
$filebi = basename( $_FILES['bigimage']['name']);
$fileti = basename( $_FILES['thumbnailimage']['name']);
$fileti = basename( $_FILES['thumbnailimage']['name']);
$fullbi_path = $folder.$filebi;
$fullti_path = $folder.$fileti;
if(move_uploaded_file($_FILES['bigimage']['tmp_name'], $fullbi_path && $_FILES['thumbnailimage']['tmp_name'], $fullti_path )) {
echo "succesful upload, we have an image!";
$stmt = $dbh->prepare("INSERT INTO imagegallery (imggall_imageurl,imggall_thumnailurl) VALUES (?,?)");
$stmt->bindValue(1,$fullbi_path,PDO::PARAM_STR);
$stmt->bindValue(2,$fullti_path,PDO::PARAM_STR);
if($stmt->execute()){
header("Location: dashboard.php");
exit;
echo "Image Recorded";
}else{
echo "Image was not Recorded";
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
}
<form method="POST" action="crud.php" enctype="multipart/form-data" >
<div style="background-color:#252323; color:#FFFFFF; "><b>Image Gallery</b></div>
<table>
<tr>
<td valign="top">
<label for="description">Big Image</label>
</td>
<td valign="top" style="text-align:right">
<input type="file" name="bigimage" /></br>
</td>
</tr>
<tr>
<td valign="top">
<label for="description">Thumbnail Image</label>
</td>
<td valign="top" style="text-align:right">
<input type="file" name="thumbnailimage" /></br>
</td>
</tr>
</table>
<input id="button" type="submit" value="Add" name="imagegalleryadd"/>
</form>
Quick Google:
http://php.net/manual/en/features.file-upload.multiple.php#53240
Shows a clear and simple method for multiple image uploads.
Quote:
function reArrayFiles(&$file_post) {
$file_ary = array();
$file_count = count($file_post['name']);
$file_keys = array_keys($file_post);
for ($i=0; $i<$file_count; $i++) {
foreach ($file_keys as $key) {
$file_ary[$i][$key] = $file_post[$key][$i];
}
}
return $file_ary;
}
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['ufile']);
foreach ($file_ary as $file) {
print 'File Name: ' . $file['name'];
print 'File Type: ' . $file['type'];
print 'File Size: ' . $file['size'];
}
}
For you:
<form method="POST" action="crud.php" enctype="multipart/form-data" >
<input type="file" name="image[]" />
<input type="file" name="image[]" />
<input id="button" type="submit" value="Add" name="imagegalleryadd"/>
</form>
Then using the earlier function linked
if ($_FILES['upload']) {
$file_ary = reArrayFiles($_FILES['ufile']);
$main = $file_ary[0]['name'];
$thumb = $file_ary[1]['name'];
// Upload to DB
}
<form method="POST" action="crud.php" enctype="multipart/form-data" >
<div style="background-color:#252323; color:#FFFFFF; "><b>Image Gallery</b></div>
<table>
<tr>
<td valign="top">
<label for="description">Big Image </label>
</td>
<td valign="top">
<input type="file" name="bigimage" /></br>
</td>
</tr>
<tr>
<td valign="top">
<label for="description">Thumbnail Image </label>
</td>
<td valign="top">
<input type="file" name="thumbnailimage" /></br>
</td>
</tr>
</table>
<input id="button" type="submit" value="Add" name="imagegalleryadd"/>
</form>
function AddImageGallery(){
global $dbh;
if(is_uploaded_file($_FILES["bigimage"]['tmp_name'] )){
$folder = "images/imagegallery/";
$filebi = basename( $_FILES['bigimage']['name']);
$fileti = basename( $_FILES['thumbnailimage']['name']);
$fileti = basename( $_FILES['thumbnailimage']['name']);
$fullbi_path = $folder.$filebi;
$fullti_path = $folder.$fileti;
if(move_uploaded_file($_FILES['bigimage']['tmp_name'], $fullbi_path)) {
if(move_uploaded_file($_FILES['thumbnailimage']['tmp_name'], $fullti_path )) {
echo "succesful upload, we have an image!";
$stmt = $dbh->prepare("INSERT INTO imagegallery (imggall_imageurl,imggall_thumnailurl) VALUES (?,?)");
$stmt->bindValue(1,$fullbi_path,PDO::PARAM_STR);
$stmt->bindValue(2,$fullti_path,PDO::PARAM_STR);
if($stmt->execute()){
header("Location: dashboard.php");
exit;
echo "Image Recorded";
}else{
echo "Image was not Recorded";
}
}
} else {
echo "upload received! but process failed";
}
}else{
echo "upload failure ! Nothing was uploaded";
}
}
anyone can try this out i was able to get what
If one is having difficulties with sending more than 1 image to .php it is crucial to put [] in the end of your name of input.
Thought I should mention that sine I spend last few hours wondering why PHP is not detecting more than 1 file.

I can't get $_FILE['file']['name'] value with ajax request

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

PHP Image Upload Via JQUERY

I'm trying to pass form data (Avatar & User ID) through a jQuery POST command, but it won't upload the file. Can someone please point me in the right direction as to what I might be doing wrong? Here is the form and script:
<form id="avatar">
<script>
$(document).ready(function()
{
var ok = true;
$('#avatarButton').click(function()
{
var id=$("#id").val();
var avatar = $("#avatar").val();
if(ok == true)
{
$('.avatarValidation').html("Uploading Avatar").removeClass("error").addClass("success");
jQuery.post("php/<?php echo $usertype; ?>/avatar.php", {
id:id,
avatar:avatar
}, function(data, textStatus){
if(data == 1){
$('.avatarValidation').html("Profile Updated").removeClass("error").addClass("success");
}
else if(data == 2){
$('.avatarValidation').html("Error").removeClass("success").addClass("error");
}
});
}
else
{
$('.avatarValidation').html("No").removeClass("success").addClass("error");
}
return false;
});
});
</script>
<table>
<tr>
<td class="textColumn profileColumn">Add Avatar:</td>
<td class="profileInput inputColumn"><input type="file" id="avatar" name="avatar" value="<?php echo $yourname; ?>"/></td>
</tr>
<tr>
<td colspan="2"><input type="hidden" name="id" id="id" value="<?php echo $yourid; ?>"></td>
</tr>
<tr class="buttonSpacer"></tr>
<tr>
<td colspan="2">
<input type="submit" class="submitButton" id="avatarButton" value="Upload Avatar" />
<span class="submitValidation avatarValidation"></span>
</td>
</tr>
</table>
</form>
And here is the PHP to which the form data is passed to:
<?php
$id= mysqli_real_escape_string($con, $_REQUEST["id"]);
$avatar= mysqli_real_escape_string($con, $_REQUEST["avatar"]);
if ($_FILES['$avatar']['error'] > 0) {
echo "2"; //Echo Error
} else {
// array of valid extensions
$validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
// get extension of the uploaded file
$fileExtension = strrchr($_FILES['$avatar']['name'], ".");
// check if file Extension is on the list of allowed ones
if (in_array($fileExtension, $validExtensions)) {
$newName = time() . '_' . $_FILES['$avatar']['name'];
$destination = 'avatar/' . $newName;
if (move_uploaded_file($_FILES['$avatar']['tmp_name'], $destination)) {
echo "1"; //Echo Success
}
} else {
echo "2"; //Echo Error
}
}
?>
You can try this plugin, it will take care of most of background work for you. They have PHP samples as well:
http://blueimp.github.io/jQuery-File-Upload/

Categories