how to manage in JavaScript null values from PHP code - javascript

I have the next PHP/HTML code for upload an image:
<label>Image (*)</label>
<!-- if image exists, show it -->
<?php if($category->getImage() === null) : ?>
<input type="file" name="image" id="image" required>
<?php else : ?>
<p><img src="../uploads/images/<?php echo $categoria->getImage(); ?>"></p>
<input type="file" name="image" id="image">
<?php endif; ?>
And I want to validate it using JavaScript
// Validate image
image = document.getElementById("image").value;
if (!image) {
window.alert("You must select a file for the image.");
document.getElementById("image").focus();
return false;
}
The image is required. If you create a new registry it sets all of its atributes to null, including the image. Then, the image is not show and you can set it in the form. If you want to update them, the form shows the current imagen but you don't have to update it if you don't want to.
I need to validate if the file hasn't been uploaded and the value is null it means that the user is creating a new registry and the image is required. If the file hasn't been uploaded but its value isn't null, the user is updating the registry and it isn't required to upload an image.
Thanks in advance and sorry for my bad english.

You can add id to the image
<img id="foo" src="../uploads/images/<?php echo $categoria->getImage(); ?>">
and check if it's in the DOM:
if ($('#foo').length) {
// image is there
}
or without jQuery:
if (document.getElementById("foo")) {
// image is there
}

Related

How to append a time/datestamp to a file name in an html file

I have an html form with an image upload section and it works fine, however for data management reasons I would like the image file name to have the time/datestamp added to it when it uploads.
What used to happen, was that if the file would be uploaded via a phone it would be called image.jpg which would be overwritten if a new file by the same name would be uploaded (understandably)
However what I want to have happen, is that the file would be called something like image091118151821 for the 11 September 2018 15:18:21. or something like that.
The HTML Form:
<form method="POST" action="incident-submit.php" enctype="multipart/form-data">
div class="element-date"><label class="title">Date</label><input class="large" data-format="yyyy-mm-dd" type="date" name="date" placeholder="yyyy-mm-dd"/></div>
<div class="element-input"><label class="title">Division</label><input class="large" type="text" name="input" /></div>
<div class="element-input"><label class="title">Location within Division</label><input class="large" type="text" name="input1" /></div>
<div class="element-input"><label class="title">Employee Division</label><input class="large" type="text" name="input2" /></div>
<div class="element-textarea"><label class="title">Cause of events</label><textarea class="large" name="textarea" cols="20" rows="5" ></textarea></div>
<input type="file" name="image">
</div>
<div>
<button type="submit" name="upload">POST</button>
</div>
And the PHP that submits the data to the database:
// If upload button is clicked ...
if (isset($_POST['upload'])) {
// Get image name
$image = $_FILES['image']['name'];
// Get text
$date = $_POST['date'];
$division = $_POST['input'];
$location = $_POST['input1'];
$employeedivision = $_POST['input2'];
$events = $_POST['textarea'];
// image file directory
$target = "img/".basename($image);
...
if (move_uploaded_file($_FILES['image']['tmp_name'], $target)) {
$msg = "Image uploaded successfully";
}else{
$msg = "Failed to upload image";
}
I then changed the
$image = $_FILES['image']['name'];
line to:
$image = $_FILES['image'.date('m-d-Y_hia').'.jpg']['name'.date('m-d-Y_hia').'.jpg'];
And it seems to not upload anything
Is there a way I can cause that to happen, it does not have to be done in php, javascript is also fine
Could someone help me solve this conundrum?
Thanks in advance
Using the handy pathinfo() function you can dig out all the seperate parts of a filename. Then just use those and the date() function to build the filename of your choice.
$path_parts = pathinfo($_FILES['image']['name']);
$dest_filename = $path_parts['filename'] . date('mdyHis') . '.' . $path_parts['extension'];
// image file directory
$target = "img/$dest_filename";
If you want to seperate the filename from the date to make it a little easier to read you could try
$dest_filename = $path_parts['filename'] .
'_' .
date('mdyHis') .
'.' .
$path_parts['extension'];
You need to change this line
$target = "img/".basename($image);
to:
$target = "img/".basename(explode('.',$image)[0] . date('m-d-Y_hia') . explode('.',$image)[1]);

Clicking on existing profile picture to upload and change image.

I have made a user profile card where the user can click on choose file to select and upload an image.
Everything works fine however I would like to change it so instead of having to click on "choose file" and then click on "upload", the user can just click on the existing image and be brought to the select image screen:
and once they have selected a image and pressed open, the image is automatically changed?
This is my code to display the user profile card.
<?php
//query to see if the user has uploaded a profile picture.
$sql = "SELECT * FROM user_image WHERE userid = ?";
$stmt = mysqli_prepare($connect, $sql);
mysqli_stmt_bind_param($stmt,"i",$_SESSION['userid']);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$userImage = mysqli_fetch_assoc($result);
mysqli_stmt_close($stmt);
?>
<h1>User's Profile</h1>
<?php if($userImage['is_set'] == 0){
echo '<img src="profile_pics/default-profile-pic.png"/>';
}
else{
echo '<img src="'.$userImage['image_dir'].'"/>';
}
?>
<form action="upload.php" method="POST" enctype="multipart/form-data">
<input type="file" name="file" accept="image/*">
<button type="submit" name="submit">Upload</button>
</form>
Use a <label> (with for targeting the id on the file field):
<label for="fileField"><img src="..."></label>
<input type="file" id="fileField" name="file" accept="image/*">
You can use a <label> tag attached the file input to trigger the open box or you can use a click handler on the image that triggers a click on the file input.
document.querySelector('img').addEventListener('click', function(){
document.querySelector('h1 + img').click();
});
To get the file to upload immediately when selected you have to attach a change event handler for the image input. Then submit the form in it. You would have to change the submit button name to something other than submit to get this to work.
document.querySelector('input[type=file]').addEventListener('change', function(){
this.form.submit();
});
<button type="submit" name="upload">Upload</button>
<label for="fileField"><img src="..." height="100px" width="100px"></label>
<input type="file" id="fileField" name="file" accept="image/*" hidden="true">
Using hidden = "true", you can invisible the choose file.
Using height and width inside the img tag, you can adjust the image size.

not able to update input type file value

1)i am adding image and its title in database
but if i submit form for first time it works but again without selecting the image when its pre selected from first submit
2) submiting form 2nd time takes image value null or is empty(updating image)
<form method="post" enctype="multipart/form-data">
<div id="photoselect_box">
<h5 id="logo_head">Profile Image</h5>
<script>
function profile_imagee(input){
$('#profile_image')[0].src = (window.URL ? URL :webkitURL).createObjectURL(input.files[0]);
}
</script>
//input image preview
<img src="<?php $path = "download/items/$uid/"; echo $path.$userRow['profile_image']; ?>" id="profile_image" alt="profile photo" name="profile_image" />
<input type="file" id="img_file" name="profile_image" onChange="profile_imagee(this);"
value="<?php echo $userRow['profile_image']; ?>" />
</div>
// i am able to update this input after clicking submit
<input type="text" id="download_content1" name="download_content1" value="<?php echo $userRow['download_content1']; ?>" >
</form>
i cannot update the image value in database after submiting form for 2nd time
php code
include_once '../../database/conn.php';
$res=mysqli_query($bd,"SELECT * FROM organisation);
$userRow=mysqli_fetch_array($res);
$email=$userRow['email'];
if (isset($_POST['register'])){
//inserting logo image
$profile_image=$_FILES['profile_image']['name'];
$profile_image_temp=$_FILES['profile_image']['tmp_name'];
// changing the destination required folder according to users unique id
$path = "download/items/$uid/";
#mkdir($path, 0666, true); // Create upload folder.
move_uploaded_file($profile_image_temp,$path.$profile_image);
//updating image in database
$insert="UPDATE organisation SET profile_image= '$profile_image',download_content1 = '$download_content1 '
WHERE email = '$email'";
$insert_pro = mysqli_query($bd,$insert);
}

Only apply image upload url to specific input field

I'm making a custom field in a custom meta box in WordPress. I have input text fields, textareas, and checkboxes that are all working fine. I also included a browse button for the image gallery that is working.
When you click on the "Browse" button, it pulls up the WordPress media upload screen, and when you select that image, it will replace the input value (as well as an image thumbnail).
Here is the relevant part of the WordPress meta box set up.
function show_custom_fields_meta_box() {
global $post;
$meta = get_post_meta( $post->ID, 'custom_fields', true ); ?>
<input type="hidden" name="custom_meta_box_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>">
<!-- image upload field -->
<p>
<label for="custom_fields[image]">Image Upload</label><br>
<input type="text" name="custom_fields[image]" id="custom_fields[image]" class="meta-image regular-text" value="<?php echo $meta['image']; ?>">
<input type="button" class="button image-upload" value="Choose or Upload an Image">
<div class="image-preview"><img src="<?php echo $meta['image']; ?>" style="max-width: 250px;"></div>
</p>
}
And here's the jQuery I'm using to open the WordPress media gallery and upload the image.
<script>
/*
* Attaches the image uploader to the input field
*/
jQuery(document).ready(function ($) {
// Instantiates the variable that holds the media library frame.
var meta_image_frame;
// Runs when the image button is clicked.
$('.image-upload').click(function (e) {
// Prevents the default action from occuring.
e.preventDefault();
var selected = $(this);
var meta_image = $('.meta-image');
// If the frame already exists, re-open it.
if (meta_image_frame) {
meta_image_frame.open();
return;
}
// Sets up the media library frame
meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
title: meta_image.title,
button: {
text: meta_image.button
}
});
// Runs when an image is selected.
meta_image_frame.on('select', function () {
// Grabs the attachment selection and creates a JSON representation of the model.
var media_attachment = meta_image_frame.state().get('selection').first().toJSON();
// Sends the attachment URL to our custom image input field.
$('.meta-image').val(media_attachment.url);
var imgurl = $('.meta-image').val();
$(selected).prev().val(imgurl);
$(selected).closest('div').find('.image-preview').children('img').attr('src',imgurl);
});
// Opens the media library frame.
meta_image_frame.open();
});
});
</script>
Now, this works perfectly fine as-is. The input button has a class of .image-upload, and the input text field has a class of meta-image.
However, if I add another field...(custom_fields[image2])
<p>
<label for="custom_fields[image2]">Image Upload</label><br>
<input type="text" name="custom_fields[image2]" id="custom_fields[image2]" class="meta-image regular-text" value="<?php echo $meta['image2']; ?>">
<input type="button" class="button image-upload" value="Choose or Upload an Image">
<div class="image-preview"><img src="<?php echo $meta['image2']; ?>" style="max-width: 250px;"></div>
</p>
The jQuery will apply to both browse buttons and text inputs, because it's a class. I know (think) I have to use some form of $(this) to get the correct button and text input, but all of my efforts have been in vain so far.
I've tried $(this).closest('.meta-image'), but that doesn't seem to work.
Thank you!
I was able to do it with this code:
var meta_image = $(this).parent().children('.meta-image');
You could use the variable selected in the select event handler.
Try this:
var metaImage = $(selected).closest('p').find('.meta-image),
imgurl = $(metaImage).val();

How to save a rendered webpage as image with JavaScript?

In my app I have to provide a 'save as image' button. I want to save the HTML rendered on my webpage as an image in JavaScript. It is a webapp and will be used in browsers of desktop/tablet/mobile phones. How to save rendered HTML as an image?
Check out html2canvas. A javascript framework that renders the page content on a canvas element. Saving the canvas as an image is as easy as:
var canvas = document.getElementById("mycanvas");
var img = canvas.toDataURL("image/png");
document.write('<img src="'+img+'"/>');
source
Using http://html2canvas.hertzen.com/
index.php
<style>.wrap{background:white;padding:0 0 16px 0;width:1500px;}.colour{width:1500px;position:relative;height:1400px;}p.footer{text-align:center;font-family:arial;line-height:1;font-size:28px;color:#333;}.wrap img{height:389px;width:389px;position:absolute;bottom:0;right:0;left:0;top:0;margin:auto;}p.invert{position:absolute;top:300px;left:0;right:0;text-align:center;display:block;font-family:arial;font-size:48px;padding:0 40px;filter:invert(0%);}p.inverted{-webkit-filter: invert(100%);filter:invert(100%);}</style>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/html2canvas.js"></script>
<script type="text/javascript" src="js/jquery.plugin.html2canvas.js"></script>
<?php // Open our CSV File
$colours = fopen('colours.csv', 'r');
// Reset Count
$i=0;
// Loop Through the Colours
while (($colour = fgetcsv($colours)) !== FALSE){
// Get the First Item and display some HTML
if($i==0){ ?>
<div id="target" class="wrap">
<div class="colour" style="background:<?php echo $colour[0]; ?>">
<img src="paragon2.png" alt="Image" />
<p class="invert inverted" style="filter:invert(100%);"><?php echo $colour[1]; ?></p>
</div>
<p class="footer"><?php echo $colour[1]; ?></p>
</div>
<form method="POST" enctype="multipart/form-data" action="save.php" id="myForm">
<input type="hidden" name="img_val" id="img_val" value="" />
<input type="hidden" name="filename" id="filename" value="<?php echo $colour[0].".png"; ?>" />
</form>
<?php } // Count
$i++;
} // Loop
// Close the CSV File
fclose($colours); ?>
<script type="text/javascript">
$(window).load(function () {
$('#target').html2canvas({
onrendered: function (canvas) {
$('#img_val').val(canvas.toDataURL("image/png"));
document.getElementById("myForm").submit();
}
});
});
</script>
save.php
<?php // Get the base-64 string from data
$filteredData=substr($_POST['img_val'], strpos($_POST['img_val'], ",")+1);
$filename=$_POST['filename'];
// Decode the string
$unencodedData=base64_decode($filteredData);
// Save the image
file_put_contents("IMG2/".$filename, $unencodedData);
// Open the CSV File
$file = fopen('colours.csv', 'r');
// Loop through the colours
while (($line = fgetcsv($file)) !== FALSE) {
// Store every line in an array
$data[] = $line;
}
// Remove the first element from the stored array
array_shift($data);
// Write remaining lines to file
foreach ($data as $fields){
fputcsv($file, $fields);
}
// Close the File
fclose($file);
// Redirect and start again!
header( 'Location:/' ) ; ?>
Your question is very incomplete. First, is that a mobile or desktop app? In both cases, the solution to your problem will strongly depend on the HTML engine that renders the pages: Webkit, Geko/Firefox, Trident/IE for example have their own method to produce the view that you want to save as an image.
Anyway, you could start looking at how this Firefox plugin works: https://addons.mozilla.org/it/firefox/addon/pagesaver/
It should do what you want to implement, look for its source code.

Categories

Resources