Can I use jquery post with image uploads? - php

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.

Related

Click image , that will show on a new tab with 100% width

Hi every one i have make some php pages that is about web design presenter, and my problem is that, i receive image from user and save it into a folder and show all the saved images with href image link but , when i click on a image it will open only image in browser not in any page.
how to resolve this issue kindly help me.
my code is .
<html>
<head>
<link rel="stylesheet" type="css/text" href="style.css">
<title>Uploading Files via PHP</title>
</head>
<body>
<center><form action="file.php" method="post" enctype="multipart/form-data">
<table border="2">
<tr height="100"><td>Upload A file:</td>
<td><input type="file" name="file"></td></tr>
<tr height="100"><td>Click Upload File:</td><td><input type="submit" name="submit" value="Upload File"></td></tr>
</table>
</form></center>
<?php
if (isset($_POST['submit'])) {
$name=$_FILES['file']['name'];
$type=$_FILES['file']['type'];
$size=$_FILES['file']['size'];
$tmp=$_FILES['file']['tmp_name'];
if ($name==''){
echo "<script>alert('Please Select a file from computer!')</script>";
exit();
}
if (($type == "image/jpeg") || ($type == "image/gif") || ($type == "image/png")) {
if (file_exists("images/" . $_FILES["file"]["name"])) {
echo "This file $name is already exist!<br> please try another one..";
exit();
}
if ($size <= 50000){
move_uploaded_file($tmp,"images/$name");
echo "<center><font color=red>File was uploaded successfully!</font><br>Uploaded Image is here<br><img src='images/$name'> </center>";
}
else {
echo "Size of the image $size is larger than 50kb and it's not allowed... <br> image size must be less than 50kb..";
}
}
else {
echo "$type this is not a valid type of file<br>only upload Jpeg, PNG and Gif images";
}
}
?>
<div class="container">
<div class="row">
<?php
$files = glob("images/*.*");
for ($i=0; $i<count($files); $i++)
{
$num = $files[$i];
echo '<div class="col-sm-4"><img src="'.$num.'" alt="random image" class="demo"/></div>';
}
?>
</div>
</div>
<script>
function fullwin(){
window.open("bigpage.php","bfs","fullscreen,scrollbars")
}
</script>
</body>
</html>

How to upload the audio file using php

i wanted to upload the mp3 file to the related folder name /uploads/ inside my project folder. But something not working correctly in php. Image file are uploading without any error but when i tried to upload the mp3 file its not working.
Here is my html form
<form action="act_songs.php" method="post" enctype="multipart/form-data">
<?php
if (isset($_SESSION['msg'])) {
echo $_SESSION['msg'];
unset($_SESSION['msg']);
}
?>
<p>
<label>Song Title</label>
<input type="text" name="sng-title">
</p>
<p>
<label>Song Name</label>
<input type="file" name="mp3" accept="audio/*" runat="server">
</p>
<p>
<input type="submit" name="add-song" value="ADD">
</p>
</form>
And here is my php code
if (isset($_POST['add-song'])) {
$title = $_POST['sng-title'];
$audio = $_FILES['mp3']['name'];
$audio_type = $_FILES['mp3']['type'];
$audio_size = $_FILES['mp3']['size'];
$tmp_location = $_FILES['mp3']['tmp_name'];
$audio_url = "../uploads/".$audio;
if ($type == '.mp3' || $type == '.wav') {
if ($size <= 5000) {
move_uploaded_file($tmp_location, $audio_url);
}
}
if (!empty($title)) {
$sql = "insert into `tbl_songs` (`title`,`songs`) values ('$title','$audio_url')";
$sql_run = mysql_query($sql);
if ($sql_run) {
$_SESSION['msg'] = "<div class='alert'>Record Saved</div>";
header('location:songs.php');
}
else{
$_SESSION['msg'] = "<div class='alert'>Record Cannot Saved</div>";
header('location:add-songs.php?invalid');
}
}
else{
$_SESSION['msg'] = "<div class='alert'>Title Must be requiired.</div>";
header('location:add-songs.php?invalid');
}
}
What is the problem i am unable to debug the problem. If anybody have solution then place your answer

image uploading locally, but not after hosted

image uploading is successful in locally. But after hosting, it's not working.
$imgname=$_FILES["imgfile"]["name"];
if($imgname!=''){
if ((($_FILES["imgfile"]["type"] == "image/jpeg")
|| ($_FILES["imgfile"]["type"] == "image/jpg"))
&& ($_FILES["imgfile"]["size"] < 200000))
{
list($img)=explode("#",$mail); $img=$img.".jpg";
$extension=end(explode(".", $_FILES["imgfile"]["name"]));
move_uploaded_file($_FILES["imgfile"]["tmp_name"],"dpstaff/".$img);
} else { ?> <script type="text/javascript"> alert(" Type mismatch or Exceed Size "); window.location = "reg2.php"; </script> <?php }
} else { ?> <script type="text/javascript"> alert(" No Image Selected "); window.location = "reg2.php"; </script> <?php }
header("location:staf2.php");
}
else
{ ?>
<script type="text/javascript">
alert("Exist same value (mobile no.)");
</script>
<?php
}
and html code is :
<form method="post" action="staf1.php" enctype="multipart/form-data" >
<tr>
<td> Photo </td>
<td> <input type="file" name="imgfile" id="imgfile" <?php if(!(isset($_GET["edit"]))) echo "required"; ?> />
<mandatory>( < 200KB , jpg format) </mandatory></td>
</tr>
</form>
and there is one more problem, the message is not displaying.

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