...

Hi! I’m Starx

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

How can I detect if an image object is being displayed?

Question by Mark

When I load an image object in the DOM for large images this will freeze the display for a moment on the iPad.

For testing purpose, let a GIF animation loader spin and add a large image to the DOM, when the image is loaded and added to the DOM you will notice that that GIF animation will freeze until the image is being displayed. This freeze will be enough to disable the CSS3 animation effect on it.

Is there something like

var image = new Image();
image.ready = function() { alert('the image is being displayed.') };

Answer by Starx

You can check if the image has been loaded like this

var img = new Image();
img.onload = function() {
  alert('Done!');
}
img.src = '/images/myImage.jpg';
Read more

PHP: get_called_class() returns unexpected value

Question by J.S.

Using PHP 5.3+ and having something equal to the following I get the output of ‘C’ instead of ‘B’:

class A
{
    public static function doSomething()
    {
        echo get_called_class();
    }
}

class B extends A
{
    public static function doMore()
    {
        self::doSomething();
    }
}

class C extends B {}

C::doMore();

If I had used static::doSomething() that would be the expected result, but when using self::doSomething() I expect this method to get called in the scope of B because it’s where the ‘self’ is defined and not the late static binding.

How is that explained and how do I get ‘B’ in the doSomething() method?

Thanks in advance, JS

Answer by Starx

Override the method doSomething, to get B

class C extends B
{
    public static function doMore()
    {
        B::doMore();
    }
}

Tested

Read more

Mysql addition and add them as new column

Question by Mohan Sinfh

I want to fetch 2 coulmns count and do their total as a new column.
How can I do this?

i wrote this query, but this is returning wrong total.

SELECT count(case when `status`='1' then 1 else 0 end) AS HOT,
count(case when `status`='5' then 1 end) 
AS Special_Case,count(case when 1=1 then 1 end) AS TOTAL 
FROM `tbl_customer_conversation` group by 
date(`dt_added`),user_id

Answer by Starx

COUNT will only give the times a record is matched, which in your query will always return 1. Because the values can either be 1 or 0. So count(1) is also 1 and count(0) is also 1.

AS, you want the total number of HOT cases and SPECIAL_CASE you have to use SUM.

SELECT 
    SUM(case when `status`='1' then 1 else 0 end) AS HOT,
    SUM(case when `status`='5' then 1 end) AS Special_Case,
    SUM(case when `status` = '1' or `status` = '5' then 1 end) AS TOTAL 
FROM `tbl_customer_conversation` 
group by date(`dt_added`),user_id
Read more

Printing UL LI nested in Foreach Loop

Question by HardCode

i have an array structure like

[members] => Members List | 26
[member.php?id=3] => John | 26-26 
[member.php?id=4] => Alice | 26-26 
[member.php?id=5] => Michel | 26-26 
[news] => News details | 45
[alerts] > Alerts | 32

i traverse this using foreach loop. i want to print the Whole list as UL LI. The Members List will be an LI but when its childs comes (memeber.php?id=*) etc then it should inherit UL LI. I want the child to be in a nested LIs

CODE

$counter = 0;
foreach($array as $key => $values)
{
     if($counter == 0)
        {
            echo "<ul>";
        }
    if($key != "" && $key != "END")
        {
            echo "<li>".$values."</li>";
        }
    if($key == "END")
        {
            echo "</ul>";
        }
    $counter++;    
}

Answer by Muhammad Alvin

I don’t know exactly the problem you have. But i think, you want something like this:

<ul>
    <li>
        <a href="members">Members List</a>
        <ul>
            <li><a href="member.php?id=3">John</a></li>
            <li><a href="member.php?id=4">Alice</a></li>
            <li><a href="member.php?id=5">Michel</a></li>
        </ul>
    </li>
    <li><a href="news">News details</a></li>
    <li><a href="alerts">Alerts</a></li>
</ul>

If yes, then i suggest you to change your array structure. Array can also be nested. And it will be easier if you have something like this:

$data = array(
    array('members', 'Members List', array(
        array('member.php?id=3', 'John'),
        array('member.php?id=4', 'Alice'),
        array('member.php?id=5', 'Michel'),
    )),
    array('news', 'News details'),
    array('alerts', 'Alerts')
);
  • $data is array.
  • Items in $data is array with at least 2 items. 1st item is href/url,
    2nd item is label/text. If it has 3rd item, then it will be the
    children (subitems).
  • Subitems is composed similar to items, where 1st item is href/url, 2nd
    item is label/text.

Then, the following code will convert it to HTML:

echo '<ul>';
foreach ($data as $item) {
    // $item[0] -> href/url, $item[1] -> label/text, $item[2] -> subitems
    echo '<li>';
    echo '<a href="' . $item[0] . '">' . $item[1] . '</a>';

    if (isset($item[2])) { // if this item has subitems...
        echo '<ul>';
        foreach ($item[2] as $subitem) {
            // $subitem[0] -> href/url, $subitem[1] -> label/text
            echo '<li><a href="' . $subitem[0] . '">' . $subitem[1] . '</a></li>';
        }
        echo '</ul>';
    }

    echo '</li>';
}
echo '</ul>';

Answer by Starx

Your script is not working, because you have referenced the URLs as $key, but still accessing them using $url inside your loop.

Here is how you should do it.

$counter = 0;
foreach($array as $url => $values)
{
     if($counter == 0)
        {
            echo "<ul>";
        }
    if($url != "" && $url != "END")
        {
            echo "<li>".$values."</li>";
        }
    if($url == "END")
        {
            echo "</ul>";
        }
    $counter++;    
}

But a simple way to create the list from your array is this

//First remove the END key from the array, is not needed


echo "<ul>";
foreach($array as $link => $value) {
   //THERE is no way $link can be ""
   echo "<li><a href="$link">$value</a></li>";
}
echo "</ul>";
Read more

The gap between two inline-block <span> element

Question by chaonextdoor

I created two elements together in html and made each an inline-block. I found that there was always a gap between these two elements but actually I didn’t set any padding/margin attibutes for them. Could someone tell me why and how I can fix this gap?

Answer by Juan G. Hurtado

CSS:

span {
  display: inline-block;
}

HTML:

<span>This will have</span>
<span>a gap between the elements</span>

<span>This won't have</span><span>a gap between the elements</span>

Answer by Starx

This is a weird behavior, which can be fixed, changed your markup to something like this.

<div class="inline">
   first
</div><div class="inline">
   second
</div>

Do not put any space, when defining another inline element.

Read more

How to assign the javascript variable value to php variable

Question by Rana Muhammad Usman

Possible Duplicate:
How to pass JavaScript variables to PHP?

I want to assign the javascript variable to php variable

$msg = "<script>document.write(message)</script>";
$f = new FacebookPost;
$f->message  = $msg;

But it is not working……

Answer by Armatus

Javascript works on the user’s computer, PHP works on your server. In order to send variables from JS to PHP and vice versa, you need communication such as a page load.

Have a look here on what you can do: How to pass javascript variables to php or more specifically the first answer (http://stackoverflow.com/a/1917626/1311593)

Answer by Starx

Javascript, is a client side script, Where as PHP is a server side script.

The only way you can send data to PHP is through redirection or ajax.

Read more

How to pass variable to anonymous function

Question by alexeyb

I want to pass variable setTimeoutfunction and do something with that. When I alert value of i it shows me numbers that i did not expected. What i m doing wrong? I want log values from 1 till 8.

var end=8;
for (var i = 1; i < end; i ++) {
       setTimeout(function (i) {
           console.log(i);   

       }, 800);
   }

Answer by Starx

The main reason for this to not to work, is because, of the setTimeout which is set to run after 800 and the scope of i.

By the time it executes which the value of i will already have changed. Thus no definitive result could be received. Just like TJ said, the way to work this around is through a handler function.

function handler( var1) {
    return function() {
      console.log(var1);  
    }        
}

var end = 8;
for (var i = 1; i < end; i++) {     
   setTimeout(handler(i), 800);
}

Demo

Read more

'div_element' is null or not an object in IE7

Question by nic

here i have get one error in java script ‘div_element’ is null or not an object.
i have given my code below

function showLoading(id) {
div_element = $("div#" + id)[0];
div_element.innerHTML = loading_anim; // Error in this line
}

when i debugging my script so it’s working fine in other browser including IE 8. but it’s not working in IE 7.i don’t understand what exact issue occur in this script.

Thanks in Advance.

Answer by Starx

First of all, you dont need to put a tag name infront of the jQuery, unless you have other elements with exact same id on other elements, in other pages.

Next, your statement div_element.innerHTML = loading_anim; is correct. So, the only explanation is that, there is no element with that ID, in the DOM.

Finally, since you are usign jQuery already, no need to mix up native JS and jQuery to create a dirty looking code.

function showLoading(id) {

    div_element = $("#" + id);
    console.log(div_element); //check the console to see if it return any element or not
    div_element.html(loading_anim);

}
Read more

Pass multiple variables to AJAX onchange select

Question by Student

I am looking at this script from W3schools.com (Ajax, PHP and Mysql)
http://www.w3schools.com/php/php_ajax_database.asp

<html>
<head>
<script type="text/javascript">
function showUser(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  } 
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Select a person:</option>
<option value="1">Peter Griffin</option>
<option value="2">Lois Griffin</option>
<option value="3">Glenn Quagmire</option>
<option value="4">Joseph Swanson</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>

</body>
</html>

This shows a simple select with 4 values.

And this is the PHP script.

<?php
$q=$_GET["q"];

$con = mysql_connect('localhost', '*', '*');
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("ajax_demo", $con);

$sql="SELECT * FROM user WHERE id = '".$q."'";

$result = mysql_query($sql);

echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
<th>Hometown</th>
<th>Job</th>
</tr>";

while($row = mysql_fetch_array($result))
  {
  echo "<tr>";
  echo "<td>" . $row['FirstName'] . "</td>";
  echo "<td>" . $row['LastName'] . "</td>";
  echo "<td>" . $row['Age'] . "</td>";
  echo "<td>" . $row['Hometown'] . "</td>";
  echo "<td>" . $row['Job'] . "</td>";
  echo "</tr>";
  }
echo "</table>";

mysql_close($con);
?>

Now I understand what it does and how it works, but let’s say that I want to pass 3 more variables to the PHP script, when someone changes the value of the selectbox, how do I do that??

Answer by Simon at mso.net

Following on from my comments, here’s an example that takes the values from 2 selects, and submits an ajax call when both are filled in

// Notice the arguments are gone at the moment
function showUser() {
    // Retrieve values from the selects
    var u = document.getElementByID('userSelect').value;
    var g = document.getElementByID('groupSelect').value;

    if (u=="" || g == "") {
        document.getElementById("txtHint").innerHTML="";
        return;
    } 

    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET","getuser.php?u="+u+"&g="+g,true);
    xmlhttp.send();
}

And then the basic form

<form>
    <select name="users" id="userSelect" onchange="showUser()">
        <option value="">Select a person:</option>
        <option value="1">Peter Griffin</option>
        <option value="2">Lois Griffin</option>
        <option value="3">Glenn Quagmire</option>
        <option value="4">Joseph Swanson</option>
    </select>
    <select name="groups" id="groupSelect" onchange="showUser()">
        <option value="">Select a group:</option>
        <option value="a">Aerosmith</option>
        <option value="k">Kiss</option>
        <option value="l">Led Zeppelin</option>
        <option value="m">Metallica</option>
    </select>
</form>

This is not a fantastic option though, and as mentioned would recommend that you into using a framework such as jQuery ( http://jquery.com/ ) as you will be able to spend more time on the logic rather than ensuring browser compatibility

However you go about it though, it doesn’t hurt to experiment so just give some things a try and see what happens (so long as you aren’t deleting live data, anyway)

Answer by Starx

In order to send mutliple values, you have change your query string accordingly.

xmlhttp.open("GET","getuser.php?q="+str,true);

To, something like

xmlhttp.open("GET","getuser.php?q="+str+"&nextvar="+value1,true);
Read more

How to setup CodeIgniter on Ubuntu

Question by user225269

I’m having trouble making my CodeIgniter project work in Ubuntu since I’ve developed it on Windows. My main problem is that I don’t even see any error or warning that can help me determine what the problem is. As you can see it’s just a blank screen. The environment that I’ve declared in the index.php file is development and I’ve also enabled display_errors by setting it to On.

enter image description here

PHP also seems to be working fine since calling php_info() displays something. I believe I’ve also configured mysql properly. I’ve also declared the defaults(host, user, password, port) in php.ini. Can you give me any ideas on how to make something show up?Or something that would allow me to check if I’ve configured things properly. Please help. Thanks!

Answer by user225269

If you’re like me and you have installed Apache, PHP, and MySQL separately using sudo apt-get
then you most likely encounter the same error wherein there is nothing showing up in the logs and on the browser even if you have already set display_errors to on.
What I did was to disable the autoloaded libraries one by one starting from the left.
And my problem was on the database class. Turns out that mysqli and mysql drivers for php isn’t automatically installed when you install php.
All you have to do is to enter the following command:

sudo apt-get install php5-mysql

Doesn’t matter if you have already installed php.

A little help from CodeIgniter could have save me a few hours trying to debug it.

Answer by Starx

The main problem shifting from Windows to Linux development is the naming. Linux distributions are strictly case sensitive regarding almost everything, unlike windows which allows the file indexing, regardless of the case.

First of all to show up something. On the first line of the document index.php

die("Showing Something");

If the message is being displayed, then remove the previous line and add a snippet to show up the errors

error_reporting(E_ALL);
Read more
...

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