...

Hi! I’m Starx

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

Sorting Images by File Name

Question by user1259527

I want help arranging images. I have this table and I want the images to appear in a certain order, eg B A G D…. (going from left to right).

The code can be found here.

Answer by Starx

See this answer. This is what you might be asking.

I create a perfect modification of that function for you

function sorter(selector, order) {
    selector.each(function() {
        if(order) {
            for(var i =0; i < order.length; i++){                     
               $("#sorted").append($(this).children('img[id='+order[i]+']'));                
            }
        }

    });
}
sorter($("div"), ['a','c','d']);

Check it out

Read more

Is there a way to change the width of the <code> HTML tag?

Question by Yeseanul

I’ve noticed that any modification of the <code>‘s style with respect to its width doesn’t have any effect. It’s seems to always be set to “auto”.

I’m just trying to have some code written inside a <code> tag (this tag is mandatory due to some known iBooks bugs) that has 100% width. One workaround is to put the <code> inside a <div> which has a 100% background style. This works OK but I’ll have to deal with a couple of hundred <code> tags… This is the reason I would prefer just to be able to modify the <code>‘s width.

Any thoughts?
Thanks.

Answer by Rob W

<code> elements are inline elements. Setting a height or width on these do not have any effect on their size.

Use display:inline-block::

code {
    display: inline-block; 
    width: 100px; /* Whatever. The <code>'s width will change */
}

Answer by Starx

Add a display: block or inline-block as per you requirement to the code element. Rest should work as planned

See an example

Read more

Doesn't Internet explorer support $.ajax method?

Question by user1089964

I am getting a problem when I am trying to invoke the $.ajax() method in Internet Explorer.

My code is:

$.ajax({
    type: "GET",
    url: "http://my_server/resource.php",
    success: my_function
});

When I am testing this in any browser I get the proper answer, but if I’m using Internet Explorer, it only takes the url: http://my_server/ where the resource.php part is left out and the response is empty.

Any suggestions? Should I send the resource.php part in the data field?

Answer by Starx

Yes, it DOES work

If that’s your current code, then there is incorrect definition of function . You have to use

success: function() { 
//.....
}
Read more

Set DIV height so that it reaches the bottom of the viewport

Question by Blacksad

How to set the height of this DIV so that it reaches the bottom of the viewport ? The DIV cannot be absolutely positioned ; it’s in the flow.

<html>
   <body>
      Hello world...
      <div>xxx</div>
   </body>
</html>

If there is a CSS solution (which I doubt), it’s great but using JS/jQuery is fine. CSS3 is fine too.

Answer by paislee

Using jQuery:

var h = $(window).height() - $('div').offset().top;
$('div').height(h);

Answer by Starx

Use $(window).height() to get the actual height of the element

$("div").height($(window).height())
Read more

How to increase width of textfield according to typed text?

Question by manishjangir

I want to increase the width of input text field automatically if a user inputs some text in it. But how to do it. Please help me.Can it be using Jquery or javascript

Thanks.

Answer by MatuDuke

Try with this:

<script>
function adjustWidth(obj) {

    obj.style.width = (obj.value.length) * 7.3 + "px";
}
</script>
<input type="text" onkeypress="adjustWidth(this)">

However this depends on text size, font, etc

Answer by Starx

The width cannot be increased as precisely as the width of character vary from one another.

But still, you can do something like this

$("input:text").keyup(function() {
    $(this).css('width', $(this).val().length*10);
});

Demo
As you can see I am assuming that for every character the field size has to be increased by 10px. This is very hard to assign a correct ration that fits all the characters.

Read more

jquery selectors: how to select all li items from some index to the end?

Question by myWallJSON

So we can select one item li:eq('+(lastItemIndex)+')' I wonder how to select this item and all items that are next from it to the end? jsfiddle demo here (in which we would like to change all elements in li from 3 to last one)

Answer by Nicola Peluchetti

You should use nextAll();

var lastItemIndex = 3;
$('li').eq(lastItemIndex).nextAll('li').css("opacity", 0);​

http://jsfiddle.net/LN6ak/2/

Answer by Starx

You can combine :gt and :lt to create yourself a range selector

 $('ul li:gt(2):lt('+$('ul li').length+')')

Demo

Read more

Zend framework Remember Me – working issue

Question by Dubious

I have used the remember me functionality in my site using the following package : http://www.jasperrooswinkel.com/unexpected-expiration-of-zend_auth-sessions/. It is working fine. But I face a problem that, a deleted user can access accounts just because of stay signed in.

The scenario is as follows:

  1. User login after setting keep me logged in.
  2. He leave the system shut down without signing out.
  3. His account being deleted on that day evening.
  4. He takes the site on next day morning.

As he had set stay signed in, he gets his session and he could post a story and do what ever in his account without knowing the fact that his account has got deleted on previous day. Also, I have set remember for 14 days.

Any ideas how to solve this issue?

Thanks

Answer by aporat

Extending the session’s expiration time for more than a few hours is a bad idea for many reasons, not just because you’re keeping sessions of deleted users. There’s also a performance and security issues related to the fact you’re keeping active session (with session_id) in your database / session storage.

See persisted login with Zend_Session::rememberMe.

In any case, you should revalidate your user account on each page load, to make sure his user still exists and active:

I’ve created a revalidate function which I call on every page load. The function is called from the controller’s init() function before the user can do anything.

 public static function revalidate() {
        $userData = self::getIdentity();

        $modelUsers = new Model_Users();
        $user = $modelUsers->fetchWithEmail($userData['email']);

        if ($user instanceof Model_User) {
            if ($user->getRoleType() == 'ACCOUNT') {
                return $user;
            }
        }
        return false;
    }

Answer by Starx

This is exactly why you need to setup a session time out for every application/page.

Use ini_set(), to the the session life time

ini_set("session.cookie_lifetime","1800"); //half an hour

Then check if a session is alive at every secured page like

if (!empty(session_id())) {
    header("Location: index.php"); //GO to home page
    exit;
}
Read more

jEditable – update new values to database

Question by generalsagar

i’m a newbie to web development world. Let me explain what i want.

id  car        make 
1   panamera   porsche  
2   italia     ferraris 
3   avantador  lamborghini  
4   slk        mercedes

I have this simple table in my database and i’m gonna echo this table in a while loop.

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="jquery.jeditable.js" type="text/javascript" charset="utf-8"></script>
</head>

<body>
<ul>
<?php  
$query = "SELECT * FROM inplace LIMIT 0, 6";    
$result = mysql_query($query) or die ('Query couldn't be executed');  
while ($row = mysql_fetch_assoc($result)) {
?>

<script type="text/javascript">
$(function() {
$("#<?php echo $row['id']; ?>").editable("http://www.example.com/save.php", { 
  indicator : "<img src='img/indicator.gif'>",
  tooltip   : "Doubleclick to edit...",
  event     : "click",
});
});
</script>

<?php
echo '<li id="'.$row['id'].'">'.$row['car'].'</li>';
echo '<li id="'.$row['id'].'">'.$row['make'].'</li>'; 
}
?>
</ul>
</body>

I’m trying to use Mika Tuupola’s jEditable edit-in-place jQuery plugin. Here in this code, i have the jQuery code pasted inside the while loop. The first problem here is, only the “car” column is editable. I’m not able to edit the “make” column. And secondly, how do i post(update) the new values to database? Thanks.

Answer by Starx

You are using two elements with same id, which is both semantically and logically incorrect. Hence it is not working as you expected.

Either give same class or differenct ID’s like shown in the following example.

echo '<li id="car'.$row['id'].'">'.$row['car'].'</li>';
echo '<li id="make'.$row['id'].'">'.$row['make'].'</li>';
Read more

How to determine the language of keyboard input using JQuery

Question by Maha Khairy

I have an application that accepts input in two languages (English and Arabic)
I’m validating the input textbox , the validation logic is not the same for English and Arabic, so I need to know what is the language the user is typing

all the solutions I came across determined the default language for the system and browser but nothing I found helped me determining the current input language

Answer by Starx

You can do this using Google’s AJAX Language API

var content = "your text";
google.language.detect(content, function(result) {
  if (!result.error) {
    var language = 'unknown';
    for (lang in google.language.Languages) {
      if (google.language.Languages[lang] == result.language) {
        language = lang;
        break;
      }
    }
    // Now use the variable `language`
  }
});
Read more

String expression in integer result

Question by Maxim Droy

After a lot of operations I’ve got some like:

$exr = "2+3/1.5";

How I can get result of this expression? Like this:

$result = (floatval)$exr; // show: 4

Of course it doesn’t work. I’ve got only 2, first symbol.
Any easy way to solve this?

Answer by Salman A

You can use the PHP eval function like this:

$exr = '2+3/1.5';
eval('$result = ' . $exr . ';');
var_dump($result);
// float(4)

Read this note carefully:

Caution: The eval() language construct is very dangerous because it allows
execution of arbitrary PHP code. Its use thus is discouraged. If you
have carefully verified that there is no other option than to use this
construct, pay special attention not to pass any user provided data
into it without properly validating it beforehand.

Answer by Starx

Eval is EVIL

I dont know why every answer here is telling you to do this? But avoid using this.

Here is very good function that can do the same without the eval() Source

function calculate_string( $mathString )    {
    $mathString = trim($mathString);     // trim white spaces
    $mathString = ereg_replace ('[^0-9+-*/() ]', '', $mathString);    // remove any non-numbers chars; exception for math operators

    $compute = create_function("", "return (" . $mathString . ");" );
    return 0 + $compute();
}

Use it as

$exr = '2+3/1.5';
echo calculate_string($exr);
Read more
...

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