July 31, 2010

jQuery Global variables are not accessible by functions

Question by revive

I have a snippet of code, to calculate the width of some child items and instead of declaring the parentWidth and other variables in EVERY function.. I am trying to create Global variables to be re-used.. but, its not working.

Here is a portion of my code:

$(document).ready(function(){

parentWidth = $(this).parent().width();     // parent width in pixels
margin = parentWidth/100;               // pixel equivalent of a 1% margin
border = 6;                 // 6px total border for each input field 


    $(".element.twoinone input").each(function() {
        $(this).css( 'width',
            (((parentWidth - (margin * 2)) - (border * 2))  / 2)
            + 'px' );
    });
});

The parentWidth, margin and border variables are NOT accessed by the ‘each’ function (which I have multiple of). I’ve tried using live(), livequery(),.. etc.. but, no dice. I know its probably something simple that this noob is overlooking.. so any help is greatly appreciated !!
Thanks!
Also, if you have any input on calculating width percentages based on a parent containers width and accounting for each elements border, margin and qty,.. I’m all ears 😀

UPDATE
Isn’t this:
$(document).ready(function(){

parentWidth = $(this).parent().width();     

    $(".element.twoinone input").each(function() {
        $(this).css( 'width',
            (((parentWidth - (margin * 2)) - (border * 2))  / 2)
            + 'px' );
    });
});

The same as this:

$(document).ready(function(){

    $(".element.twoinone input").each(function() {
        $(this).css( 'width',
            (((     $(this).parent().width()     - (margin * 2)) - (border * 2))  / 2)
            + 'px' );
    });
});

Answer by Starx

Try putting the variables outside the $(document).ready()

July 29, 2010

php script acting weird, shows record even if one does not exist

Question by Krasi

I have a weird problem. Every time i execute this query in php i get the output “Challenge” even if the query is empty (should get “emptyq” if empty) when i test it in phpmyadmin everything is great and query is empty when it should be. I also tried to echo $detectChallengeRes[0][1] and got nothing. I cant find the problem, any help is very appreciated.
The script is suppose to look in the database and check if there is any challenges associated with the current userID, its basically a script that checks if a user has been challenged by another user, the gameID on the current page is the same as the one in the database and that the user hasnt completed the challenge already ($yourscore==0).

$detectChallengeRes = query("SELECT * FROM `AMCMS_challenges` WHERE `gameid`=$gameid AND `winner`=0 AND (`userkey1`=$user OR `userkey2`=$user);");
        if($detectChallengeRes[0][1]!=$user && $detectChallengeRes[0][2]==$user) {
            $yourscore = $detectChallengeRes[0][6]; //Check your score to see if you've already played
        } elseif ($detectChallengeRes[0][2]!=$user && $detectChallengeRes[0][1]==$user) {
            $yourscore = $detectChallengeRes[0][5]; //Check your score to see if you've already played  
        } 
if ($detectChallengeRes!=NULL && $yourscore==0) {
echo 'Challenge';   
} else {
echo 'emptyq';
}

Table structure:

CREATE TABLE IF NOT EXISTS `AMCMS_challenges` (
  `primkey` int(11) NOT NULL auto_increment,
  `userkey1` int(11) NOT NULL,
  `userkey2` int(11) NOT NULL,
  `gameid` int(11) NOT NULL,
  `winner` int(11) NOT NULL,
  `score1` int(11) NOT NULL,
  `score2` int(11) NOT NULL,
  PRIMARY KEY  (`primkey`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

Answer by Starx

This might not solve your question but It looks like it is showing an previous data. Put this before your script

unset($detectChallengeRes);
July 28, 2010

Is there a way to override/rename/remap function in php?

Question by erotsppa

I know it’s possible in other language like C++ or Obj-c even (at runtime AND compile time) but is there a way to override/rename/remap function in php? So what I mean is, let’s say we want to replace the implementation of mysql_query. Is that possible?

SOME_REMAP_FUNCTION(mysql_query, new_mysql_query);

//and then you define your new function
function new_mysql_query(blah...) {
  //do something custom here
  //then call the original mysql_query
  mysql_query(blah...)
}

This way the rest of the code can transparently call the mysql_query function and not know that we inserted some custom code in the middle.

Answer by Cags

I believe if you make use of namespaces you can write a new function with the same name and ‘trick’ the system in that manner. Here’s a short blog I read about it on…

http://till.klampaeckel.de/blog/archives/105-Monkey-patching-in-PHP.html

Answer by Starx

If you have functions inside class. We can override it from other class inheriting it.

Example

class parent {
    function show() {
        echo "I am showing";
    }
}

class mychild extends parent {
    function show() {
        echo "I am child";
    }
}

$p = new parent;
$c = new mychild;

$p->show(); //call the show from parent
$c->show(); //call the show from mychild

how to give two heights to DIV (one for IE and second for other browsers)

Question by JaHelia

In a CSS file, is there a way to give a specific height for a DIV that only applies to Internet Explorer ONLY, and at the same time, give that same DIV another height that applies to all browsers except for Internet Explorer?

Answer by Starx

try this

<style>
    #mydiv { height:800px; }
</style>
<!--[if IE]>
<style>
    #mydiv { height:500px; }
</style>
<![endif]-->

round corners in a image

Question by Kumod

I want to display my images with rounded corners in a web page.
i want to bring the below effect on my image in a page
see the image

Rounded Image

Answer by Starx

For a CSS solution try this

<img src="yourimg.jpg" style="border:1px #000 solid;-moz-border-radius:5px;border-radius:5px;-webkit-border-radius:5px;"/>

Note:
border-radius is a CSS3 tag so it will not work in old browsers

What's faster/more efficient: Continuous Deleting OR Continuous Updating + Intermittent Deleting?

Question by user371699

I have a cron that runs through many rows, deleting the “bad” ones (according to my criteria). I’m just wondering what would be the best to optimize the script. I can do one of the following:

  1. Have the same cron instantly delete the “bad” rows upon finding them.

  2. Have the same cron instantly update the “bad” rows to status “1”, meaning bad. Then, I can set up another cron that runs onces an hour deleting all rows with status “1”. To make it faster, I guess I’d have an index on “status”, but that might also ruin performance.

Any suggestions?

Answer by Juergen Hollfelder

I am not experienced in mySQL but on other DBMS I worked on an update and then delete does not help. Just try with huge amounts of data and measure the time on the delete versus update+delete. It helps if the columns that act as a criteria for the “bad” ones have an index.

Answer by Starx

IF you are thinking of updating a row as bad and then later deleting it, you are putting extra pressure on the server.

Deleting them directly is the better option.

If you think there are going to be huge amount of bad rows, make a cron in such a way that it does not delete more than 100 rows at a time. That should limit the server load to some extend.

Simple CSS Layout

Question by Louis

I need to find a cross browser way of having two divs contained in a parent div where the first child has a fixed height and the second flows down to be contained in the parent.

<div id="parent"><div id="header"></div><div id="body"></div></div>

     height: 500px
 _____________________
|  _________________  |
| |  height: 20px   | |
| |_________________| |
|  _________________  |
| |                 | |
| |                 | |
| |  height: 100%   | |
| |                 | |
| |                 | |
| |_________________| |
|_____________________|

So the parent has a fixed height of 500px, the header div has a fixed height of 20px but the body div’s height must flow down to fit inside the parent. Giving it a height of 100% overflows it’s height by 20px because height:100% uses the parents height not taking into account the children. I saw a solution using position absolute but this does not work on IE7 or 6. Is there a cross browser solution for this as it is a relatively simple layout?

Edit: Forgot to mention that the parent will be resizable so will not always be 500px. Using jquery resizable, the parent dimensions could be anything and will change often.

Edit 2: I wish I could credit multiple people for this solution as I took advice from everyone. Basically I gave #body a height of 480px and used the alsoResize option in resizable to resize the parent and the body.

Answer by loxxy

.parent  { height : auto; }
.child1  { height : 20px;  }
.child2  { height : 480px;  }

Instead of setting the size of the parent dynamically, control child2’s height.

Hope that is what your asking for.

Edit: Edited as per your update!

Answer by Starx

If you already know the height of outer container, and the one of height of the divisions inside, you can know the height of the remaining div I think.

try something like this height: 480px;. Keep it simple and easy

July 25, 2010

From where do i pass id to delete a record?

Question by TCM

How do i pass id to delete record in this code?

<form action="index.php">
        <?php
                     mysql_connect('localhost', 'root', '');
            mysql_select_db('user');
            $query = mysql_query("Select * from tbluser");
            echo "<center>";
            echo '<table style="border:solid 2px black;">';
            while(($row = mysql_fetch_array($query)) != NULL) {
                echo '<tr>';
                echo '<td>' . $row['UserName'] . '</td>';
                echo '<td>' . $row['Password'] . '</td>';
                echo '<td>' . $row['EmailAddress'] . '</td>';
                echo '<td>' . $row['Address'] . '</td>';
                echo '<td>' . $row['Address'] . '</td>';
                echo '<td><input type = "Submit" value = "Delete" name = "btnDel" /></td>';
                echo '</tr>';
            }
            echo '</table>';
            echo "</center>";
        ?>
          </form>

The above code is in index.php and it is submitting it to itself.

Answer by Wrikken

Without needing javascript, seperate GET urls etc, just plain old HTML & the original POST: just add the ID to the name of the button:

<input type="submit" value="Delete" name="btnDel[<?php echo $id;?>]">

And in receiving code:

if(isset($_POST['btnDel']) && is_array($_POST['btnDel'])){
    foreach($_POST['btnDel'] as $id_to_delete => $useless_value){
        //delete item with $id_to_delete
    }
}

Answer by Starx

Use this to submit the id as a part of form.

<input type="hidden" id="id" name="id" value="<? echo $row['id']; ?>" />

or you can send values in URL to do the same thing

An example:

<a href="index.php?action=delete&id=<? echo $row['id']; ?>">Delete</a>

A full working sample

<?
    mysql_connect('localhost', 'root', '');
    mysql_select_db('user');
    switch($_GET['action']) { 
        case "delete":
            $query = "DELETE FROM tbluser WHERE id='".$_GET['id']."'"
            $result = mysql_query($query);
            break;
        //well other actions
    }

    $query = mysql_query("Select * from tbluser");
    echo "<center>";
    echo '<table style="border:solid 2px black;">';
    while(($row = mysql_fetch_array($query)) != NULL) {
        echo '<tr>';
        echo '<td>' . $row['UserName'] . '</td>';
        echo '<td>' . $row['Password'] . '</td>';
        echo '<td>' . $row['EmailAddress'] . '</td>';
        echo '<td>' . $row['Address'] . '</td>';
        echo '<td>' . $row['Address'] . '</td>';
        echo '<td><a href="thispage.php?action=delete&id='.$row['id'].'">Delete</a></td>';
        echo '</tr>';
    }
    echo '</table>';
    echo "</center>";
?>
July 24, 2010

jQuery, Ajax problem?

Question by user303832

I have one table, and when I click on row, it loads some content in another table.

The problem is, when I click on row the first time it loads just one time (message ‘Some msg’ and message ‘Some other msg’ is shown one time). When I click on another row, it loads twice (messages is shown twice). The third time when I click on row it loads three times, etc.

Here is my code:

$("#myTable tr").click(function(e){
    $.ajax({
        url:'<?php echo $full_path_ajax_php; ?>',
        data:{'what':'2','mypath':'12345678'},
        dataType:'json',
        type: 'GET',
        beforeSend:function(){alert('Some msg')},
        success: function(){alert('Some other msg')}
    });
    return false;
});

Answer by Starx

You need to use the .live() function in the parent table but don’t use this code in the portion which you are going to use:

$("#myTable tr").live('click', function(e){
    $.ajax({
        url:'<?php echo $full_path_ajax_php; ?>',
        data:{'what':'2','mypath':'12345678'},
        dataType:'json',
        type: 'GET',
        beforeSend:function(){alert('Some msg')},
        success: function(){alert('Some other msg')}
    });
    return false;
});

Remember, only once in the parent page or table.

July 23, 2010

PHP: open a file download dialog

Question by Hugh Valin

I have an MPEG file (.mpg) hosted in Amazon S3, that I want to link to a page I have, so the user will be able to download it from the page.
I have in my page a link:
bla bla

The link to the file works when I right-click it and choose “Save Target As” , but I would like it to work also when I left click it, and that it will open a file download dialog. right now, a left click will direct to a page that has the video directly played in it (in FireFox) or just won’t load (in Internet Explorer).

I am working in PHP, why does this happen?

Answer by Starx

Use this:

download.php?movie=moviename.mpg
header('Content-disposition: attachment; filename='.$_GET['moviename.mpg']);
exit();

This will force the download box for whatever movie you have.

...

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