...

Hi! I’m Starx

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

Passing URI segments into Codeigniter functions

Question by luckytaxi

Let’s say I have a view method that receives a variable via the URI.

ex. http://www.domain.com/item/view/200

Does it make sense to turn the incoming variable into the correct type? In this case, making $item_id into int which is what is expected.

For example, in the controller …

function view($item_id) {
    if ( $this->item_model->checkItem( (int) $item_id )) {
    ...
    }
}

Answer by Starx

Yeah, casting the variable as integer like you are doing is OK.

And the way to pass the segment into function is like

$segment = $this->uri->segment(2); //get the second segmention
           // ^ You can send a default Values as well if itemid is not set
           // Like: $this -> uri -> segment(2, '0')
//now pass it to the function you need
Read more

animate offset().left

Question by fuey

I’ve been all over the place looking for this. There are some answers out there but none of them work.

All I want to do is slowly move a div to the left when a user does a mouseover on a button.

This works to make the div move:

$("#myDiv").offset({left:-1000});

but all my attempts to animate the move cause the move itself to fail.

Answer by Starx

Use .animate() function like this

$("#myDiv").animate({ left: '-1000' });

Update:
Since your division is floated to the left, you can animate the property using marginLeft instead.

$("#myDiv").animate({ marginLeft: '-1000' });

Demo

Read more
April 25, 2012

Input fieldset with border-radius and shadow not showing all text in IE9

Question by Hommer Smith

I have the following css:

fieldset ul li input {
  width: 96%;
  margin: 0;
  padding: 6px;
  font-size: 13px;
  border: 1px solid #CCC;
  -moz-border-radius: 6px;
  -webkit-border-radius: 6px;
  border-radius: 6px;
  -moz-box-shadow: 0 2px 2px white, inset 0 1px 3px #EEE;
  -webkit-box-shadow: 0 2px 2px white, inset 0 1px 3px #EEE;
  box-shadow: 0 2px 2px white, inset 0 1px 3px #EEE;
}

Which is working under Firefox and Chrome. However in IE9, when I insert some text, I can’t see it completely. As you can see is hidden in the half of it:

IE9 fieldset input problem

Answer by Starx

Either increase the height or the padding.

input {
    padding: 10px;
}
Read more

Why isn't data being returned to the getJSON success handler?

Question by typoknig

I was calling getJSON and looping through the results like this and everything was working great:

$.getJSON( base_url + 'search/drill_down',{
        nextSelectName: nextSelectName,
        thisSelectName: thisSelectName,
        itemId: itemId
    }, function( r ) {
        $.each( r.items, function( k, v ) {
            //do stuff
        });
});

Now on a certain condition I need to return some HTML data, but I still need JSON for my original condition, so I figured I would just encode my HTML as JSON, but the data never returns! The original code still works fine, it is only when I’m trying to return HTML encoded as JSON that things blow up.

$.getJSON( base_url + 'search/drill_down',{
        nextSelectName: nextSelectName,
        thisSelectName: thisSelectName,
        itemId: itemId
    }, function( r ) {

        alert('working!'); // Not hitting this!

        if(r.tabs){
            $.each( r.tabs, function( k, v ) {
            var html = v[ 'html' ];
                return $('#content').html(html); // No need to continue, there is only one HTML string and no items.
            });
        }

        $.each( r.items, function( k, v ) { 
            //do stuff
        });
});

I have a break point on the server (using CodeIgniter) and everything there looks good. I checked checked the HTML I encoded as JSON and it is valid JSON. Why is the JSON generated by my server not making it back to the getJSON success handler?

Answer by Starx

The only explanation is the request was flaud, and reason might be many. One might be requesting on a wrong place. Check using

console.log(base_url + 'search/drill_down');
Read more

FInding out referring page (php)

Question by pg.

At my work I often need to figure out where our traffic comes from. We buy google ads and that traffic gets identified by a query string in the url. (mywebsite.com/?x=”google_ad_group_4″).

On every page I include some sessions stuff that sets $_SESSION[‘x’] to $_GET[‘x’] if $_GET[‘x’] is there. If there is no $_GET[‘x’] I go through some other options to see where they came from and set that in $_SESSION[‘x’]:

$refurl = parse_url($_SERVER['HTTP_REFERER']);
$query = $refurl['query'];
parse_str($query, $result);

if (isset($result['q'])&& strstr($_SERVER['HTTP_REFERER'],'google')) {
    $_SESSION['x'] = 'G-'.str_replace('\"',"X",$result['q']);
}elseif (isset($result['p'])&& strstr($_SERVER['HTTP_REFERER'],'yahoo')) {
    $_SESSION['x'] = 'Y-'.$result['p'];

//took out bing, aol, ask etc in the name of brevity

}else{
    if ($refurl['host']){
        $_SESSION['x'] = $_SESSION['x'].'_ref-'.$refurl['host'];
    }
}

This way I can append the search query that brought the user to the site and what search engine they used. I log the incoming $_SESSION[‘x’]’s.

Many users are coming in with $_SESSION[‘x’]’s of “_ref-mywebsite.com” which doesn’t make sense, if they were coming from my own domain, they’d have already had a $_SESSION[‘x’] set on whatever page they’d been on. Is this because they have their browser’s security turned up high or something?

Am I missing something obvious? Is there a smarter way to do this?

Answer by Starx

You can get the referrer like this

echo $_SERVER['HTTP_REFERER'];

But as mentioned in comment, it can easily be manipulated.

Read more

SELECT command denied to user

Question by dtj

Im getting a funny MySQL error. Here’s whats happening:

query:

SELECT COUNT(id) AS mycount FROM ip_protection.hits WHERE datetime_created>DATE_SUB(NOW(), INTERVAL 10 MINUTE) AND ip='166.248.6.19'

error:

SELECT command denied to user 'goatpric_db'@'166.248.6.19' for table 'hits'

privileges:

GRANT ALL PRIVILEGES ON `goatpric_ip_protection`.* TO 'goatpric_db'@'%'

‘hits’ is a table in ip_protection. Any thoughts?

Answer by Starx

You are using wrong database name everywhere. Use correct Database, which according to your question is ip_protection.

Read more

Captions on an image with CSS

Question by StickFigs

I’m trying to make “meme”-looking captioned images with CSS using an <img> object and two <p> objects styled with CSS. Right now I have a <div> which contains the <img> and then the two <p>‘s. What I want to do is have the picture positioned in the top-left corner of the div and then I set the z-index to -1 and THEN somehow position the two p objects over the image but positioned relative to the top-left corner of the div.

This is so I can set the top: y and left: x values of the p objects such that they will be positioned accordingly relative to the top-left of the div and in turn the image.

But when I try to set position: relative for the p objects there’s a problem where the first p is correctly placed but the 2nd p is positioned relative to the first one so even though it’s at top: 0, left: 0 it’s still lower than it should be.

How can I fix this?

Answer by Kirean

check out this jsfiddle:

http://jsfiddle.net/56J8y/1/

relevant CSS

.meme_container {
 position: relative;   
}
.meme_container .top_meme {
    position:absolute;
    top:0;
    left:0;
}
.meme_container .bottom_meme {
    position:absolute;
    bottom:0;
    left:0;
}

and the html

<div class="meme_container">
<img src="https://www.google.com/images/srpr/logo3w.png"/>
<p class="top_meme">This is a caption 1</p>
<p class="bottom_meme">This is a caption 2</p>
</div>​

Answer by Starx

One way is to use Pseudo element like :after and :before

Example:

img:after {
   content: "Hello, I am the caption";
}
Read more

Seach.php is not working and not showing any results

Question by Erik

I’m trying to figue out how to make my search.php script work with mySQL. I can’t get the information to show up. Not sure where the problem is.

PAGE 1:

<form action="search_result.php" method="GET">
    <input type="text" name="reg" />
    <input type="submit" value="Search" />
</form>

PAGE 2:

<?php
$host="localhost";
$username="XXXXXXXXXXX";
$password="XXXXXXXXXXX";
$db_name="XXXXXXXXXXXX";
$tbl_name="reg_add";
mysql_connect("$host", "$username", "$password") or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");


$record = $_POST['record']; // if coming from e.g. a form
$result=mysql_query(" SELECT * FROM reg_add WHERE reg='" . mysql_real_escape_string($record) . "'");


$row = mysql_fetch_assoc($result);
$first_name = $row['first_name'];
$last_name = $row['last_name'];
$reg = $row['reg'];
?>

<input  name="reg" value="<? echo "$record" ?>">

<input  name="first_name" value="<? echo "$first_name" ?>">

<input  name="last_name" value="<? echo "$last_name" ?>">

Answer by Adriaan

You form is method GET and in your PHP you use this:

$record = $_POST['record']; // if coming from e.g. a form

How are you gonna get the POST[‘record’] if your form has the method GET?

I guess you should or change your form to:

method="POST" 

or change your $record in php to:

$record = $_GET['record'];

Try this version:

You form:

    <form action="search_result.php" method="POST">
    <input type="text" name="reg" id="reg" />
    <input type="submit" name="Submit" id="Submit" value="Search" />
</form>

search_result.php :

<?php

$host       ="localhost";
$username   ="XXXXXXXXXXX";
$password   ="XXXXXXXXXXX";
$db_name    ="XXXXXXXXXXXX";
$tbl_name   ="reg_add";

/* Connect to MySQL database */
mysql_connect("$host", "$username", "$password") or die("Error connecting to database");
mysql_select_db("$db_name")or die("Error selecting database");

$error = '';

if (isset($_POST['Submit'])) {


    if (!empty($_POST['reg'])) {

        $record = $_POST['reg']; // if coming from e.g. a form

        $query = mysql_query("SELECT * FROM reg_add WHERE reg='" . mysql_real_escape_string($record) . "'");
        $result = mysql_num_rows($query);

        if ($result != 0) {

            $row = mysql_fetch_array($query);

            $first_name = $row['first_name'];
            $last_name = $row['last_name'];
            $reg = $row['reg'];

        } else {

            $error = 'No result have been found!';

        }

    } else {

        $error = 'You have not entered the search field, <a href="javascript:history.back(1)">Go back</a>.';

    }
}

if (!empty($error)) { echo $error; } 
?>


<input  name="reg" value="<? echo $record; ?>">

<input  name="first_name" value="<? echo $first_name; ?>">

<input  name="last_name" value="<? echo $last_name; ?>">

Answer by Starx

Syntax of mysql_result() is wrong. According to the manual, it should be

string mysql_result ( resource $result , int $row [, mixed $field = 0 ] )

SO the correct way to use it would be like

mysql_result($result, 1, "first_name");
Read more

MySQL query where item in column a selects item in b, and vice versa

Question by anfuller

I have two columns of data

Refer > Target
1 > 4
1 > 7
2 > 5
3 > 6
4 > 1

I want to run a query in MySQL that selects every refer that is also selected by its target. So, 1 > 4 and 4 > 1.

The furtherest I can get is:

SELECT refer FROM table WHERE refer IN
(SELECT target FROM table)

But that just lists what is in the other column, not what’s matching.

Answer by Starx

I dont think there is a need to over complicate this query

SELECT refer FROM TABLE WHERE (refer = '1' and target = '4') or (refer ='4' and target = '1')
Read more

Disable right click in Galleria Fullscreen theme

Question by user1213807

I’m using Drupal 7 and Galleria fullscreen theme for my images. I don’t want click right and save images. So, i added this code in my jQuery file:

$('img').bind('contextmenu', function(e){
    return false;
});

This function working on my site images but not working on Galleria fullscreen. This is my Galleria fullscreen js:

(function($) {

Galleria.addTheme({
    name: 'fullscreen',
    author: 'Galleria',
    version: '2.0',
    css: 'galleria.fullscreen.css',
    defaults: {
        transition: 'fade',
        image_crop: true,
        thumb_crop: 'height'
    },
    init: function(options) {

        this.addElement('thumbnails-tab');
        this.appendChild('thumbnails-container','thumbnails-tab');

        var tab = this.$('thumbnails-tab');
        var loader = this.$('loader');
        var thumbs = this.$('thumbnails-container');
        var list = this.$('thumbnails-list');
        var infotext = this.$('info-text');
        var info = this.$('info');

        var OPEN = false;
        var POS = 0;

        if (Galleria.IE) {
            this.addElement('iefix');
            this.appendChild('container','iefix');
            this.setStyle(this.get('iefix'), {
                zIndex:3,
                position:'absolute',
                backgroundColor: '#000',
                opacity:.4
            })
        }

        if (options.thumbnails === false) {
            thumbs.hide();
        }

        var fixCaption = this.proxy(function(img) {
            if (!(img || img.width)) {
                return;
            }
            var w = Math.min(img.width, $(window).width());
            infotext.width(w-40);
            if (Galleria.IE && this.options.show_caption) {
                this.$('iefix').width(info.outerWidth()).height(info.outerHeight());
            }
        });

        this.bind(Galleria.RESCALE, function() {
            POS = this.stageHeight - tab.height()-2;
            thumbs.css('top', OPEN ? POS - list.outerHeight() + 2 : POS);
            var img = this.getActiveImage();
            if (img) {
                fixCaption(img);
            }
        });

        this.bind(Galleria.LOADSTART, function(e) {
            if (!e.cached) {
                loader.show().fadeTo(100, 1);
            }
            $(e.thumbTarget).css('opacity',1).parent().siblings('.active').children().css('opacity',.5);
        });

        this.bind(Galleria.LOADFINISH, function(e) {
            loader.fadeOut(300);
            this.$('info,iefix').toggle(this.hasInfo());
        });

        this.bind(Galleria.IMAGE, function(e) {
            fixCaption(e.imageTarget);
        });

        this.bind(Galleria.THUMBNAIL, function(e) {
            $(e.thumbTarget).click(function() {
                if (OPEN) {
                    tab.click();
                }
            });
        });

        this.trigger(Galleria.RESCALE);

        this.addIdleState(thumbs, { opacity:0 });
        this.addIdleState(this.get('info'), { opacity:0 });

        if (Galleria.IE) {
            this.addIdleState(this.get('iefix'), { opacity:0 });
        }

        this.attachKeyboard({
            up: function(e) {
                if (!OPEN) {
                    tab.click();
                }
                e.preventDefault();
            },
            down: function(e) {
                if (OPEN) {
                    tab.click();
                }
                e.preventDefault();
            }
        });

        this.$('image-nav-left, image-nav-right').hover(function() {
            //$(this).animate({opacity:1},100);
        }, function() {
            //$(this).animate({opacity:0});
        }).show();

        tab.click(this.proxy(function() {
            tab.toggleClass('open', !OPEN);
            if (!OPEN) {
                thumbs.animate({
                    top: POS - list.outerHeight() + 2
                },400,'galleria');
            } else {
                thumbs.animate({
                    top: POS
                },400,'galleria');
            }
            OPEN = !OPEN;
        }));

        this.$('thumbnails').children().hover(function() {
            $(this).not('.active').children().css('opacity', 1);
        }, function() {
            $(this).not('.active').children().fadeTo(200, .5);
        }).children().css('opacity',.5)

        this.enterFullscreen();
    }
});

})(jQuery); 

How disable right click in my Galleria fullscreen mode?

Answer by Eduardo Crimi

Did u try using live instead of bind? that way the img that match your selector will have it always

$('img').live('contextmenu', function(e){
return false;

});

Jquery .live()

Hope it helps!

Answer by Starx

Disable the right click like this

$('body').mousedown(function(event) {
    switch (event.which) {
       case 3: return false; break;
    }
});
Read more
...

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