Jump to content

Javascript & PHP Copy Button


ricpurcell

Recommended Posts

  <p>Current Images Inside Gallery
    <br />
<?php foreach($rows as $row): ?>
  <div class="t">
    <table class="table2">
    <tr>
      <td class="table2"><?php echo $row["id"]; ?></td>
    </tr>
    <tr>
      <td><img src="images/<?php echo $row["photo"] ; ?>" alt="" width="130" height="130" /></td>
    </tr>
    <tr>
      <td><textarea class="js-copyfilename" readonly="readonly" ><?php echo $row["photo"];?></textarea>

  <button class="js-copyfilenamebtn">Copy Filname</button>
  </td>
    </tr>

    </table>
  </div>
<?php endforeach;?>
</div>
<script type="text/javascript">
        var copyfilenameBtn = document.querySelector('.js-copyfilenamebtn');

copyfilenameBtn.addEventListener('click', function(event) {
  var copyfilename = document.querySelector('.js-copyfilename');
  copyfilename.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
    </script>

I am trying to create a button so the user can copy `$filename` then paste it into a field (this part I will code after this is sorted) I have this code which works but it only works for the first row I understand that I will need array the that this is because I would probably need to array the js-copyfilename and js-copyfilenamebtn classes so each one is different but i know very little about JavaScript so would know where to start

 

Thanks in advance

Link to comment
Share on other sites

I absolutely love heredoc's.  Seriously, can't get enough of them. have a look as this re-write of your form loop:

<?php 
$formOut = "";
foreach($rows as $row){
$formLine = <<<FORMLINE
<div class="t">
  <table class="table2">
    <tr>
      <td class="table2">{$row['id']}</td>
    </tr>
    <tr>
      <td><img src="images/{$row['photo']}" alt="" width="130" height="130" /></td>
    </tr>
    <tr>
      <td>
        <textarea class="js-copyfilename" readonly="readonly" >{$row['photo']}></textarea>
        <button class="js-copyfilenamebtn">Copy Filname</button>
      </td>
    </tr>
  </table>
</div>
FORMLINE;
$formOut .= $formLine;
};

I find that it's much more readable without all the php opening and closing tags all over the place. 

 

That said, what exactly are you looking to achieve here?

 

If you're trying to push info into the clipboard (as it looks like you) then you can't just pass it a raw array - it's not going to have access to the array contents.  You would need to serialize the array then pass the string to the clipboard, but then the output when someone pastes the content back out will look weird to them.  You could try to append the values to the clipboard in a custom format by calling a paste back into a temp variable before each "copy" and then append the new data and pass it back as the value to the copy call - but I don't even know if this will work without a hidden text-area to act as a collection point for the Copy call.  Another way would be to change your whole layout so that the user sees and is aware that they are adding each photo location to said textarea with the button click (even giving the option to remove should they choose?) and provide a separate button to copy this text area to the clipboard.  This would provide more control to the end user, but more click's required as well....

 

So it really depends on your own preference and the target audience of the site.  How would you like to go forward?

Link to comment
Share on other sites

<?php
// Include Databse
include "common.php";

// validation errors
$error = array();

// Check if form has been submitted
if (isset ($_POST['delete']))
{
// get the filename & id. See php.net/basename for more info
    $filename = basename($_POST['filename']);
	$id =($_POST['id']);
    
// get file extension, see php.net/pathinfo for more info
    $ext = pathinfo($_POST['filename'], PATHINFO_EXTENSION);

// allowed file extensions
    $allowedExtensions = array('jpeg','jpg','gif','png','bmp');

// Check filename is not empty
    if(empty($filename))
    {
        $error[] = "Please enter a Filename";
    }

// Check valid file extension used
   else if(!in_array($ext, $allowedExtensions))
    {
        $error[] = "Please check Filename";
    }
	
// Check ID is not empty    
if(empty($_POST['id']))
    {
        $error[] = "Please enter a ID";
    }
	
	else if(is_numeric($id))
{
// Check ID exists in database
$query = "SELECT id FROM `test` WHERE `id` = :id" ;
$stmt = $db->prepare($query);
$stmt->bindParam(":id", $id);
$stmt->execute();

if(!$stmt->rowCount() == 1)
{
	$error[] = "Please check ID";
}
}

else {
	$error[] = "ID is not numeric";
}

// delete file from database if there are no errors
    if (empty($error))
    {
// path to the image
    $file_to_delete = 'images/' . $filename;
	
// Checks the file exists and that is a valid image
        if(file_exists($file_to_delete) && getimagesize($file_to_delete))
        {
// Delete File From Directory
            unlink($file_to_delete);
        }
        else
        {
            $error[] = "File not found please check Filename";
        }

if (empty($error))
{
// Run Query To Delete File Information From Database
        try
        { 

            $query = "DELETE FROM `test` WHERE `id` = :id";
            $stmt = $db->prepare($query); 
            $stmt->execute(array('id' => intval($_POST['id']))); 
        } 
        catch(PDOException $ex) 
        {  
            die("Failed to run query: Please report issue to admin"); 
        }


        $status = "File Deleted";
    }
}
}

// Run Query To Show The Current Data In Database
try 
{ 
    $query = "SELECT id,photo FROM test ORDER BY id";
    $stmt = $db->prepare($query); 
    $stmt->execute(); 
} 
catch(PDOException $ex) 
{   
    die("Failed to run query: Please report issue to admin"); 
} 
         
$rows = $stmt->fetchAll(); 
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Image</title>
<link href="css/delete.css" rel="stylesheet" type="text/css" />
</head>

<body>
<div id="wrap">
<form action="delete.php" method="post" enctype="multipart/form-data">
Please enter the Filename and ID of the image you wish to delete
  <table width="284" align="center">
    <tr>
      <td width="144" class="table1">Filename</td>
      <td width="128" class="table1">ID </td>
    </tr>
    <tr>
      <td class="table1"><input name="filename" type="text" value="<?php echo $filename; ?>" /></td>
      <td class="table1"><input name="id" type="text" id="id" value="<?php echo $id; ?>" size="3" maxlength="4" /></td>
    </tr>
  </table>
  <p>
    <?php 
// Show validation errros here
    if(!empty($error)):
    echo  implode('<br />', $error);
	echo $status;
	endif; 
    ?>
    <br />
    <input type="submit" value="Delete Selected Image" name="delete" />
  </p>
  </form>
  <p>Current Images Inside Gallery
    <br />
<?php foreach($rows as $row): ?>
  <div class="t">
    <table class="table2">
    <tr>
      <td class="table2"><?php echo $row["id"]; ?></td>
    </tr>
    <tr>
      <td><img src="images/<?php echo $row["photo"] ; ?>" alt="" width="130" height="130" /></td>
    </tr>
    <tr>
      <td><textarea class="js-copyfilename" readonly="readonly" ><?php echo $row["photo"];?></textarea>

  <button class="js-copyfilenamebtn">Copy Filname</button>
  </td>
    </tr>

    </table>
  </div>
<?php endforeach;?>
</div>
<script type="text/javascript">
        var copyfilenameBtn = document.querySelector('.js-copyfilenamebtn');

copyfilenameBtn.addEventListener('click', function(event) {
  var copyfilename = document.querySelector('.js-copyfilename');
  copyfilename.select();

  try {
    var successful = document.execCommand('copy');
    var msg = successful ? 'successful' : 'unsuccessful';
    console.log('Copying text command was ' + msg);
  } catch (err) {
    console.log('Oops, unable to copy');
  }
});
    </script>
</body>
</html>

Basicly this is my full page code what I am tring to do is create a button that will copy the filename so the user can paste it into the field (incase its to long and saves them highliting it heres a live preview of the code so you can perhaps see what the problem is the first copy filename works but the rest doesn't http://rbgraphix.co.uk/gallery/display/New/delete.php

Edited by ricpurcell
Link to comment
Share on other sites

This would likely be much easier with jquery.  Then you could target the nearest textarea to the button and grab the text you need.  Your page is throwing a console error for the doctype, that could be hindering the js in some way.

SyntaxError: expected expression, got '<'
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "ht

You also say that the button works for the first filename, but according to your code and what is happening in the console, it's giving the error message, not the success message.  So it doesn't look like it's working at all to me.

Link to comment
Share on other sites

for anybody trying to do something similar i done this like so works perfect how I wanted it to (copies the filename of button clicked and then pastes it into the filename field   ....

PHP CODE TO RETRIEVE DATABASE AND DELETE SELECTED

<?php 

    // These variables define the connection information for your MySQL database 
    $username = ""; 
    $password = ""; 
    $host = ""; 
    $dbname = ""; 

    // UTF-8 is a character encoding scheme that allows you to conveniently store 
    // a wide varienty of special characters, like ¢ or €, in your database. 
    // By passing the following $options array to the database connection code we 
    // are telling the MySQL server that we want to communicate with it using UTF-8 
    // See Wikipedia for more information on UTF-8: 
    // http://en.wikipedia.org/wiki/UTF-8 
    $options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'); 
     
    // A try/catch statement is a common method of error handling in object oriented code. 
    // First, PHP executes the code within the try block.  If at any time it encounters an 
    // error while executing that code, it stops immediately and jumps down to the 
    // catch block.  For more detailed information on exceptions and try/catch blocks: 
    // http://us2.php.net/manual/en/language.exceptions.php 
    try 
    { 
        // This statement opens a connection to your database using the PDO library 
        // PDO is designed to provide a flexible interface between PHP and many 
        // different types of database servers.  For more information on PDO: 
        // http://us2.php.net/manual/en/class.pdo.php 
        $db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options); 
    } 
    catch(PDOException $ex) 
    { 
        // If an error occurs while opening a connection to your database, it will 
        // be trapped here.  The script will output an error and stop executing. 
        // Note: On a production website, you should not output $ex->getMessage(). 
        // It may provide an attacker with helpful information about your code 
        // (like your database username and password). 
        die("Failed to connect to the database: " . $ex->getMessage()); 
    } 
     
    // This statement configures PDO to throw an exception when it encounters 
    // an error.  This allows us to use try/catch blocks to trap database errors. 
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
     
    // This statement configures PDO to return database rows from your database using an associative 
    // array.  This means the array will have string indexes, where the string value 
    // represents the name of the column in your database. 
    $db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); 
     
    // This block of code is used to undo magic quotes.  Magic quotes are a terrible 
    // feature that was removed from PHP as of PHP 5.4.  However, older installations 
    // of PHP may still have magic quotes enabled and this code is necessary to 
    // prevent them from causing problems.  For more information on magic quotes: 
    // http://php.net/manual/en/security.magicquotes.php 
    if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc()) 
    { 
        function undo_magic_quotes_gpc(&$array) 
        { 
            foreach($array as &$value) 
            { 
                if(is_array($value)) 
                { 
                    undo_magic_quotes_gpc($value); 
                } 
                else 
                { 
                    $value = stripslashes($value); 
                } 
            } 
        } 
     
        undo_magic_quotes_gpc($_POST); 
        undo_magic_quotes_gpc($_GET); 
        undo_magic_quotes_gpc($_COOKIE); 
    } 
     
    // This tells the web browser that your content is encoded using UTF-8 
    // and that it should submit content back to you using UTF-8 
    header('Content-Type: text/html; charset=utf-8'); 
     
    // This initializes a session.  Sessions are used to store information about 
    // a visitor from one web page visit to the next.  Unlike a cookie, the information is 
    // stored on the server-side and cannot be modified by the visitor.  However, 
    // note that in most cases sessions do still use cookies and require the visitor 
    // to have cookies enabled.  For more information about sessions: 
    // http://us.php.net/manual/en/book.session.php 
    session_start(); 

    // Note that it is a good practice to NOT end your PHP files with a closing PHP tag. 
    // This prevents trailing newlines on the file from being included in your output, 
    // which can cause problems with redirecting users. 

JAVASCRIPT TO COPY FILENAME TO FILENAME FIELD

// JavaScript Document
function ClipBoard(obj) 
{
	var filename = document.getElementById("filename");
	filename.innerText = obj.innerText;
	Copied = filename.createTextRange();
	Copied.execCommand("Copy");
}

PHP CODE TO CONNECT TO DATABASE

<?php
include ("common.php");


// Run Query To Show The Current Data In Database
try 
{ 
    $query = "SELECT id,photo FROM test ORDER BY id";
    $stmt = $db->prepare($query); 
    $stmt->execute(); 
} 
catch(PDOException $ex) 
{   
    die("Failed to run query: Please report issue to admin"); 
} 
         
$rows = $stmt->fetchAll(); 
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript">
function ClipBoard(obj) 
{
	var filename = document.getElementById("filename");
	filename.innerText = obj.innerText;
	Copied = filename.createTextRange();
	Copied.execCommand("Copy");
}
</script>
</head>
<body>

<?php 
foreach ($rows as $row)
 {
$i = $row["photo"];

	print '<textarea class="js-copyfilename" name="copytext'.$i.'" id="copytext'.$i.'">'.$i.'</textarea><input type="button"  onclick="ClipBoard(document.getElementById(\'copytext'.$i.'\'));" value="Copy to Clipboard"> <br>';
}
?>

<textarea name="filename" id="filename" style="display:block;">
</textarea>
 
</body>
</html>




 

Link to comment
Share on other sites

Couple things to adjust to make this better, set all the PDO options before connecting.  You already have the $options array with an option in it, set the others there too.

With this query

$query = "SELECT id,photo FROM test ORDER BY id";
    $stmt = $db->prepare($query); 
    $stmt->execute();

There is no reason to use a prepare and execute on this, you're not inserting any variables to the query so it's already 100% safe, just run a normal query().  Plus there is no reason to do the try/catch block on it either.  If it fails it'll be because of a coding or server error during the connection, not cause the $stmt failed.  Just my 2 cents.

Link to comment
Share on other sites

Do this

$options = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8', PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC);

Then remove the $db->setAttribute()s

 

I don't have a clue what you mean by this statement:

 

can you also help me with something else please I want to do a further validation check that the $filename and $id is in the same column  how would I do this ?

Link to comment
Share on other sites

Thanks done that

Basicly I want to check that the filename and id the user has entered exists in the same column else print the error ?

summit like I know how to check it exists in db but not how check its in same column

if ($filename & $id !== Same column in database )

{

error[] = "Please check the details you entered ;

}

 

else {

continue with code

}

sorry my mistake same row not column

Edited by ricpurcell
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.