...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
April 14, 2012

How can I "remove" the disabled attribute on click?

Question by Strawberry

I couldn’t quite get it to work properly. I’m trying to remove the disabled attribute on click so that I can edit it.

My jQuery:

$('#edit-credentials').click(function() { 
    $('#credentials :input').prop("disabled", !$('#credentials:input').prop("disabled")) 
});

HTML:

<a id="edit-credentials" onclick="return false;" href="#">edit</a>

<div id="credentials">
<input disabled="disabled">
<input disabled="disabled">
</div>

Answer by Starx

What wrong with

$('#credentials :input').prop("disabled", false);
Read more

Customizing the appearance of a file input in an HTML form

Question by Danny

I’ve been trying to figure out how to customize the appearance of a file input in an HTML form so that the button will match with the rest of the buttons on my site. Looking around here I found a solution that I would expect to work, but it’s having some strange behavior.

I took my file input and set display:none, and created a new text input and button within the form.

            <form method="post" action="../Entry/Create" enctype="multipart/form-data" onsubmit="return aentryValidate()">
                <input type="text" id="EntryTitle" name="EntryTitle" maxlength="50" />
                <div id="invalidTitle" class="invalidData"></div>
                <p id="char-remaining">(50 characters remaining)</p>

                <input type="file" id="ImageFile" name="ImageFile" style="display:none;" />
                <input type="text" id="ImageFileMask" name="ImageFileMask" disabled="true" />
                <button type="button" onclick="HandleFileButtonClick()" id="ImageFileButton" style="margin-left:10px;padding-bottom:0px;height:20px;width:100px;font-size:14px;">browse...</button>
                <div id="invalidImage" class="invalidData"></div>
                <p id="file-desc">(image to represent your entry, jpg, png, or gif)</p>

                <textarea id="EntryDesc" name="EntryDesc"></textarea>
                <div id="invalidDesc" class="invalidData"></div>
                <br />

                <input type="checkbox" id="isPrivate" name="isPrivate" value="true" />
                <input type="hidden" name="isPrivate" value="false" />
                Make my entry private.

                <button id="new-entry-save">save</button>
            </form>

Then my javascript to handle the ImageFileButton button being clicked:

function HandleFileButtonClick() {
    document.getElementById("ImageFile").click();
    document.getElementById("ImageFileMask").value = document.getElementById("ImageFile").value;
}

It appears to work fine. I click the button, the window pops up for me to select a file. When I select a file, it appears in the text box.

The weird behavior comes when I hit the save button on the form. I noticed that it has to be clicked twice to actually submit for some reason now. And, when it submits it is no longer posting the file.

So I made the file input visible again to see what was happening. If I use the ImageFileButton button to select a file, the file shows up in the file input. But when save is clicked, the file input clears and the form doesn’t submit. You then have to click again to submit, and of course now there is no file.

Anybody know what is happening here?

Answer by Starx

No, its not possible. File inputs are generally browser dependant. You might have to use JavaScript replacement or Flash replacement like uploadify.

Article: Input File

Of all form fields, the file upload field is by far the worst when it comes to styling. Explorer Windows offers some (but not many) style possibilities, Mozilla slightly less, and the other browsers none at all. The “Browse” button, especially, is completely inaccessible to CSS manipulation.

Read more

When to load database in php

Question by EvilDesire

This is a general question.

I have a website with a page showing many elements of my database.
And in this page I have a script where I’m loading these elements.

The the thing I want to know is it alright to load the database at the display of the page, knowing that everytime user will click and reload the page, my script will reload everything again from my database?

Is it a proper way to do it? Like creating an init.php at the first loading of the website, and storing my elements into a $_SESSION?

I don’t know if I managed to explain my problem, so please ask me more informations if needed.

Answer by Starx

The concept is pretty simple.

If you are sending a new request, it is wise to always start a new connection when needed and close it when its done.

But do not store the connection or any results in SESSION, as this can cause security issues. Creating a common script to start adn close a connection is the way to go.

Having said that look at persistent connections is it probably the thing you want.

Read more

Use Field Values For Filepath

Question by IRHM

I wonder whether someone may be able to help me please.

I’m trying to load an xml file with the following filepath:

/UploadedFiles/username/location/files.xml

What I’ve been trying to do for some time, is to use the values of two forms fields, ‘username’ and ‘location’ and incorporate them into the filepath, but I just can’t seem to get this right.

I just wondered whether someone could someone perhaps tell me how I take these values and use them in the filepath.

Many thanks

POST AMENDMENT

I thought I could solve my issues by simply changing the file path, hence my original post, but I fear my lack of PHP knowledge as let me down and I suspect the issues I have are deeper within my code.

Please find below more detail.

The script below shows how I initially save the images.

‘upload.php’

<?php
require_once 'Includes/gallery_helper.php'; 
require_once 'ImageUploaderPHP/UploadHandler.class.php'; 
$galleryPath = 'UploadedFiles/'; 

function onFileUploaded($uploadedFile) { 
  global $galleryPath; 

  $packageFields = $uploadedFile->getPackage()->getPackageFields(); 
  $username=$packageFields["username"]; 
  $locationid=$packageFields["locationid"]; 
  $username = preg_replace('/[^a-z0-9_-.()[]{}]/i', '_', $_POST['username']); 
  $location = preg_replace('/[^a-z0-9_-.()[]{}]/i', '_', $_POST['locationid']); 
  $dirName = preg_replace('/[^a-z0-9_-.()[]{}]/i', '_', $_POST['folder']); 

  $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR . $username . DIRECTORY_SEPARATOR . $location . DIRECTORY_SEPARATOR; 
  $absThumbnailsPath = $absGalleryPath . 'Thumbnails' . DIRECTORY_SEPARATOR; 


  if (!is_dir($absGalleryPath)) mkdir($absGalleryPath, 0777, true); 
  chmod($absGalleryPath, 0777); 
  if (!is_dir($absGalleryPath . $dirName)) mkdir($absGalleryPath . $dirName, 0777, true); 
  chmod($absGalleryPath . $dirName, 0777); 

  if ($uploadedFile->getPackage()->getPackageIndex() == 0 && $uploadedFile->getIndex() == 0) 
    initGallery($absGalleryPath, $absThumbnailsPath, FALSE); 

  $originalFileName = $uploadedFile->getSourceName(); 
  $files = $uploadedFile->getConvertedFiles(); 
  $sourceFileName = getSafeFileName($absGalleryPath, $originalFileName); 
  $sourceFile = $files[0]; 

  if ($sourceFile) $sourceFile->moveTo($absGalleryPath . $sourceFileName); 
  $thumbnailFileName = getSafeFileName($absThumbnailsPath, $originalFileName); 
  $thumbnailFile = $files[1]; 
  if ($thumbnailFile) $thumbnailFile->moveTo($absThumbnailsPath . $thumbnailFileName); 

  $descriptions = new DOMDocument('1.0', 'utf-8'); 
  $descriptions->load($absGalleryPath . 'files.xml'); 

  $xmlFile = $descriptions->createElement('file'); 
  // <-- please check the following line 
  $xmlFile->setAttribute('name', $_POST['folder'] . '/' . $originalFileName); 
  $xmlFile->setAttribute('source', $sourceFileName); 
  $xmlFile->setAttribute('size', $uploadedFile->getSourceSize()); 
  $xmlFile->setAttribute('originalname', $originalFileName); 
  $xmlFile->setAttribute('thumbnail', $thumbnailFileName); 
  $xmlFile->setAttribute('description', $uploadedFile->getDescription()); 
  $xmlFile->setAttribute('username', $username); 
  $xmlFile->setAttribute('locationid', $locationid); 
  $xmlFile->setAttribute('folder', $dirName); 


  $descriptions->documentElement->appendChild($xmlFile); 
  $descriptions->save($absGalleryPath . 'files.xml'); 
} 

$uh = new UploadHandler(); 
$uh->setFileUploadedCallback('onFileUploaded'); 
$uh->processRequest(); 
?>

This script produces the following file structure:

UploadedFiles (Pre-existing folder)

  • ‘username’ (Subfolder containing ‘location’ folder)
  • ‘location’ (Subfolder containing original image, ‘files.xml’ and ‘Thumbnails’ folder)
  • ‘Thumbnails’ (Subfolder containing thumbnail of original image)

NB. The ‘username’ and ‘location folder names are derived from the current user and location values.

I then come onto my issue with the creation of the image gallery.

The code below is my initial ‘gallery.php’ script. I need to change the top PHP section of the script to match the new folder structure i.e. UploadedFiles/'username'/'location'/Thumbnails and UploadedFiles/'username'/'location'.files.xml

‘gallery.php’

<?php 

  $galleryPath = 'UploadedFiles/'; 

  $thumbnailsPath = $galleryPath . 'Thumbnails/'; 

  $absGalleryPath = realpath($galleryPath) . DIRECTORY_SEPARATOR; 

  $descriptions = new DOMDocument('1.0'); 
  $descriptions->load($absGalleryPath . 'files.xml'); 
?>
<head> 
  <title>Gallery</title> 
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
  <link href="Libraries/fancybox/jquery.fancybox-1.3.1.css" rel="stylesheet" type="text/css" /> 
  <link href="Styles/style.css" rel="stylesheet" type="text/css" /> 
  <!--[if IE]>   
  <link href="Styles/ie.css" rel="stylesheet" type="text/css" /> 
  <![endif]-->
  <script src="Libraries/jquery/jquery-1.4.3.min.js" type="text/javascript"></script> 
  <script src="Libraries/fancybox/jquery.fancybox-1.3.1.pack.js" type="text/javascript"></script> 
  <script type="text/javascript"> 

  $(function() { $('a.fancybox').fancybox(); }); 

  </script> 
  <style type="text/css">
<!--
.style1 {
    font-size: 14px;
    margin-right: 110px;
}
.style4 {font-size: 12px}
-->
  </style>
</head>
<body style="font-family: Calibri; color:  #505050; font-size: 9px; border-bottom-width: thin; margin-top: 5px; margin-left: -476px; margin-right: 1px; margin-bottom: -10px;">
<div align="right" class="style1"> <a href = "imagefolders.php" /> View Uploaded Images In Folder Structure <a/> &larr; View All Uploaded Images </div>
  <form id="gallery" class="page"> 
  <div id="container"> 
    <div id="center"> 
      <div class="aB"> 
        <div class="aB-B"> 
          <?php if ('Uploaded files' != $current['title']) :?>
          <?php endif;?>
          <div class="demo"> 
          <input name="username" type="text" id="username" value="IRHM73" />
          <input name="locationid" type="text" id="locationid" value="1" />
            <div class="inner"> 
              <div class="container"> 
                <div class="gallery"> 
                  <ul class="gallery-image-list"> 
                  <?php for ($i = 0; $i < $descriptions->documentElement->childNodes->length; $i++) : 
                          $xmlFile = $descriptions->documentElement->childNodes->item($i); 
                          $name = htmlentities($xmlFile->getAttribute('originalname'), ENT_COMPAT, 'UTF-8'); 
                          $description = htmlentities($xmlFile->getAttribute('description'), ENT_COMPAT, 'UTF-8'); 
                          $folder = htmlentities($xmlFile->getAttribute('folder'), ENT_COMPAT, 'UTF-8'); 
                          $source = $galleryPath . rawurlencode($xmlFile->getAttribute('source')); 
                          $thumbnail = $thumbnailsPath . rawurlencode($xmlFile->getAttribute('thumbnail')); 
                  ?>
                    <li class="item"> 
                      <a class="fancybox" target="_blank" rel="original" href="<?php echo $source; ?>"><img class="preview" 
                        alt="<?php echo $name; ?>"  src="<?php echo $thumbnail; ?>" /></a></li>
                        <p><span class="style4"><b>Image Description:</b> <?php echo htmlentities($xmlFile->getAttribute('description'));?> <br />
                          <b>Contained in folder:</b> <?php echo htmlentities($xmlFile->getAttribute('folder'));?> </span><br />  
                          <?php endfor; ?>
                          </li>
                        </p>
                  </ul>
                </div> 
              </div> 
            </div> 
          </div> 
        </div> 
      </div> 
    </div> 
    </div> 
        <div class="aB-a">        </div> 
      </div> 
    </div> 
  </div> 
  </form> 
</body> 
</html>

I admit to being at a real loss at how to solve this, I don’t whether it’s my ‘gallery.php’ script that needs to change or my ‘upload.php’

Any help would be so gratefully received.

Kind regards

Answer by Starx

You have to define them as variable and include within the string

$username = "user1";
$location = "userlocation1";

$url = "/UploadedFiles/$username/$location/files.xml";

//Next you might want to verify the location

if(is_file($url)) {
   //do your operation....
}
Read more

Overflow hidden doesn't seem to work

Question by user1184100

I have a div containing text and image and text details within ul li and below is the html structure . I have applied overflow hidden to class .sbox but it doesn’t seem to work and the text details doesn’t appear to be hidden and overflown.

JSFiddle – http://jsfiddle.net/SAN6n/

HTML

<div id="content" class="contentList">
  <ul id="slist" class="storyList">    
    <li>
     <div id="storyBox1" class="sbox"> 
        <div class="boxContent" >
            <span class="overlay"><h5>Picture1 </h5></span>
            <div class="txtOverlay"><h3>This is spring and weather looks good ...</h3</div>
            <span><img src="http://img13.imageshack.us/img13/38/picture11tp.jpg"/></span>
         </div>
      </div>
     </li>    
    </ul>
</div>​

CSS

.storyList {
  width:100%;
  height:100%;   
}


.sbox {
float:left;
width:300px;
height:150px;
padding: 5px 7px 8px 5px;
margin-top:20px;
margin-right:40px;

background:white;
border:1px solid #DDD;

<!--border radius-->
-webkit-border-radius: 3px;
-moz-border-radius: 2px;
border-radius: 3px;

overflow: hidden;

}

.boxContent {

width:100%;
height:100%;
border: 1px solid #777;
}

.storyList li {
list-style:none;
}

.overlay {

float:left;
opacity: .7;
background: #000;  
height: 40px;  
width: 300px; 
position: absolute;    
}


h5{
float:left;
margin-top:0px;
padding:0 0 0 5px;
font-family: Tahoma;
letter-spacing: 0.5px;
font-size:30px;
color: white; 

}


.txtOverlay {
opacity: .7;
background: #000;  
height: 110px;  
width: 300px; 
position: absolute;        
margin-top:150px;
z-index:1;
font-weight:bold;
float:left;
font-family: OpenSansRegular;
letter-spacing: 0.5px;
font-size:10px;
color: white;

}​

Answer by coder

DEMO

I think this is what you need ?
Any time when you have two div's one inside the other the first div needs to be set to relative and the other div’s need to be set to absolute position.

Answer by Starx

Actually It is working, the padding you gave and the content it has, it making it useless of applying the overflow:hidden;

See this demo to see my point, I have decrease the height, and the overflow:hidden is working.

Read more
April 13, 2012

How do I create a highlight on mouseover?

Question by Jeff

On my page, if i mouseover a state, the hyperlink on the right changes to a hover style. Can someone suggest how I might make the opposite happen.. when I hover one of the hyperlinks on the right, the state is highlighted (as when I hover over the state itself)?

Answer by Starx

Get the id of the map area and trigger the mouseover event.

$('.staff').mouseover(function() {
    var id = $(this).attr("class").split("-")[1];
    $("#"+id).trigger('mouseover');
});
Read more

Wildcard for WHERE?

Question by Sam Clark

I want to setup code that does this: (* is wildcard)

SELECT * FROM * WHERE * CONTAINS '$search-query';

What MYSQL code can I use to acheive this.

Answer by Starx

There is a project called anywhereindb which can do what you want.


I am not going to create a full solution, its going to take a long time, but, I am going to create an example of what you would called

SELECT * From `tablename` WHERE * CONTAINS `$search_query`

First, lets extract the fields

$fields = array();
$query = "SELECT * FROM `yourtable` LIMIT 1;";
$result = mysql_query($query);
while ($i < mysql_num_fields($result)) {
    $info = mysql_fetch_field($result, $i);
    $fields[] = $info -> name;
}

Now prepare your query

$query = "SELECT * FROM `table` WHERE";
foreach($fields as $index => $field) {
    $fields[$index] = $field." CONTAINS '$search_query'"
}
$query .= implode(" and ", $fields);
//Finally query
$result = mysql_query($query);
Read more

How to check whether domdocument has items

Question by BetterMan21

How to check whether domdocument has items

code:

 $iframe =  $dom->getElementsByTagName('iframe');


 foreach ($iframe as $if) {

    //how to check whether $if has items for
     // $if->item(0) so that I can access it without errors?
 }

Answer by Michael Berkowski

Test if the node has child nodes with hasChildNodes()

 foreach ($iframe as $if) {
    if ($if->hasChildNodes()) {
       // first child is $if->childNodes->item(0)
    }
 }

Answer by Starx

You can check using like

if($if -> hasChildNodes()) { ... }

Read more

php mysql search through 26 tables

Question by AisRuss

I’ve got this database with about 26 tables (field names are the same in each table) and i was wondering how simple it would be to do a general search on my website based on a keyword which will search through all tables?

Eg Each table has title, author etc etc so if i had a keyword of hairspray – whats the best way to look for the keyword through all tables..

Preferably not through a join or union due to the amount of tables

Cheers in advance

Answer by Starx

Its a very bad way, of creating tables.

If they share a common schema they should be one single table, with some additional field to separate or distinguish the data.

If this is not going to be an option for you, you might want to create a temporary table, which will hold all the data from all 26 tables, then query this table for the search.

Read more

How to control a <label> with CSS?

Question by AAA

I have this snippet:

      <label>&nbsp;</label><a id="whatever" 
      onclick="addmore('field_whatever', 'What's up?');">The deal is?</a><br/>

How do i use CSS to add space on the top or the bottom. I am able to do it for margin-left but it won’t work for margin-top nor margin-bottom.

Thanks

Answer by Starx

labels are by default inline. They will not respond on top/bottom margin. You have to tell them to display as block/inline-block .

Like this

label { 
    display: inline-block;
    margin: 20px 0;
}

Additionally, your anchor has an un-escaped quote. Correct it as this

<a id="whatever" 
      onclick="addmore('field_whatever', 'What's up?');">The deal is?</a>
Read more
...

Please fill the form - I will response as fast as I can!