...

Hi! I’m Starx

experienced Software Developer. And this is my blog
Start Reading About me
Blog Page
September 26, 2011

Why isn't my button click event being triggered?

Question by Sheehan Alam

I have the following js file:

var IOMaximizeButton = {
 setup: function () {
    $(this).click(function(){
        console.log("maximize button was clicked!");
    });
  }
};

$(document).ready(function() {
  IOMaximizeButton.setup();
});

Here is the body of my HTML:

 <body>
    <a href="#" data-role="button" data-icon="delete">Maximize</a>
    <iframe id='iframe-primary' name='iframe-primary' src='foo.html' />
    <iframe id='iframe-secondary' name='iframe-secondary' src='bar.html' />
    </body>

I want that javascript to execute when my button is clicked. But it doesn’t seem to be triggering. Why?

I have imported my JS file at the bottom of the HTML page btw.

Answer by James Allardice

In your object, this refers to the instance of the object itself, so you’re trying to bind a click event to the JavaScript object, rather than a DOM element. I’m guessing you actually want something like this:

var IOMaximizeButton = {
 setup: function () {
    $("#yourButton").click(function(){
        console.log("maximize button was clicked!");
    });
  }
};

Here’s a working example.

Answer by Starx

Your function is not attached to any selector, so I cannot catch any events. $(this) is a blank object.

Try changing $(this) to some specific selectors.

Read more

Redirecting a page using Javascript, like PHP's Header->Location

Question by Keith Donegan

I have some code like so:

$('.entry a:first').click(function()
{
    <?php header("Location:" . "http://www.google.com"); ?>
});

I would like to know how I can achieve this using Javascript.

Answer by Starx

You application of js and php in totally invalid.

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

However you can do something like this

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

Read more

Are there any essential reasons to use isset() over @ in php

Question by Tchalvak

So I’m working on cleanup of a horrible codebase, and I’m slowly moving to full error reporting.

It’s an arduous process, with hundreds of notices along the lines of:

Notice: Undefined index: incoming in /path/to/code/somescript.php on line 18

due to uses of variables assuming undefined variables will just process as false, like:

if($_SESSION['incoming']){
    // do something
}

The goal is to be able to know when a incorrectly undefined variable introduced, the ability to use strict error/notice checking, as the first stage in a refactoring process that -will- eventually include rewriting of the spots of code that rely on standard input arrays in this way. There are two ways that I know of to replace a variable that may or may not be defined
in a way that suppresses notices if it isn’t yet defined.

It is rather clean to just replace instances of a variable like $_REQUEST['incoming'] that are only looking for truthy values with

@$_REQUEST['incoming'].

It is quite dirty to replace instances of a variable like $_REQUEST['incoming'] with the “standard” test, which is

(isset($_REQUEST['incoming'])? $_REQUEST['incoming'] : null)

And you’re adding a ternary/inline if, which is problematic because you can actually nest parens differently in complex code and totaly change the behavior.

So…. …is there any unacceptable aspect to use of the @ error suppression symbol compared to using (isset($something)? $something : null) ?

Edit: To be as clear as possible, I’m not comparing “rewriting the code to be good” to “@”, that’s a stage later in this process due to the added complexity of real refactoring. I’m only comparing the two ways (there may be others) that I know of to replace $undefined_variable with a non-notice-throwing version, for now.

Answer by user187291

Another option, which seems to work well with lame code that uses “superglobals” all over the place, is to wrap the globals in dedicated array objects, with more or less sensible [] behaviour:

class _myArray implements ArrayAccess, Countable, IteratorAggregate
{
     function __construct($a) {
       $this->a = $a;
     }

    // do your SPL homework here: offsetExists, offsetSet etc

    function offsetGet($k) { 
        return isset($this->a[$k]) ? $this->a[$k] : null;
        // and maybe log it or whatever
    }
}

and then

 $_REQUEST = new _myArray($_REQUEST);

This way you get back control over “$REQUEST” and friends, and can watch how the rest of code uses them.

Answer by Starx

You answered you question yourself. It suppress error, does not debug it.

Read more
September 21, 2011

How to know route from the URL or $request Object?

Question by mrN

PLOT:

After implementing ACL on my website, if a user tries to access unauthorised page he will be denied and shown a page to login. After he loggs in, I wanted to redirect the user to the previous page to which he was denied to earlier.

To do this, I store the request parameters using $request -> getParams(), onto a session variable, which will be used to generate the url again. This is where the problem occurs, to generate the url back, I need the name of the route and that i dont know how to read.

I need to know the route name, so that I will be able to regenerate the url, from the array stored in session, or if there is a better way to solve this, please suggest.

Answer by Starx

Dont try to think of complex solutions for simple problem.

You can do this, with just using $_SERVER['REQUEST_URI'], this gives the same result as @Phil’s answer (Correct me, If i am missing something). and is more than enough to do what you want.

Read more
September 14, 2011

.getSelection()

Question by Jean

HTML code–

<script language="javascript" type="text/javascript" src="js/jquery-1.4.2.min.js"></script>

<script language="javascript" type="text/javascript" src="js/jquery.field.selection.js"></script>

    <div id="copy">Copy</div>
        <textarea....id="t">

jquery—

$(docu.....
$('#copy').click(function(){
var range = $('#TextArea').getSelection();
alert(range.text);
});

});

When the #copy button is pressed the alert does not show the selected text in #t. It comes in blank.

I need the selected text from the textarea

Answer by Starx

Your code is not running because, this statement fails

var range = $('#TextArea').getSelection();

There is nothing as TextArea as ID in the markup you provided, so the script encounters an error and does not continue beyond it.

If you place the alert at the top part, I am sure the alert box will pop up.
i.e

$('#copy').click(function(){
    alert(''); //this will work
    var range = $('#TextArea').getSelection();
    alert(range.text);
});
Read more

if mouse on hover of div then display menu

Question by PD24

I have the following menu which cascades on hover but i need to add some conditional checks like if the mouse is on hover on the div then keep the menu sliding down.

Also if the mouse is hovered on the LI then check them menu down.

As you can see it just slides down and back up once you leave the “div”.

Im stuck… and have tried for hours searching for if statements etc, i just cant get the syntax correct.

my example

Answer by ShadowScripter

Here is a working example

HTML

<div id="leftWrap">
    <div id='accordion'>
        <ul>
           <li><div>Absorption</div>
               <ul style="display: none;">
                   <li>Accessories</a>
                       <ul style="display: none;">
                           <li>AA500AFG</li>
                           <li>AA500F</li>
                           <li>AA500G</li>
                           <li>AA990F</li>
                       </ul>
                   </li>
                   <li>Consumables</li>
                   <li>Products</li>
               </ul>
           </li>
           <li><div>Fluorescence</div>
               <ul style="display: none;">
                   <li>Accessories</li>
                   <li>Consumables</li>
                   <li>Products</li>
               </ul>
           </li>
       </ul>
    </div>
</div>

Javascript/JQuery

jQuery(document).ready(function() {
    $('#accordion ul > li').hover(function() {
        $(this).children("ul").slideToggle('slow');
    });
});

If you ask me, it gets really messy when you use mousehover/mouseenter for such things. I’d prefer using a click event after the first hover or something, this way the user won’t get annoyed by all that movement.

jQuery(document).ready(function() {
    $('#accordion ul:first-child > li').hover(function() {
        $(this).children("ul").slideToggle('slow');
    });

    $('#accordion ul:not(:first-child) > li').click(function(){
        $(this).children("ul").slideToggle('slow');
    });
});

Answer by Starx

I tried to fiddle in your fiddle, but the markup and css are a lot confusing.

As Rikudo said, you should make the div, its child its much easier to do it that way. I have created a simplest accordion skeleton. You can see it here.

It does everything you want. However for the customizations and others things, I will leave it up to you.

Read more

Changing background onchange on check box: jquery

Question by danny

I am new to jquery and i am having problem i want to change background color of parent div when i click at checkbox

Please Advice

Thank You

<script type="text/javascript">
    function chngbg(id){
        id2 = "d-" + id;
        $(id2).addClass('bg');
    }
</script>

<div class="dataDiv" id="d-<?=$row->id?>">
    <input type="checkbox" onchange="chngbg($(this).val());" value="<?=$row->id?>" name="cbox" /></span>
</div>

Answer by gilly3

You are missing the # in your id selector.

function chngbg (id) { 
    id2 = "#d-" + id; 
    $(id2).addClass('bg'); 
}

By the way, you’ve got an extra </span> that seems like it doesn’t belong.

Answer by Starx

If you are leaning jquery, its better to do such tasks using the following method.

$("#yourcheckboxselector").change(function() {
    id = "#d-" + id;
    $(id).addClass('bg');
});
Read more
September 13, 2011

is it possible to have multiple classes inside php extension?

Question by sunset

I would like to wrapp a .cc code that contains multiple public classes. Is it possible to do that ? how? Do I need to use multiple .cc files one for each class that i want to wrapp?

THX

Answer by Chris

You want to call a C++ class from php? This is incredibly difficult. Usually you have to write a php module (a lot of work). Alternatively you could take a look at Thrift which would let you call your C++ code as a network service (sounds hard, but trust me it’s easier than writing a php module).

Answer by Starx

I wonder what you are attempting to do… if motives were mentioned may be we can help better. Anyways….

To execute a compiled application you can use execute();

$output = exec('/path/to/your/app');

Besides that, you can always write your own php extension….

Check out these tutorials

AFAIK, Many developers use PHP to execute C functions, because it boosts performance quite remarkably.

Read more
September 7, 2011

DB schema for RBAC with multiple levels of roles

Question by blacktie24

I’m trying to come up with a DB schema for an RBAC, and I want to be able to create “departments” and “positions”. Positions will extend the generic privileges of departments. Should I just create a single “roles” table, holding both the positions and departments? Or should I create 3 tables: positions, departments, and roles, with the positions and departments table having a foreign key to the roles table? Thx in advance for your help everyone! Cheers.

Answer by Starx

Standards? This is an unanswerable question, as none such things exists. RBAC is always customized on the basis of the requirements.

You might want to see following resources:

Read more
September 6, 2011

Jquery and old IE versions

Question by GuyFromOverThere

i made my site with Jquery and now if i test it in an old IE version like 5.5 and 6 it completely is filled with errors in javascript. is there a way of getting this problem to stop… and is that error in jquery?

Answer by WTK

Currently as others have already stated, jQuery doesn’t support IE in version less than 6.

BUT, according to this thread back from 2006 (post by John Resig so it should be legit source), jQuery was compatibile with IE 5.5+ in 2006, meaning (based on this history) that you can try to get it working on jQuery 1.0.

Answer by Starx

No and Yes both!

No!, because those old browsers, are so outdated, that they do not recognize the new methods and functions.

Yes!, because JQuery is only compatible above IE 6, not IE 5.5, so most the codes may not work in IE 5.5, as it should.

Read more
...

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