...

Hi! I’m Starx

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

Why bind and unbind don't work as expected

Question by Ayen

I was originally doing this:

$('div.ocontainer').each(function() {
    var o = $(this);
    var newCode = $(this).attr('id');
    if (o.parents('.ocontainer').length != 0) {
        var oldCode = o.parents('.ocontainer').attr('id');
        console.log('unbinding '+oldCode);
        $('#'+oldCode+' a').each(function() {
            $(this).unbind('click')
            })
    }
    console.log('binding '+newCode);
    $('#'+newCode+' a').each(function() {
        $(this).click(function() {
            decideStMethod(newCode);
        })
    })
})

…but the unbind was not working. I ended up with the original code being passed in the click function. So I changed to using name spaced events:

$('div.ocontainer').each(function() {
    var o = $(this);
    var newCode = $(this).attr('id');
    if (o.parents('.ocontainer').length != 0) {
        var oldCode = o.parents('.ocontainer').attr('id');
        console.log('unbinding '+oldCode);
        $('#'+oldCode+' a').each(function() {
            $(this).unbind('click.'+oldCode)
            })
    }
    console.log('binding click.'+newCode);
    $('#'+newCode+' a').each(function() {
        $(this).bind('click.'+newCode,function() {
            decideStMethod(newCode);
        })
    })
})

…and now the unbind works but the subsequent bind does not. Note, though, that the line that is doing the bind DOES work if it’s not subsequent, that is, if it is not preceded by an unbind.

The use of this is that first a region of the page is processed, and the binding is done on the links within it. Then, the subregions are processed, and if one of them has its own code, the region’s handler must be unbound and replaced with the subregion’s. The reason for all of this is that the subregions are placed in the region dynamically, so what they will be is never known in advance. Oh, and just in case it matters, this is jQuery 1.72

So:

<div id="region" class="ocontainer">
   <div id="subregion" class="ocontainer">
      <a>

On the processing of region, the link is bound to click.region and a function passing ‘region’. Then, click.region should be unbound, which it is, and click.subregion bound in its place with a function passing ‘subregion’, which does not happen.

Answer by Starx

First thing is first, bind() and unbind() are deprecated functions. Use .on() and .off() instead.

Here is an example with some improvements too.

$('div.ocontainer').each(function() {
    var o = $(this);
    var newCode = o.attr('id'); //Use cached version instead
    if (o.parents('.ocontainer').length != 0) {
        var oldCode = o.parents('.ocontainer').attr('id');
        console.log('unbinding '+oldCode);
        $('#'+oldCode+' a').each(function() {
            o.off('click', "#"+oldCode); //Turn off the event handler
        })
    }
    console.log('binding click.'+newCode);
    $('#'+newCode+' a').each(function() {
        $(this).on('click', "#" + newCode, function() {
            decideStMethod(newCode);
        })
    })
})
Read more
October 1, 2012

PHP .htacces and index.php redirection

Question by Emann Tumala Saligue

I am new about this redirection and I want to know how it works?
I have some file called index.php and i want to hadlle it any directory in the site

 index.php

<?php 
    if(empty($dir)){
    include('includes/home.php');
    }  
    if($dir=='profile'){
    include('includes/profile.php');
    }
    elseif($dir=='settings'){
    include('includes/settings.php');
    }
    else{
    include('includes/404.php');
    }
    ?>

The url is:

test 1. www.example.com/ - will view the include home.
test 2. www.example.com/settings - will view the include  settings.
test 3. www.example.com/errorsample - will view the include   404 page.

How to make .htaccess and index.php using that code or any idea how it works and sample code of it.

Answer by Starx

I will try to explain this with a simple example. Consider the following .htaccess file

Options +FollowSymLinks
RewriteEngine On
RewriteRule ^(.*)$ /index.php?x=$1 [L] 
#  ^ This is the rule that does the redirection

What it does is, it routes every url request and sends the request to index.php. How it send it? I will show couple of example to do that.

  • www.example.com/settings will be send as www.example.com/index.php?x=settings
  • www.example.com/errorsample will be send as www.example.com/index.php?x=errorsample

So, now you are configure your index.php and decided what you want to do, with the value you get in $_GET['x']

switch($_GET['x']) {
   case "profile": include("include/profile.php"); break;
   // .... similarly other cases
   default: include("includes/home.php"); break;
}

}

Read more

setting the width of my footer to 100% shows a scrollbar

Question by bigollo

Although I set the width of my footer to 100%, there it extends to more than 100% having a scroll bar in terms of width. Any ideas why? I know the problem is the width because when I remove the 100%, it does not show the scroll bar. The page is broken down to body>wrapper>footer
Here is my code:

 #footer {
  margin-top: 30px;
  color: white !important;
  padding-bottom: 15px;
  background: black;
  text-align: center;
  padding: 20px;
  height: 40px;
  min-width: 1000px;
  width:100%;
  position:absolute;
  bottom:0;
}

And there is the body css:

body {
  font: normal 12pt Georgia, serif;
  color: #111;
  background: #990000;
  margin: 0 auto;
  text-align: center;
  background-position: 50% 50%;
  min-height: 100%;

  margin:0;
    padding:0;
    height:100%;
}

And the wrapper css:

#wrapper {
    min-height:100%;
    position:relative;
}

Answer by Starx

This is happening because of the padding. See the illustration of your problem here.

When you use padding, the size gets added to the total height and width respectively.

Removing the padding will fix your problem. Demo

 #footer {
  margin-top: 30px;
  color: white !important;
  background: black;
  text-align: center;
  height: 40px;
  min-width: 1000px;
  width:100%;
  position:absolute;
  bottom:0;
}

Another good solution is to make the browser treat your element differently. by using box-sizing property.

 #footer {
  /* Add box-sizing */
  -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
  -moz-box-sizing: border-box;    /* Firefox, other Gecko */
  box-sizing: border-box;         /* Opera/IE 8+ */
  margin-top: 30px;
  color: white !important;
  padding-bottom: 15px;
  background: black;
  text-align: center;
  padding: 20px;
  height: 40px;
  min-width: 1000px;
  width:100%;
  position:absolute;
  bottom:0;
}

Demo

Read more
September 30, 2012

how to prevent script tags in zend form

Question by Awais Qarni

Hi there I am just testing my own developed application and got a problem. I entered

<script>window.location = "http://www.google.com";</script>

in Zend_Form_Element_Text element. I pressed submit and the value is saved. After saving value I redirect the user to listing and when it redirects to listing, script tag executes and it goes to google.com.

My form element looks like

 $first_name = new Zend_Form_Element_Text('first_name');
 $first_name->setRequired(true)
            ->addFilter('StringTrim')
            ->addValidator('StringLength', false, array(2, $metaData['first_name']['LENGTH']))
            ->setDecorators(array('ViewHelper', 'errors'));

I want to know how can I prevent the user to enter such kind of values? Is there any built in validation or any other way?

Answer by vascowhite

Well done for testing your app, many people don’t bother. Don’t worry about storing that string in your database it won’t do any harm and changing it may give you problems with other, valid, entries. As vstm says, escape it when you use it.

However, as you are specifically talking about a ‘First Name’ field there is probably some more validation that you can do, such as rejecting any names with a / in them. I’m not aware of any language that has that as part of a name. If there is, I’d love to know how it’s pronounced. You could probably add . = and some others to that list too, but don’t get too carried away.

You should carefully consider every field in your form with regards to what input you would reasonably expect to receive and validate the input accordingly. Anything that doesn’t pass validation is rejected. A string like '<script>window.location = "http://www.google.com";</script>' should certainly never pass validation for a field expecting a person’s name.

Personally, I never filter input. It either passes validation and is accepted, or it doesn’t and is rejected. I can’t make good input out of bad input by filtering it, so it gets rejected and the user is asked to re-enter their data. For example, using a StripTags filter on

<script>window.location = "http://www.google.com";</script>

will leave you with

window.location = “http://www.google.com”;

which is still not a valid name and should be rejected.

Your validation will never work 100% of the time and that is why you should always escape values received from user input before echoing them out to the browser.

Zend Framework has a raft of validators that you could use and don’t forget the validators and filters that PHP has already available for you. Use them properly and you will greatly reduce the risk of malicious input hurting either your application or, more importantly, your users.

Those validators and filters are there for you to use, but neither PHP nor Zend Framework know what kind of data you are expecting, so it is very important that you read the documentation and learn exactly how they work, how to use them and when to use them.

There is an excellent resource at The Web Application Security Project that every web dev should be forced to read on pain of death.

tl;dr
Validate input and escape output.

Answer by Starx

You can use filters to restrict input from the user. Read about the filters

There is a filter in Zend Framework called Zend_Filter_StripTags which will give you the option to strip all or selected tags. Here is an example from the site itself.

$filter = new Zend_Filter_StripTags();     
print $filter->filter('<B>My content</B>'); 

As result you will get the stripped content ‘My content’.

On your case the following

$first_name->setRequired(true)
            ->addFilter('StringTrim')
            ->addFilter('StripTags') //Here a add a filter to strip tags
            ->addValidator('StringLength', false, array(2, $metaData['first_name']['LENGTH']))
            ->setDecorators(array('ViewHelper', 'errors'));
Read more

How will I compare a text input if it is empty or not?

Question by eggshot

How will I compare a text input if it is empty or not inside a Jquery statement? Is the code below alright?

$(#'generate').click(function(){
   if(parseInt($('#lastname').val,10)==0){
      alert("Should Not Be Empty!");
   }
}

Answer by Starx

Simply

$('#generate').click(function(){
    if($('#lastname').val().trim() != "") {
       alert("Should Not Be Empty!");
    }
}

Also, there is a typo

  $(#'generate').click(function(){
//   ^   Right here
Read more
September 28, 2012

Difference between typing and pasteing in a field

Question by Ferenc Dajka

If I use xss, what’s the difference between typing in ALERT(‘DSSA’);, or just paste it to a search textfield? In a site, typing works, and makes the alert, but if I just paste it, than it doesn’t. To prevent the question, I don’t want to hack any site, I’m just interested in network security.

thanks for the answer

Answer by Starx

I may not have understood the question properly.

Typing triggers keyUp, keyDown and keyPress events on the element. If the codes are programmed to capture them only, then only those events will be captured.

Pasting can be done using keyboards, mouse and browser options. So this depends on which events you are listening too. There is a separate event called onpaste which will ease everything.

What I mean is, lets say my code is written to capture the pasting my pressing “Ctrl” + “v” only, but if mouse and browser options are used to paste on the
element, then it is configured to capture mouse events also, it cannot
be captured.

Read more

Why can't I override existing pseudo-elements?

Question by DanMan

I have two CSS rules following each other:

.some td:first-child:before {
    content:url('path/to/image.png')" " ;
}
.some .other:before {
    content:url('path/to/image2.png')" " ;
}

Here’s the HTML snippet:

<table class="some">
<tr>
    <td class="other">Text goes here</td>
    <td>Some more text.</td>
</tr>
</table>

They’re both supposed to be applied to the same table cell. The one without the class is meant as a fallback. But for some reason, it’s always choosing the first rule over the second. I know the 2nd one works, since it will be used if i disable the first one in Firebug.

What am I missing here?

Answer by DanMan

Ok, to put this straight, after some reading, this is the specificity:

  • Id: 100
  • classes: 10
  • pseudo-classes: 10
  • pseudo-elements: 1
  • elements: 1

So that makes the first selector have a specificity of 22, and the 2nd of just 21. Apparently first-child seems to be a pseudo-class and not a pseudo-element.

Finally, adding a td before .other does the trick, since then document order takes precedence.

Answer by Starx

The first rule is more specific than the second one, so in a case when both the selectors are valid, the more specific one overrides other.

Read this article to know how can we overcome such complications of having conflicting styles. To brief them, Here is how specificity are calculated.

+--------------------+--------------------+-----------------------------------+
|    Type            |   Specific Value   |  Example                          |
+--------------------+--------------------+-----------------------------------+
|  Inline Style      |   1000             | style="color: #f00;"              |
+--------------------+--------------------+-----------------------------------+
|  Id                |   100              | #text { color: #f00; }            |
+--------------------+--------------------+-----------------------------------+
|  Classes           |   10               | .text { color: #f00; }            |
+--------------------+--------------------+-----------------------------------+
|  Pseudo Classes    |   10               | a:hover { color: #f00; }          |
+--------------------+--------------------+-----------------------------------+
|  Pseudo Elements   |   10               | a:first-child { color: #f00; }    |
+--------------------+--------------------+-----------------------------------+
|  Elements (tag)    |   1                | a { color: #f00; }                |
+--------------------+--------------------+-----------------------------------+

Basically, Class Selectors are more specific than tag selectors.
Lets calculate your specificity

  • For first rule: 31
  • For second rule: 30

SO the first rule wins.

You can increase the specificity of the second rule like

.some tr td.other:before {
    content:url('path/to/image2.png') ;
}

Its calculate to 33, to override the style first rule.

Read more
September 26, 2012

Zend Framework: Page not found

Question by José Carlos

I have developed a web application with Zend Framework which root is http://www.demo31.com/validacion/demo31/ but when I call that url I’ve got the next error:

Page not found

Request Parameters:

array (
  'controller' => 'validacion',
  'action' => 'demo31',
  'module' => 'default',
)

I want that the values of array would be next:

array (
  'controller' => 'index',
  'action' => 'index',
  'module' => 'default',
)

And my .htaccess is correct.

So, what do I have to do what I want?

Answer by Starx

Zend framework normally operates as per routes. If a particular URL is not reaching your code, then you have to configure routes to do that.

    $router = $front -> getRouter();
    $routePage = new Zend_Controller_Router_Route('/:controller/:action', array(
    /*                                             ^ Things to notice
                                                     Only two parameters are 
                                                     asked from the route */
        'controller' => 'default',
        'action'    => 'index',
        'module'    => 'default' //Predefine the module as `default
    ));
    $router -> addRoute('default', $routePage);
Read more
September 25, 2012

Should I place a semicolon at the end of my jQuery statement?

Question by Marilou

Possible Duplicate:
Do you recommend using semicolons after every statement in JavaScript?

I have the code like this:

$("#delete_" + row)
   .attr('data-href', '/Admin/' + tab + 's/Delete' + params)
   .attr('title', 'Delete ' + id);

It’s typical of the code I have everywhere in my application. What I notice is that it seems to work with or without a semicolon at the end. Is there any advantage for formatting or any other reason that I should put a semicolon at the end?

Answer by Explosion Pills

Always put the semicolon. Not only is it more cross-browser compatible, it’s easier to minify (removing newlines is part of that).

Answer by Starx

Semicolons, although not required in JavaScript, denote end of statement. So its a good habit of ending a statement with semicolon at the end. Other point, Explosion Pills has already mentioned.

Read more
September 23, 2012

Understanding parameter 'e' and e.pageX/e.pageY

Question by user1692159

function smtMouseMove(e){
    smtMouseCoordsX=e.pageX;
    smtMouseCoordsY=e.pageY;
    smtTipPosition();
}

function smtTipPosition(e){
    var thePosX=e.pageX+20;
    smtTip.css("left",thePosX);

    var thePosY=smtMouseCoordsY+20;
    smtTip.css("top",thePosY);

}

If I have this: var thePosX=e.pageX+20; I gat the error that parameter e is undefined. But if I write var thePosX=smtMouseCoordsX+20; everything is ok. What do I miss in here?

Answer by Starx

On your function declaration, you are asking a parameter e to be sent.

function smtTipPosition(e) {}

But, you are not sending the parameter on your execution.

function smtMouseMove(e){
    smtMouseCoordsX=e.pageX;
    smtMouseCoordsY=e.pageY;
    smtTipPosition();
               // ^ Right here, you have to send the parameter 'e' too
}

Implementing something like this, should fix the problem.

function smtMouseMove(e){
    smtTipPosition(e);
}

function smtTipPosition(e){
    var thePosX=e.pageX+20;
    smtTip.css("left",thePosX);

    var thePosY=smtMouseCoordsY+20;
    smtTip.css("top",thePosY);

}

Generally, e refers to an event object. It has to be initiated or passed on by some event or function. On you case also, function setMouseMove and smtTipPosition both require a event object for its execution.

Lets see a simple example

$("a").click(function(e) {
    //Here `e` will hold the event object of the page, when any `a` on the page will be clicked
    console.log(e.pageX); //Calling this will give the x coordinates of mouse position on the page, when the `a` was clicked
});
Read more
...

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