...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
July 17, 2010

Dynamically adding a div element in jquery

Question by Chendur Pandian

I use the following function to show a status message after a form submit from my asp.net page.. The function gets called but it(alertmsg div) doesn’t seem to show up why?

 function topBar(message) {
        var $alertdiv = $('<div id = "alertmsg"/>');
        $alertdiv.text(message);
        alert($alertdiv);
        alert($alertdiv.text(message));
        $alertdiv.click(function() {
            $(this).slideUp(200);
        });
        $(document.body).append($alertdiv);
        setTimeout(function() { $alertdiv.slideUp(200) }, 5000);
    }

What happens is both the alert statements show [Object object]… I think both need to show different outputs… Any suggestion..

css:

#alertmsg
{
  font-family:Arial,Helvetica,sans-serif;
   font-size:135%;
   font-weight:bold;
  overflow: hidden;
  width: 100%;
  text-align: center;
  position: absolute;
  top: 0;
  left: 0;
  background-color: #404a58;
  height: 0;
  color: #FFFFFF;
  font: 20px/40px arial, sans-serif;
  opacity: .9;
}

Answer by Jim Schubert

You’re alerting the jQuery object. Try changing your alert to:
alert($alertdiv.get(0).innerText);

Other than that, your div may not be showing because you’re adding the click event before you add the div element to the page.

Try changing:

$alertdiv.click(function() {
            $(this).slideUp(200);
        });

To:

$alertdiv.bind('click', function() {
            $(this).slideUp(200);
        });

or even:

$alertdiv.live('click', function() {
            $(this).slideUp(200);
        });

I think this may be the only way to bind dynamically generated elements. I’ve never tried .click() outside of the document ready function.

Edit:
In addition to the above suggestion for jQuery, your css should be changed to specify a height for the div. Your height of 0 will cause it to render, technically, and possibly slide up. But, you won’t be able to see it because it is 0 pixels tall at point 0,0.

Answer by Starx

To insert a <div> dynamically you can use this

$('<div>Test</div>').insertAfter('.inner'); //to insert after an element with class inner

or better

$("#myparent").html("<div id='mynewdiv'>hi</div>");
Read more

Why are the font sizes different

Question by Mark0978

I’ve got the following html and css
In Firefox the computed font size is 16.66667px
In Chrome the computed font size is 13px

Needless to say there is a good bit of difference in these two sizes, one is too small to read, one is nicely sized. I guess one way to work around it is to set the font size to 16.67px but why is this the case.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>My first styled page</title>
  <style type="text/css">
    body {
        font-family: Arial, sans-serif;
        font-size: 10pt;
    }
  </style>
</head>
<body>

    This is some text.
</body>
</html>

All my measurements come from inspect element (using firebug in firefox).

Answer by egrunin

The font sizes are different because the browser programmers make different assumptions about the normal user’s system.

There’s nothing wrong with that, and this is also why you should not use px to set the font size. On a computer with a high-resolution screen, your font will be too small. Certainly 10px will be unreadable on many people’s computers.

I recommend How to Size Text in CSS for a good overview of your choices.

Answer by Starx

Try setting the font size in PX like font-size:10px

Read more
July 16, 2010

What are best practices for removing "friends" from a database?

Question by Josh Smith

Say you have a table schema such as this: friends(friendship_id, uid1, uid2, are_friends).

When one friend un-friends another person, is it best practice to delete that row from the database (and reset auto-incrementing)? Or should you simply change the are_friends status to ‘N’?

I’d love to know what you think and why.

EDIT: My primary concern is showing some information about the state of the friends, and also showing who friended who. That way at the time of the add I can notify the friended of the friender’s request and yet not have them be friends yet.

I had originally had are_friends as a large ENUM with more options. But in that ENUM I had options such as removed and blocked, and I wasn’t sure whether that was truly useful data or not. Any further thoughts on the merits of having more vs. less data?

Also, an added question I’ve had since I posted is how one should avoid duplicating friendships. Should you make (uid1, uid2) a primary key?

Answer by fencliff

Is there any data associated with the friend record you might want to restore, if the user re-friends the other user?

If you want to track their history, or keep some metadata associated with their relationship, then keep the record.

If you don’t want to track their history, and re-friending later doesn’t require user to input any extra data, delete it. You’ll have smaller tables, easier queries, and decreased likelihood you’ll ever forget that where-clause and show the user friends they’ve already deleted.

Answer by Starx

I would suggest to remove the row, because first thing is first, it is unnecessary data to occupy space, and besides the next time the user decides to re-friend with the same friend, then we can enter the data again, if needed.

Read more
July 15, 2010

Split a string array into pieces

Question by arkchong

let said I have an array that store like this.

Array ( 
   [0] => width: 650px;border: 1px solid #000; 
   [1] => width: 100%;background: white; 
   [2] => width: 100%;background: black; 
) 

How should I make the array[0] string split into piece by separated the “;”? Then I want to save them in array again, or display them out. How should I do it?

Array(
   [0] => width: 650px
   [1] => border: 1px solid #000
)

Any idea? Thank in advanced

Answer by animuson

I would personally use the preg_split to get rid of that extra array element that would occur from the final semicolon…

$newarray = array();
foreach ($array as $i => $styles):
    // Split the statement by any semicolons, no empty values in the array
    $styles = preg_split("/;/", $styles, -1, PREG_SPLIT_NO_EMPTY);
    // Add the semicolon back onto each part
    foreach ($styles as $j => $style) $styles[$j] .= ";";
    // Store those styles in a new array
    $newarray[$i] = $styles;
endforeach;

Edit: Don’t add the semicolon to each line:

$newarray = array();
foreach ($array as $i => $styles):
    // Split the statement by any semicolons, no empty values in the array
    $newarray[$i] = preg_split("/;/", $styles, -1, PREG_SPLIT_NO_EMPTY);
endforeach;

Which should output:

Array(
   [0] => width: 650px;
   [1] => border: 1px solid #000;
)

Unlike explode, which should output:

Array(
   [0] => width: 650px;
   [1] => border: 1px solid #000;
   [2] => ;
)

Answer by Starx

An example

foreach($array as $item) {
   $mynewarray = explode(";",$item);
   foreach($mynewarray as $newitem) {
        $finalarray[] = $newitem.";";
   }
   //array is ready
}
Read more

Div max-height too tall

Question by mag725

I am doing some of my first web dev, and had a question about the max-height css property.

Here’s my code:

div{
     max-height:10px; 
}

Whenever I create a new div, everything works fine, but when I add any sort of other element between the div tags, the height of the div increase by around 10 pixels (I’m guessing). Is there any way to override this? I want to have a div with text in it where there is almost no border around the text.

Thanks for any help!
-Matt

Answer by Starx

Sometimes even the default font-size affect the division height. so try overflow:hidden or font-size:10px.

I think this can solve your problem

Read more

Will a page taking 2-3 mins to render cause a javascript 'taking too long' warning

Question by bcm

I’m using the jQuery document ready method – $(function()

If the page takes too long to render (say 2mins+), will this be the reason for the page throwing a javascript taking too long to execute error/warning?

Answer by Igor Zevaka

No. $(function(){}) will get called once the DOM is loaded – i.e. it doesn’t keep running throughout the load process. Unless you are trying to do a long running synchronous task or stuck in a long loop, you shouldn’t get that error.

Have a look at the CPU utilization. If it’s high for the browser, it’s a tell tale sign that there is an infinite loop somewhere.

Answer by Starx

No the document.ready only loads after the DOM is ready (i.e after the jquery core is loaded and ready to be used), so it will not throw any error, if a page takes 2-3 mins.

Read more
July 12, 2010

How many 'includes' is too many as part of a common script startup sequence? Or is there no such thing?

Question by Hammerite

By “common script startup sequence”, what I mean is that in the majority of pages on my site, the first order of business is to consult 3 specific files (via include()), which centrally define constants, certain functions used in many scripts, and a class or two, as well as providing the database credentials. I don’t know if there’s a more standard term for such a setup.

What I want to know is whether it’s possible to have too many of these and make things slower as a result. I know that using include() has a certain amount of overhead because it’s another file to look for in the filesystem, parse, and execute. If there is such a thing as too many includes, I want to know whether I am anywhere near that point. N.B. Some of my pages include() still more scripts that they specifically, individually need (for example, a script that defines a function used by only a few pages), and I do not count these occasional extra includes, which are used reasonably sparingly anyway. I’m only worrying about the 3 includes that occur on the majority of pages and set everything up.

What are the 3 includes?

Two of them are outside of webroot. common.php defines a bunch of functions, classes and other things that do not vary between the development and production sites. config.php defines various constants and paths that are different in the development and production sites (which database to connect to, among other things). Of course, it’s desirable for this file in particular to be outside of webroot. config.php include()s common.php at the bottom.

The other one is inside webroot and contains a single line:

include [path to appropriate directory]/config.php

The directory differs between the development and production sites.

(Feel free to question the rationale behind setting up the includes this way, but I feel that this does provide a good, reliable system for preparing to execute each page, and my question is about whether it is bad to have that many includes as a baseline on each page.)

Answer by bisko

The best thing to do is use an accelerator of some kind, APC or eAccelerator or something like this to keep them cached in RAM. The reasons behind this are quite a few and on a busy site it means a lost.

For example a friend did an experiment on his website which has about 15k users a day and average page load time of 0.03s. He removed most of the includes which he used as templates – the average load time dropped to 0.01 secs. Then he put an accelerator – 0.002 secs per page. I hope those numbers convince you that includes must be kept as little as possible on busy sites if you don’t use an accelerator of some kind.

This is because of the high I/O which is needed to scan directories, find the files, open them, read them and so on.

So keep the includes to minimum. Study the most important parts of your site and optimize there by moving required parts to general includes and so on.

Answer by Starx

I dont believe the performance has anything do with no of includes, because think of a case where one included file contains 500 lines of codes and in another case you have 50 included files with just one line of code each.

Read more

Basic HTML/Javascript – Creating an Image Navigator – How to dynamically load images?

Question by mireille raad

I am buidling a small image navigator where the user inserts an image number and it has to load in the page so he can view it and do some processing on it later.

The images will be physically named 1,2,3,4,5.jpg for example.

Any quick code that i can use to make the corresponding image load

I know this is fairly simple – but i am pretty tight on deadline and would appreciate some code that works

thanks a lot in advance

Answer by Starx

OK, use jquery. It is easy

Here is an example

HTML

<input type="text" id="imagenum" />
<a href="#" class="viewimage">View Image</a>
<img class="previewimage" src="">

The Script

$(document).ready(function() {

       $(".viewimage").click(function() {
          $(".previewimage").attr('src', "imagetopath"+$("#imagenum").val()+".jpg");
       });

       //To catch the enter key
       $('#imagenum').keypress(function(event) {
          if (event.keyCode == '13') {
               $(".previewimage").attr('src', "imagetopath"+$(this).val()+".jpg");
          }
       });

});
Read more

Make a multidimensional array through loop!

Question by esafwan

How can i make an array like below through a loop? The text will generated from database!

 $listofimages = array(
        array(  'titre' => 'PHP',
                'texte' => 'PHP (sigle de PHP: Hypertext Preprocessor), est un langage de scripts (...)',
                'image' => './images/php.gif'
        ),
        array(  'titre' => 'MySQL',
                'texte' => 'MySQL est un système de gestion de base de données (SGDB). Selon le (...)',
                'image' => './images/mysql.gif'
        ),
        array(  'titre' => 'Apache',
                'texte' => 'Apache HTTP Server, souvent appelé Apache, est un logiciel de serveur (...)',
                'image' => './images/apache.gif'
        )
    );

Answer by hsz

Something like :

$listofimages = array();

foreach ( $rowset as $row ) {

    $listofimages[] = array(
        'titre' => $row['titre'],
        'texte' => $row['texte'],
        'image' => $row['image']
    );

}

?

Answer by Starx

do something like this,

$result = mysql_query("SELECT * FROM table;");
while($row = mysql_fetch_assoc($result) {
    //$row will hold all the fields's value in an array
    $mymainarray[] = $row; //hold your array into another array
}

//To display
echo "<pre>";
print_r($mymainarray);
echo "</pre>";
Read more
July 11, 2010

The most strange error in the world (PHP $_GET, $_POST, $_REQUEST and ajax)

Question by Eureka

I hope you’ll able to help me. I’m fed up of trying things without any solution and php it’s just driving me crazy. I’m looking for help because I have a html document where I use ajax thanks to jquery api. Inside this file, in a js function I have:

$.ajax({
type: "GET",
url: "c.php",
data: "dia="+matriz[0]+"&mes="+matriz[1]+"&ano="+matriz[2]+"&diaa="+matriz2[0]+"&mess="+matriz2[1]+"&anoo="+matriz2[2]+"&modo=0&semana=0",
success: Mundo,
error: function(e){
alert('Error: ' + e);
}
});

This code allows me to send the information that I want to the file c.php where I have:


include('funciones.php');
include('config.php');

 $mierda = array();
 $mierda[0] = $_GET['modo']; 
 $mierda[1] = $_GET['dia']; 
 $mierda[2] = $_GET['mes']; 
 $mierda[3] = $_GET['ano']; 
 $mierda[4] = $_GET['diaa']; 
 $mierda[5] = $_GET['mess']; 
 $mierda[6] = $_GET['anoo']; 
 $mierda[7] = $_GET['semana'];   

As you see it’s very simple. My crazy problem is that with firebug I’ve seen that the data is sent well but for some reason I can’t use it. I have tried with $_Get, $_post and $_request and always is the same problem. But this can be stranger… If I put:

echo json_encode($mierda);

then miraculously, the php returns the data that I have passed so in conclusion I have:

  1. I can send the data to the php file well
  2. I can print all the data that I have sent well just accessing yo $_GET, $_POST, $_REQUEST
  3. I can’t use any value separatly like $_GET[‘dia’]

What’s going wrong there?

PS. The include php files are functions that access to my database so there’s no interaction with them.

Answer by Starx

If you are returning a json value use json to read that.

See
http://api.jquery.com/jQuery.getJSON/

http://pinoytech.org/blog/post/How-to-Use-JSON-with-jQuery-AJAX

Here is an example to read json value

$('document').ready(function(){
    $('#submit).click(function(){
        $.post('your_php_page.php', {employee_id: '456'},
            function(data){
                console.log(data.first_name);
                console.log(data.last_name);
            }, 'json');
    })
});

Hope it helps

Read more
...

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