We are working on our own MVC framework and on edit if we unchange the image, image changes to default. We don't want image to change in edit mode unless image is re selected.
Our code is as follows:
HTML (View)
<form id="form-category" class="form-horizontal" action="<?php $_SERVER['PHP_SELF']; ?>" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label class="col-sm-2 control-label">Image</label>
<div class="col-sm-10">
<a href="" id="thumb-image" data-toggle="image" class="img-thumbnail">
<img src="<?php echo HTTP_HOST ?>/image/<?php echo $data['industry_image']; ?>" alt="<?php echo $data['industry_name']; ?>" title="<?php echo $data['industry_name']; ?>" data-placeholder="<?php echo HTTP_HOST ?>/image/<?php echo $data['placeholder']; ?>" width="100" height="100">
<input type="hidden" name="delete_image" value="<?php echo $data['industry_image']; ?>">
</a>
<input type="file" class="hidden" name="industry_image" value="<?php echo $data['industry_image']; ?>" id="input-image" onchange="readURL(this);">
</div>
</div>
</form>
jQuery for displaying image on file select
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#thumb-image').children('img').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
jQuery for Bootstrap Popover
$(document).on('click', 'a[data-toggle=\'image\']', function(e) {
var $element = $(this);
var $popover = $element.data('bs.popover'); // element has bs popover?
e.preventDefault();
// destroy all image popovers
$('a[data-toggle="image"]').popover('destroy');
// remove flickering (do not re-add popover when clicking for removal)
if ($popover) {
return;
}
$element.popover({
html: true,
placement: 'right',
trigger: 'manual',
content: function() {
return '<button type="button" id="button-image" class="btn btn-primary"><i class="fa fa-pencil"></i></button> <button type="button" id="button-clear" class="btn btn-danger"><i class="fa fa-trash-o"></i></button>';
}
});
$element.popover('show');
$('#button-image').on('click', function() {
$('#input-image').trigger('click');
// $element.parent().find('input').attr('value', '');
$element.popover('destroy');
});
$('#button-clear').on('click', function() {
$element.find('img').attr('src', $element.find('img').attr('data-placeholder'));
$element.parent().find('input').attr('value', '');
//alert($('#input-image').attr('value', ''));
$element.popover('destroy');
});
});
Controller
$data = [
'industry_image' => isset($_POST['industry_image'] ? $_POST['industry_image'] : NULL
]
if(empty($_FILES['industry_image']['size'])) {
$data['industry_image'] = 'no-image.png';
} else {
$file = $_FILES['industry_image'];
$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];
$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));
$allowed = array('gif', 'jpg', 'jpeg', 'png');
$allowedFileSize = 2000000;
if(in_array($fileActualExt, $allowed)) {
if($fileError === 0) {
if($fileSize < $allowedFileSize) {
$fileNameNew = strtolower($data['industry_name']) . "." . $fileActualExt;
$fileDestination = DIR_IMAGE . 'industries/' . $fileNameNew;
$filePath = 'industries/' . $fileNameNew;
if(array_key_exists('delete_image', array($data['industry_image']))) {
if(file_exists($filePath)) {
unlink($filePath);
}
}
$moveResult = move_uploaded_file($fileTmpName, $fileDestination);
if($moveResult != true) {
echo "Error: File Upload Failed. Try again.";
unlink($fileTmpName);
exit;
} else {
if(file_exists($fileNameNew)) {
flash("file_alert alert-danger", "File already exists");
} else {
$data['industry_image'] = $filePath;
}
}
} else {
flash("file_alert alert-danger", "File size is $fileSize of $allowedFileSize");
}
} else {
flash("file_alert alert-danger", "Error uploading the file");
}
} else {
$a = "Please upload only ";
foreach($allowed as $ext) {
$a .= '<b>' . $ext . '</b>' . ', ';
}
$a .= " extensions";
flash("file_alert alert-danger", $a);
}
}
if($this->model->getIndustries($industry_id, $data) {
redirect("catalog/industries", $data);
} else {
redirect("catalog/industries_form", $data);
}
Model
public function editIndustry($industry_id, $data) {
# Prepare Query for category
$this->db->query("UPDATE industry SET industry_name = :industry_name, industry_description = :industry_description, sort_order = :sort_order, status = :status WHERE industry_id = '" . $industry_id ."'");
# Bind Values
$this->db->bind(':industry_name', $data['industry_name']);
$this->db->bind(':industry_description', $data['industry_description']);
$this->db->bind(':sort_order', $data['sort_order']);
$this->db->bind(':status', $data['status']);
# Execute
$this->db->execute();
if(isset($data['industry_image'])) {
$this->db->query("UPDATE industry SET industry_image = :image WHERE industry_id = '" . $industry_id . "'");
$this->db->bind(":image", $data['industry_image']);
//$this->db->execute();
}
# Execute
if($this->db->execute()) {
return $industry_id;
} else {
return false;
}
}
Bootstrap popover image
Above code works but as mentioned earlier, image gets updated even if we don't select on POST. If the image is unedited, same image should go to database. If we clear the database with the red delete button, value gets clear from input tag should send no-image.png to the database.
Hope, I could explain my problem and looking for a solution from you'll awesome guys.
Thank you.
Related
I'm not familiar with ajax and I'm trying to submit a form using one PHP page and ajax so that after form is submitted/updated the page doesn't refresh completly. the php page is loaded on a div section of a parent page.
Can someone point me in the right direction how to submit the form without refreshing the entire page?
Below the code I have so far, and it is only all in one php file. Thank you
<?php
$servername = "data";
$username = "data";
$password = "data";
$database = "data";
$successAdd="";
$errorAdd="";
$connect = mysql_connect($servername, $username, $password) or die("Not Connected");
mysql_select_db($database) or die("not selected");
if (isset($_POST['Add'])) {
$venueName = $_POST['cname'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png');
if (in_array($file_ext, $allowed)) {
if ($file_error == 0) {
$file_name_new = $venueName . '.' . $file_ext;
$file_destination = 'images/category/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$sql = "INSERT INTO `categorytable`(`category`) VALUES ('$venueName')";
$result = mysql_query($sql, $connect);
if ($result != 0) {
$successAdd = "Success fully done";
} else {
$errorAdd = "Not done ";
}
}
} else {
$errorAdd = "Something is wrong";
}
} else {
$errorAdd = "Only png file allowed";
}
}
if (isset($_POST['Update'])) {
$venueName = $_POST['cname'];
$file = $_FILES['file'];
$file_name = $file['name'];
$file_tmp = $file['tmp_name'];
$file_size = $file['size'];
$file_error = $file['error'];
$file_ext = explode('.', $file_name);
$file_ext = strtolower(end($file_ext));
$allowed = array('png');
if (in_array($file_ext, $allowed)) {
if ($file_error == 0) {
$file_name_new = $venueName . '.' . $file_ext;
$file_destination = 'images/category/' . $file_name_new;
if (move_uploaded_file($file_tmp, $file_destination)) {
$successAdd = "Success fully done";
}else{
$errorAdd = "Not Updated";
}
} else {
$errorAdd = "Something is wrong";
}
} else {
$errorAdd = "Only png file allowed";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
<h3 style="color: red"><?php echo $errorAdd; ?></h3>
<h3 style="color: green"><?php echo $successAdd; ?></h3>
<!--<div style="float: left;width: 50%">-->
<h1>Add Category</h1>
<form action="" method="POST" enctype="multipart/form-data" id="add-category" >
Category Name <input type="text" name="cname" value="" /><br/>
Category Image <input type="file" name="file" accept="image/x-png"/><br/>
<input type="submit" value="Add" name="Add"/>
</form>
<!--</div>-->
<!--<div style="float: left;width: 50%">-->
<h1>Update Category</h1>
<form action="addCategory.php" method="POST" enctype="multipart/form-data" >
Select Category<select name="cname">
<?php
$sql = "SELECT * FROM `categorytable`";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<option value="<?php echo $row[1]; ?>"><?php echo $row[1]; ?></option>
<?php } ?>
</select><br/>
Category Image <input type="file" name="file" accept="image/x-png"/><br/>
<input type="submit" value="Update" name="Update"/>
</form>
<!--</div>-->
<div style="width: 25%;margin: 20px auto;float: left">
<table border="1">
<tr>
<th>Category Name</th>
<th>Category Image</th>
</tr>
<?php
$sql = "SELECT * FROM `categorytable`";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
?>
<tr>
<td><?php echo $row[1]; ?></td>
<td>
<img src="images/category/<?php echo $row[1]; ?>.png" height="50"/>
</td>
</tr>
<?php
}
?>
</table>
</div>
</body>
First things first, swap to PDO, ASAP. This will save you TONS of time and can help with SQL execution time, when used correctly (You can find a quick PDO tutorial here). To answer question, I would recommend you start with importing the jQuery library. It allows near effortless manipulation of the DOM.
Then, just do something like
$('#your-form-id-here').submit(function(clickEvent){
$.ajax({
url: 'http://www.foo.com/',
data: $('#your-form-id-here').serialize(),
method: 'POST',
success: function(Response){
//If the request is successful, this code gets executed
},
error: function(){
//If the request failed, this code gets executed
}
});
return false; <----This prevents the page from refreshing
});
Now lets break it down a bit
data: $('#your-form-id-here).serialize() <-- This gets all of your form data ready
NOTE: There's way more to it than this. You'll need to do some server-side stuff to make this work right. For instance, if you want a JSON object back, you'll need to return it. In php, I like to do something like
if(My request succeeded){
echo(json_encode(array(
'status' => 'success',
'message' => 'Request description/whatever you want here'
)));
}
I am trying to upload only PDF files in my form, but nothing happens. It doesn't save the file name in the database and the file does not save into the directory.
My PHP code is
if (isset($_POST['submit'])) {
$folder_path = 'health/';
$filename = basename($_FILES['healthfile']['name']);
$newname = $folder_path . $filename;
if (move_uploaded_file($_FILES['healthfile']['tmp_name'], $newname)) {
if ($_FILES['healthfile']['type'] != "application/pdf") {
echo "<p>Class notes must be uploaded in PDF format.</p>";
} else {
$filesql = "INSERT INTO tbl_health (link) VALUES ('{$filename}')".die(mysql_error());
$fileresult = mysql_query($filesql, $con).die(mysql_error());
}
if ($fileresult) {
echo 'Success';
} else {
echo 'fail';
}
}
}
my form is
<form action="allhealth.php" method="post" enctype="multipart/form-data">
<label>Upload Your Health Certificate</label>
<span class="btn btn-default btn-file">
Browse <input name="healthfile" type="file">
</span>
<br/><br/>
<button type="button" name="submit" class="btn-success">Submit</button>
</form>
Please help!!
Use this
if(isset($_POST["submit"]))
{
$folder_path = 'health/';
$filename = basename($_FILES['healthfile']['name']);
$newname = $folder_path . $filename;
$FileType = pathinfo($newname,PATHINFO_EXTENSION);
if($FileType == "pdf")
{
if (move_uploaded_file($_FILES['healthfile']['tmp_name'], $newname))
{
$filesql = "INSERT INTO tbl_health (link) VALUES('$filename')";
$fileresult = mysql_query($filesql);
if (isset($fileresult))
{
echo 'File Uploaded';
} else
{
echo 'Something went Wrong';
}
}
else
{
echo "<p>Upload Failed.</p>";
}
}
else
{
echo "<p>Class notes must be uploaded in PDF format.</p>";
}
}
Note Before upload file you should check whether its in correct format
and MySQL extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
Use this it's working now I have tested at local.
<?php
if (isset($_POST['submit'])) {
$folder_path = 'health/';
$filename = basename($_FILES['healthfile']['name']);
$newname = $folder_path . $filename;
if ($_FILES['healthfile']['type'] == "application/pdf")
{
if (move_uploaded_file($_FILES['healthfile']['tmp_name'], $newname))
{
$filesql = "INSERT INTO tbl_health (link) VALUES('$filename')";
$fileresult = mysql_query($filesql);
}
else
{
echo "<p>Upload Failed.</p>";
}
if (isset($fileresult))
{
echo 'Success';
} else
{
echo 'fail';
}
}
else
{
echo "<p>Class notes must be uploaded in PDF format.</p>";
}
}
?>
<form action="" method="post" enctype="multipart/form-data">
<label>Upload Your Health Certificate</label>
<span class="btn btn-default btn-file">
Browse <input name="healthfile" type="file">
</span>
<br/><br/>
<input type="submit" name="submit" class="btn-success" value="submit">
</form>
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
I have a single file named test.php. In this file, I written below codes to upload a picture (.PNG and .JPG). I also add some code to make a preview of pictures before being uploaded...
Nothing seems to be wrong but when I press the SUBMIT button, nothing happens...
Why? Where is my problem?
Update: I make changes and now I get this warning:
Warning: Invalid argument supplied for foreach() in...
test.php:
<script type="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<body>
<?php
if ( isset( $_POST[ 'submit' ] ) ) {
define ("UPLOAD_DIR" , "uploaded/pic/");
foreach ($_FILES["images"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$name = $_FILES["images"]["name"][$key];
$info = getimagesize($_FILES["images"]["tmp_name"][$key]);
$image_type = $info[2];
$type = $_FILES['images']['type'][$key];
// if the image is .JPG or .PNG
if ( ($image_type == 3) || ($image_type == 2) ){
// ensure a safe filename
$name = preg_replace("/[^A-Z0-9._-]/i", "_", $name);
// don't overwrite an existing file
$i = 0;
$parts = pathinfo($name);
while (file_exists(UPLOAD_DIR . $name)) {
$i++;
$name = $parts["filename"] . "-" . $i . "." . $parts["extension"];
}
// preserve file from temporary directory
$success = move_uploaded_file($_FILES["images"]["tmp_name"][$key], UPLOAD_DIR . $name);
if (!$success) {
echo "<p>Unable to save file.</p>";
exit;
}
// set proper permissions on the new file
chmod(UPLOAD_DIR . $name, 0644);
echo "<h2>Successfully Uploaded Images</h2>";
}
else{
echo "<h2>format not supported... </h2>";
}
}
}
}
?>
<div id="upload_form">
<form id="frm1" name="frm1" method="post" action="test.php" enctype="multipart/form-data">
<p>
<label for="images">insert your image</label>
<input type="file" name="images" id="images" tabindex="80"/>
</p>
<img id="pic" name="pic" src="#" />
<button type="submit" id="submit" name="submit">Upload Files!</button>
</form>
<script type="text/javascript" language="javascript">
// Preview the picture before Uploading on the server!
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#pic').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#images").change(function(){
readURL(this);
});
</script>
</div>
You need to put your name="images as an array using []
Like this:
<input type="file" name="images[]" id="images" tabindex="80"/>