...

Hi! I’m Starx

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

error in 301 permanent redirect

Question by asitha

i am using htaccess for 301 permanent redirect.
i have to make a redirect for bima.php to ge.php.so i wrote the below code in htaccess

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^bima.php?$ $1/ge.php [NC,R=301,L]

this works properly..whenever i put www.test.com/bima.php in url it will redirect to www.test.com/ge.php
the problem is i have to do a 301 redirect for ge.php also.that means whenever www.test.com/gen.php in url it will redirect to www.test.com/bima.php.
www.test.com/bima.php needs to redirect to www.test.com/gen.php and vice versa.
Any idea?or anyway to do this?

Answer by Starx

Your redirect rule

RewriteRule ^bima.php?$ $1/ge.php [NC,R=301,L]
RewriteRule ^ge.php?$ $1/bima.php [NC,R=301,L]

Is redirecting in infinite loop. Remove one of them.

No matter what type of logic you use, the redirection you are attempting will end of in loop at one time. So better avoid the need of such requirement.


Here is a PHP Solution

File: ge.php

if($_SESSION['redirected']['from'] != 'bima.php') {
   header("location: bima.php");
   $_SESSION['redirected']['from'] = 'ge.php';
   exit;
}

File: bima.php

if($_SESSION['redirected']['from'] != 'ge.php') {
   header("location: ge.php");
   $_SESSION['redirected']['from'] = 'ge.php';
   exit;
}
Read more

jquery load between two urls

Question by Mr. 1.0

I am trying to load content from 2 different URLS but at different intervals. Ideally I would like to load one url wait 10 seconds load the other and repeat the over and over. This is what I have but its not working correctly. Its constantly loading the urls rapidly back and forth so fast I cant read the content

setInterval(function(){
          $('#ticker').load('misc.php?users=10');
      }, 10000);

      setInterval(function(){
          $('#ticker').load('misc.php?news=10');
      }, 20000);

Answer by Starx

I have a better suggestion

var links = ['misc.php?users=10', 'misc.php?news=10'];
var pointer = 0;

setInterval(function() {
     $("#ticker").load(links[pointer++ % links.length]);
}, '10000');

Demo

Read more

CSS3 Animating position

Question by George

Consider CSS3 animation with ship moving above blue div. For some reason the ship isn’t moving. The HTML is as follows:

<div id="wrapper">
  <div id="sea">
    <img src="ship.png" alt="ship" width="128" height="128"/>
  </div>
</div>

In order to make CSS3 animation I use the following:

#wrapper { position:relative;top:50px;width:700px;height:320px;
          margin:0 auto;background:white;border-radius:10px;}
#sea { position:relative;background:#2875DE;width:700px;height:170px;
       border-radius:10px;top:190px; }
#sea img { 
  position:relative;left:480px;top:-20px;
  animation:myship 10s;
  -moz-animation:myship 10s; /* Firefox */
  -webkit-animation:myship 10s; /* Safari and Chrome */
  @keyframes myship {
    from {left: 480px;} 
    to{left:20px;} 
   }
   @-moz-keyframes myship {
     from {left: 480px;} 
     to {left:20px;} 
   }
   @-webkit-keyframes myship {
     from {left: 480px;} 
     to{left:20px;} 
   }
}

The ship image isn’t moving. Any help is greatly appreciated.

Answer by Kirean

you have to declare your keyframe outside the css selector, as well as animate an absolutely positioned element.

http://jsfiddle.net/aNvSf/

your modified css looks like this:

#wrapper{position:relative;
    top:50px;
    width:700px;
    height:320px;
            margin:0 auto;background:white;
    border-radius:10px;
}
#sea{position:relative;
    background:#2875DE;
    width:700px;height:170px;border-radius:10px;top:190px;
}
#sea img{
    position:absolute;
    left:480px;
    top:-20px;
    animation:myship 10s;
            -moz-animation:myship 10s; /* Firefox */
            -webkit-animation:myship 10s; /* Safari and Chrome */

}

@keyframes myship
                {
                from {left: 480px;} 
                to{left:20px;} 
                }
                @-moz-keyframes myship
                {
                from {left: 480px;} 
                to{left:20px;} 
                }
                @-webkit-keyframes myship
                {
                from {left: 480px;} 
                to{left:20px;} 
                }​

Answer by Starx

To animate with left, top, bottom or right, you either have to have a absolutely positioned or floated element. SO, Change the position to absolute.

Also, there was as unclosed braces } before you started to declare the keyframes.

#sea img { 
    position:absolute;
    /* ... */
}

Braces Error:

    #sea img{
         position:absolute; /* absolute */
         left:480px;top:-20px;
         animation:myship 10s;
        -moz-animation:myship 10s; /* Firefox */
        -webkit-animation:myship 10s; /* Safari and Chrome */
    } 
 /* ^ You have to close the braces here, before declaring the keyframes.

Here is a working demo

Read more

Basic JSON With PHP

Question by Talon

I have some Data like this in PHP:

NumberOfPeople.php
<?php
$numberOfPeople = 5;
?>

How do I convert that variable into a JSON Object and then output it into an HTML file.

Something like this:

RandomHTMLFile.html
<script type="text/javascript">
  var NumberOfPeople = JSON VARIABLE FROM THE PHP FILE
</script>

This is the type of thing JSON is for right?

Notice that the Output file is in an HTML file and not a PHP File, so it has to be completely Javascript based.

Also the HTML file will be on a different server than the PHP file.

Answer by Starx

Change it into a PHP array and use json_encode() function

$jsonArray = array('numberOfPeople' => 5); //Now the value will be accessible under `numberOfPeople` json index
$json = json_encode($jsonArray);
echo $json;
Read more
May 2, 2012

How do I dynamically center images?

Question by Wilfred

With css and javascript/jquery, how do I center the images I have displayed vertically down a page? Let me draw a diagram.
This is what I have…

-------
|     |
|     |
-------
----------
|        |
|        |
----------
------
|    |
|    |
------

This is what I want

  -------
  |     |
  |     |
  -------
-----------
|         |
|         |
-----------
   -----
   |   |
   |   |
   -----

Answer by Brad

Set the following CSS on your centered image class:

display: block;
margin: 1em auto; /* the key here is auto on the left and right */

Answer by Starx

A small snippet will get this done

display: inline-block;
margin: 1em auto;

Using jQuery you can set the properties like:

$("img#selector").css({
    'display':'inline-block',
    'margin' : '1em auto'
});
Read more

jQuery change var by event in real time – not work

Question by Михаил Дмитриев

How make change “aspectRatio” in settings https://github.com/trentrichardson/UberUploadCropper/blob/master/example-advanced/index.php in real time.

$(function() {

$.("#test1").click( function () {
    $ratio = 1;
});
$.("#test2").click( function () {
    $ratio = 2;
});

$('#UploadImages').uberuploadcropper({

...

'aspectRatio': $ratio, 

It not work. Why?
How it is correct to make?

Answer by Starx

Define a global variable of the $ratio.

Example:

var $ratio; //Define a global variable like this
$(function() {

    $("#test1").click( function () {
        $ratio = 1;
        initPlugin();
    });
    $("#test2").click( function () {
        $ratio = 2;
        initPlugin();
    });

    function initPlugin() {    
        $('#UploadImages').uberuploadcropper({

             ...

             'aspectRatio': $ratio, //now the value will be taken from global scope
        });
    }
});
Read more

make an ifnot statement and if statement in one line

Question by sven30

I’m trying to make an if statement with 2 conditions. One that checks if one variable is NOT present & does NOT matches the word “good2go” and the other that checks to make sure “body” variable is present. I’m trying to trip the error message here. Here is what I have and what I’ve tried, and none of it seems to work.

if (stripos($_POST['check'], 'good2go') == FALSE && $_POST['body']) {        
                $error = true; } 

if (!$_POST['check'] == 'good2go' && $_POST['body']) {  
                $error = true; }

if (!stripos($_POST['check'], 'good2go') && $_POST['body']) {   
                $error = true; }

if ((!stripos($_POST['check'], 'good2go')) && $_POST['body']) { 
                $error = true; }

How do I get this to work?

here’s the entire code of contact_us.php this has the validation code and the email code.

    $error = false;
  if (isset($_GET['action']) && ($_GET['action'] == 'send')) {

          // Winnie the pooh check
         //$t = tep_db_prepare_input($_POST['verify']);
         if (!isset($_POST['check']) && !$_POST['check']=='good2go' && isset($_POST['body'])) {
                $error = true;              
        } else  {  // Winnie the pooh Check

    $name = tep_db_prepare_input($_POST['name']);
    $email_address = tep_db_prepare_input($_POST['email']);


//IP recorder start
$ipaddress = $_SERVER["REMOTE_ADDR"];
$ip = "nnIP: " . $ipaddress;
$content = "nnName: ".$name."nnComments: ".$_POST['enquiry'];
$product = tep_db_prepare_input($_POST['product']);
    if ($product) { 
$product_text = "nnProduct Interest: ".$product; }
$content_ip = $content . $product_text. $ip;
$enquiry = tep_db_prepare_input($content_ip);
//IP recorder end


        }
 // BOF: Remove blank emails
// if (tep_validate_email($email_address)) {
// tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);
// tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// } else {
// $error = true;
// $messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
    if (! tep_validate_email($email_address)) {
        $error = true;
        $messageStack->add('contact', ENTRY_EMAIL_ADDRESS_CHECK_ERROR);
    }
    if ($enquiry == '') {
        $error = true;
        $messageStack->add('contact', ENTRY_EMAIL_CONTENT_CHECK_ERROR);
    }
    if ($error == false) {      
      tep_mail(STORE_OWNER, STORE_OWNER_EMAIL_ADDRESS, EMAIL_SUBJECT, $enquiry, $name, $email_address);

      tep_redirect(tep_href_link(FILENAME_CONTACT_US, 'action=success'));
// EOF: Remove blank emails
    }
  }

Answer by dweiss

Solution to your updated problem:

if (!isset($_POST['check']) || !$_POST['check']=='good2go' || !isset($_POST['body'])) {
                $error = true;              
} 

The reason for the pipes vs ampersands is that you want to throw an error if ANY of the fields has issue. Also, you want to check if body is NOT set vs IS set. Glad this worked out for you!

Answer by Starx

No need for all those unneeded functions. What you are trying to achieve is:

if (isset($_POST['check']) && $_POST['check']=='good2go' && !isset($_POST['body']) {
   // your code 
}

However, As per the title of the question: Use a ternary statement. Syntax is as such

$var = <condition> ? <true> : <false>;
Read more

How to dynamically set and modify CSS in JavaScript?

Question by AkademiksQc

I have some JavaScript code that creates some div elements and it sets their CSS properties.
Because I would like to decouple CSS logic from my JavaScript code and because CSS is easier to read in its own .css file, I would like to set the CSS className of my element and then dynamically inject some values into the defined CSS property.

Here is what I would like to do :

style.css:

.myClass { 
    width: $insertedFromJS 
}

script.js:

var myElement = document.createElement("div");
myElement.className = "myClass";

I want to do something like this but at that point myElement.style.width is empty

myElement.style.width.replaceAll("$insertedFromJS", "400px");

I think my problem here is that after the call to myElement.className = "myClass", the CSS is not yet applied.

Answer by Mark Rawlingson

If I understand your question properly, it sounds like you’re trying to set placeholder text in your css file, and then use javascript to parse out the text with the css value you want to set for that class. You can’t do that in the way you’re trying to do it. In order to do that, you’d have to grab the content of the CSS file out of the dom, manipulate the text, and then save it back to the DOM. But that’s a really overly-complicated way to go about doing something that…

myElement.style.width = "400px";

…can do for you in a couple of seconds. I know it doesn’t really address the issue of decoupling css from js, but there’s not really a whole lot you can do about that. You’re trying to set css dynamically, after all.

Depending on what you’re trying to accomplish, you might want to try defining multiple classes and just changing the className property in your js.

Answer by Starx

Setting the style, might be accomplished defining the inner-page style declaration.

Here is what i mean

var style = document.createElement('style');
style.type = 'text/css';
style.cssText = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);
document.getElementById('someElementId').className = 'cssClass';

However the part of modifying it can be a lot of tricky than you think. Some regex solutions might do a good job. But here is another way, I found.

if (!document.styleSheets) return;
var csses = new Array();
if (document.styleSheets[0].cssRules)  // Standards Compliant {
   csses = document.styleSheets[0].cssRules;
}
else {         
   csses = document.styleSheets[0].rules;  // IE 
}
for (i=0;i<csses.length;i++) {
   if ((csses[i].selectorText.toLowerCase()=='.cssClass') || (thecss[i].selectorText.toLowerCase()=='.borders'))
   {
     thecss[i].style.cssText="color:#000";
   }
}
Read more

slide down effect with jquery

Question by Thomas

suppose i have one div which has data. i want when i will click on a button then a new div will be created and which will cover the actual div like shutter down. here is sample code i got from a site which is very close but not the way i want.

    $(document).ready(function() {
  var $box = $('#box')
    .wrap('<div id="box-outer"></div>');
  $('#blind').click(function() {
    $box.blindToggle('slow');  
  });    
});

check the demo of above code http://www.learningjquery.com/2008/02/simple-effects-plugins
just go to site and click on blind toggle button just to see how i want the things.
i want when button will be click then a new div will be created and the new div will cover the actual div with slide down effect and when i will click again then new div will slide up.how to implement it using jquery. guide me with sample code if possible. thanks

Answer by kei

The link you’ve provided pretty much have the code already for you. You just need a few tweaks.

demo:
http://jsfiddle.net/dACjL/

Answer by Starx

There are already native function .slideUp() and .slideDown() which do what you want.


Update: Not sure if i understood it correctly but, here is a demo.

Read more

JavaScript dynamic function name

Question by John R

I need to dynamically assign the name of a function to an element of an associative array. This is my attempt which does not work. The problem I am asking for help with is here where I try to call the function: cr['cmd1'](x);

<!DOCTYPE html>

<html>
<head>
    <script type="text/javascript">
        var cr =[];
        var x = 5;
        cr['cmd1'] ='foo';
        var msg = cr['cmd1'](x);  
        alert(msg);

        function foo(y){
            return y;
        }
    </script>
</head>
<body>
</body>
</html>

Edit: I being passed a string here cr['cmd1'] ='foo'; that I cannot control. That is why I have to work with a string as a starting point from an external application.

Answer by Starx

Access the functions using this syntax window[function_name]('para1');

Your usage will be something like this

var msg = window[cr['cmd1']](x);
Read more
...

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