...

Hi! I’m Starx

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

How to week of the year and use it as image source?

Question by Will Gibbons

What I am trying to do is show a jpg for each week in the year depending on what the date is. Does anybody know why this does not work?

Date.prototype.getWeek = function() {         
var onejan = new Date(this.getFullYear(),0,1);         
return Math.ceil((((this - onejan) / 86400000) + onejan.getDay()+1)/7);     
}       

var weekNumber = (new Date()).getWeek();

var test='<img src="C:/temp/ + weekNumber + .jpg"/>';
document.write(test);

Answer by Starx

Here is a function to get the week number.

function getWeekNumber(d) {
    // Copy date so don't modify original
    d = new Date(d);
    d.setHours(0,0,0);
    // Set to nearest Thursday: current date + 4 - current day number
    // Make Sunday's day number 7
    d.setDate(d.getDate() + 4 - (d.getDay()||7));
    // Get first day of year
    var yearStart = new Date(d.getFullYear(),0,1);
    // Calculate full weeks to nearest Thursday
    var weekNo = Math.ceil(( ( (d - yearStart) / 86400000) + 1)/7)
    // Return array of year and week number
    return weekNo;
}

Credit: RobG

Use the above function to get the number and use in your script

weekNumber = getWeekNumber(new Date());
var test='<img src="C:/temp/' + weekNumber + '.jpg"/>';
document.write(test);

Demo

Read more

SubPaging Php with if else

Question by ElDiabl

I’m having a hard time passing values so here is the code:

These is the code to pass the values($vview is the container of the value) to be used when showing the sub page: from enrollalpha.php

   if(!empty($_POST['Vpanel'])){
             $vview = $_POST['Vpanel'];
             }else {
                 if(!empty($_GET['VPanel'])){                
                 $vview= $_GET['VPanel'];
                }else{
                 $vview= 'VS';
                }
             }

And this is the codes where $vview is to be used

if($vview == 'VS'){
            require_once 'vpanel_student.php';
        }
        else if($vview == 'VA'){
            require_once 'vpanel_adviser.php';
        }
        else if($vview == 'VA'){
            require_once 'vpanel_adviser.php';
        }else{
            require_once 'vpanel_student.php';
        }

let us assume my subpage now is showing vpanel_adviser.php at the said page i have this code:

    else if(empty($_GET['id'])){
               header("location:enrollalpha.php?&VPanel='VA'");

            }

So at enrollalpha.php remember i have this

    if(!empty($_GET['VPanel'])){                 
             $vview= $_GET['VPanel'];
            }else{
             $vview= 'VS';
            }

my current problem is when vpanel_adviser.php returns the user to enrollalpha.php it is not showing vpanel_adviser.php but shows vpanel_student.php Would appreciate any help on this.

Answer by Starx

You dont need to quote the value in the URL and unneeded “&” in the URI string.

header("location:enrollalpha.php?&VPanel='VA'");
                              // ^   &   ^ Here

Change to

header("location:enrollalpha.php?VPanel=VA");
Read more
October 7, 2012

What's the best way use caching data in js on client side?

Question by artzub

My application receives data from the another server, using API with limited number of requests. Data changing rarely, but may be necessary even after refresh page.

  1. What’s the best solution this problem, using cookie or HTML5
    WebStorage?
  2. And may be have other way to solve this task?

Answer by Starx

As much as cross browser compatibility matters, cookie is the only choice rather than web storage.

But the question really depends on what kind of data you are caching?

For what you are trying, cookie and web-storage might not be needed at all.

  • Cookies are used to store configuration related information, rather than actual data itself.
  • Web storage supports persistent data storage, similar to cookies but with a greatly enhanced capacity and no information stored in the HTTP request header. [1]

I would rather say, it would be stupid to cache the entire page as cookie or web-storage both. For these purposes, server-side caching options might be the better way.

Update:

Quoting:

data about user activity in some social networks (fb, vk, google+)

Detect the web-storage features, using libraries like mordernizr and if does not exists fall back to cookie method. A simple example

if (Modernizr.localstorage) {
    // browser supports local storage
    // Use this method
} else {
    // browser doesn't support local storage
    // Use Cookie Method
}

[1]: http://en.wikipedia.org/wiki/Web_storage

Read more

$row['id'] – undefined index

Question by kdot

I am new to PHP. I am practicing how to delete a row in mysql using PHP.

I have this code:

<?php

$con = mysql_connect("localhost","root","");

mysql_select_db("usersdb", $con);


echo "<table border='1'>
<tr>
<th>USERNAME</th>
<th>PASSWORD</th>
<th>ACTION</th>
</tr>";

$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['username'] . "</td>";
echo "<td>" . $row['password'] . "</td>";
echo "<td>";
echo '<a href="index.php?delete='.$row['id'].'">Delete</a></html>';
echo "</td>";
echo "</tr>";
}
echo "</table>";

if(isset($_GET['delete']) and is_numeric($_GET['delete']))
{
    mysql_query("DELETE FROM Persons WHERE `id` = '".$_GET['delete']."'");
}

?>

When I tested it on the browser, it gives this error:

Notice: Undefined index: id in C:wampwwwindex.php on line 22

The error is pointing at the $row[‘id’]. I tried to defined it as $id = $row[‘id’] and replace $id on the line where $row[‘id’] is located. But in the end, I still get the same error. How can I solve this kind of error?

Answer by Starx

It means your data row, does not have a column named id or it can’t find it for some reason.

Verify this, by doing a print_r($row) inside the loop like this.

$result = mysql_query("SELECT * FROM users");
while($row = mysql_fetch_array($result))
{
    print_r($row);
}
Read more

Use PHP to rewrite the address bar?

Question by Hoser

Maybe I’m going about this the wrong way, but I’ll lay out the process I’d like my website to perform and then see what solutions you guys can think of.

At the URL

example.net/ShellySite/Form/form.php

There is a form to be filled out, then a submit button is pressed, and the website goes to

example.net/ShellySite/Controller/PHP/submitform.php

It goes here because it submits the details in the form to a database, what I’d like to do is basically instantly reroute the browser to a different page after the code at the submitform.php page has finished running, something like

example.net/ShellySite/Home/home.php

But I can’t seem to get it to work. I’ve tried stuff like header(Location:"example.net/ShellySite/Home/home.php")
but it just appends all that onto the end of example.net/ShellySite/Controller/PHP/submitform.php, and that obviously isn’t what I want.

Any help would be great!

Answer by deceze

Use absolute URLs:

header('Location: http://example.net/ShellySite/Home/home.php');

Answer by Starx

Rewriting can be done with .htaccess what you are looking for in redirection.

Since, you are trying to use absolute URLs, You are missing protocol in your request. Like http and https. Add them

header('Location: http://example.net/ShellySite/Home/home.php');
exit; // Dont forget to add this

Or use relative URLs like

header('Location: /ShellySite/Home/home.php');
exit;
Read more

hide p element if empty

Question by user1726062

I want to use jQuery to hide a p element with class of .last_edit if the p element is empty. example

<p class="last_edit"></p>

<p class="last_edit">This would be displayed since there is text in it</p>

Does anyone know how t

Answer by Starx

There are many ways

$(".last_edit:empty").hide();

or

$(".last_edit").each(function() {

    if($.trim($(this).html()).length > 0) {
       $(this).hide();
    }

});
Read more
October 6, 2012

How to deliver different Responsive Images?

Question by MEM

On this website:

  • .php

  • .jquery

  • .yii based

We need to have two or more different infographic pictures, depending on the viewport width.

  • The client is picky about w3c validation

  • picturefill solution doesn’t validate

  • different images and not only different image version, should be served

  • for a lot of reasons background images are not a solution*

  • IE8 and up support

I can use either a server or client side version, no problem.

Reasons:

  1. Background image technique does work, but those infographics are NOT background.

  2. They should arrive server side.

  3. Obviously, they need to adapt. (and background size… well…)

  4. Even worst, we do have responsive tooltips image maps associated with those infographics.

Answer by Starx

If media queries is not what you want then use response.js, if done properly you can load <img>s too. Here is a example:

<-- Load lo-fi.png  when viewport is 0–480px wide or no-js. 
    Load medium.png when viewport is 481–1024px wide. 
    Load hi-fi.png  when viewport is 1025px+ wide. --> 

<img src="lo-fi.png" data-src481="medium.png" data-src1025="hi-fi.png" alt="example" />
Read more
October 5, 2012

What is the best way to make entire web page links non clickable

Question by Codemator

Possible Duplicate:
Override default behaviour for link ('a') objects in Javascript

What is the best way for making entire page links in home page read only (non clickable like href=# or href="javascript:void()" based on a user action.

I wanted to use only Javascript and CSS to achieve this.

Answer by Veli

try

with jquery

$("a").click(function() { return false; });

vanilla js

        var elements = document.getElementsByTagName("a");
        for (var i = 0; i < elements.length; i++) {
            elements[i].onclick = function () { return false; }
        }

Answer by Starx

Here is a wonderful solution by CMS, by using event delegation technique.

document.onclick = function (e) {
  e = e ||  window.event;
  var element = e.target || e.srcElement;

  if (element.tagName == 'A') {
    someFunction(element.href);
    return false; // prevent default action and stop event propagation
  }
};

Demo

Read more
October 3, 2012

Rewrite rule in htaccess for mobile version

Question by Soumya Mohanan

I am using codeigniter framework for my site and I have done two site one for accessing through mobile and another for accessing through pcs. both are in same domain . My site url is like this http://mydomain.comAnd my mobile is http://mydomain.com/celphone. I need to write htaccess rule which redirect to site url http://mydomain.com/celphone when i am accessing site from mobile and i need to rewrite to http://mydomain.com/ when i am accessing the site from pc.

How can i write rewrite rule in such case ,please help any help will be appreciated.

Answer by Starx

As scessor, said, it cannot be done with .htaccess. You need to analyse the browser’s user agent for this.

Check out this mobile detection in php.

Usage is as easy as this

if ($detect->isMobile()) {
    header("location: mobile.yourdomain.com");
    exit;
}
Read more

How to replace style with javascript that has already been set?

Question by vusan

I’m implementing menu that is selected by the help of javascript. In jsfiddle.
Blocks are selected by the help of changing the style in innerHTML of div here.

But how to replace the style that has already been set?

Here my problem is I cannot select block 1.

full html code:

<style>
div {width:10px;height:10px;margin:10px;
    background:#ccc;cursor:pointer;padding:10px;
}
</style>
<div id="makeThatEnable" style="display:none"></div>

<div id="one" onclick="makeThisEnable(this.id)" style="border:1px solid #00f">1</div>
<div id="two" onclick="makeThisEnable(this.id)">2</div>
<div id="three" onclick="makeThisEnable(this.id)">3</div>
<div id="four" onclick="makeThisEnable(this.id)">4</div>
<div id="five" onclick="makeThisEnable(this.id)">5</div>
<br>
Click on box to select it.

<script>
function makeThisEnable(id) {
    document.getElementById('makeThatEnable').innerHTML="<style> #"+id+" {border:1px solid #f00}</style>";   
}
</script>

Answer by Starx

I have a better approach.
Uniquely identify a style element like this

<style id="innerStyle">
</style>

Then update your function like this

function makeThisEnable(id) {
    document.getElementById('innerStyle').innerHTML="div#"+id+" {border:1px solid #f00}";   
}

Instead of using !important to force the style, simple increase the specificity of the declaration like I am doing.

DEMO

Read more
...

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