...

Hi! I’m Starx

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

how to enable php on a subdomain?

Question by Link

when i’m using the

“www . website . com”

php codes are working but when i’m using it on a subdomain the php script won’t work

“secure . website . com”

how can i enable the use of php code on my subdomain?
i’m using justhost as my server.

my subdomain is located at
/public_html/secure <–folder directory

but when i put the files inside the folder,
php scripts won’t work.
how can i enable php scripts inside my folder?

<?php
phpinfo();
?>

says it’s not supported?

justhost said to contact a php developer regarding this issue that is just what i’m doing.

Answer by Starx

This looks to be because of the server settings.

Contact the support personal at JustHost.com, there are live chat available. You can tell them your issue and fix the server settings.

Read more

Putting specific element into variable

Question by Arken

how can i get a specific element of a text input into a variable via javascript, in other words take the example below

   <form id="123">

        <input type="text" id="supply_qty" />

     <input type="submit" name="submit" id="123" />
  </form>

How do i get the element within the text input into a variable when the submit button is clicked, the problem i have is that i have multiple instances of the code above, with lots of text inputs, so i only want to get the element specific to the submit button clicked. Hopefully you will get what i mean. The reason i need this done via JavaScript and not php etc… is that i later want to use ajax with it, but for the moment i just need the variable.

Thanks

Answer by Starx

The most easiest way is to give and id to the element and user getElementById() method to grab the element on variable. Just like what you are doing right now

Simple Example:

var button = document.getElementyById("123");
button.onclick = function() {
    var text = document.getElementById('supply_qty'); //now you got your element in varaiblle
};

Using jQuery make a slight change to your markup. I am just going to add some classes.

   <form>
        <input type="text" class="textbox" />
        <input type="submit" class="submit" name="submit" />
  </form>

then

$(".submit").click(function() {
    var txtbox = $(this).parent("form").children(".textbox")[0];
});

Or, it might be better to bind to the submit handler of the form, on that case, give a common class to the form.

   <form class="tinyforms">
        <input type="text" class="textbox" />
        <input type="submit" class="submit" name="submit" />
   </form>

Then

$('.tinyforms').submit(function() {
    var txtbox = $(this).children(".textbox")[0];
});
Read more
September 1, 2012

MySQL – for every ID in the list select 2 last element

Question by Salvador Dali

I have a table with a following schema:

id, field, time
3, 'test0', 2012-08-29
3, 'test1', 2012-08-30
3, 'test2', 2012-08-31
2, 'test0', 2012-08-19
2, 'test1', 2012-08-20
2, 'test2', 2012-08-26
...

I need for every id in the list find it’s last and previous to last value.
For example if the ids = [2,3] the result should return

3, 'test1', 2012-08-30
3, 'test2', 2012-08-31 
2, 'test1', 2012-08-20
2, 'test2', 2012-08-26

If i will need just last value, I would use

SELECT *
FROM table
WHERE id IN (2, 3)
GROUP BY id

Any ideas how I can achieve this?

Answer by Starx

Give this a try

SELECT *
    FROM table
    WHERE id = '1'
    ORDER BY `id` desc
    LIMIT 0,2
UNION
    SELECT *
    FROM table
    WHERE id = '2'
    ORDER BY `id` desc
    LIMIT 0,2

UPDATE:

If can also try something like this:

SELECT t1.*
FROM `tablename` t1
LEFT OUTER JOIN `tablename` t2
  ON (t1.id = t2.id AND t1.time > t2.time)
GROUP BY t1.id, t1.field, c1.time
HAVING COUNT(*) < 2;

Reference

Read more

Can not control the item which create by appendTo function

Question by jchuang1977

I want to get the image url (the img in #demo) wich I parser from the JSON data and appendTo #demo.

I can see the picture which I get from flickr after parser the JSON data and appendTo to #demo.

But the “$(‘#demo img’).bind(‘click’, function()” never be trigger. So I can not get the img url and dump to #log to debug.

But If I write some static img elements into #demo , the click function can be triggered.

Is the “appendTo” cause it ?

<!DOCTYPE html>
<html> 
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ch13_4_2</title>
<link rel="stylesheet" href="jquery.mobile.min.css">
<script src="cordova-1.5.0.js"></script>
<script src="jquery-1.6.4.min.js"></script>
<script src="jquery.mobile.min.js"></script>

<script>
function onDeviceReady() {
   $('#shoot').bind('click', function() {
     $("#demo").empty();
      $("#log").empty();

      $.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tagmode=any&format=json&jsoncallback=?&tags=baby&id=82216313@N00" ,
              function(data) {
                $.each(data.items, function(i,item){

                var photoString = "<a href="#"><img src=" + item.media.m + "></a>";                
                 $(photoString).appendTo("#demo");

                  if ( i == 3) return false;
                });
              });             
   });   
} 

function onLoad() { 
   document.addEventListener("deviceready", onDeviceReady, false);
}   
</script>
</head>
<body onload="onLoad()">

<div data-role="page" id="home">   
   <div data-role="header" data-position="fixed">
     <h1>Andy's Flickr Search</h1>
     <a href="#" id="shoot" data-role="button" data-icon="search" data-inline="true">search</a>
   </div>


   <div data-role="content">
   <div id="log"></div>


     <div id="demo">

     </div> 

<script>

              $('#demo img').bind('click', function() {
                    $("#log").empty();
                    var img_link = this.src;                            
                    var photoString = "<img src=" + img_link + ">";                    
                    $('div #log').html(photoString);

           });  
</script>    


</div>   
</div>



</body>
</html>

Answer by undefined

For dynamically generated elements, events should be delegated from one of static parents of the element, you can use on method.

$('#demo').on('click', 'img', function(){
  // ...
})

Answer by Starx

Do not use bind any more. As of 1.7, use .on() to delegate the event handler.

$('#demo').on('click', 'img', function() {
   // ...
});

Update:

live() and bind() worked differently: live() will also work for non existent elements or elements that are created on the fly but bind() will only bind the event handlers for currently existing elements. Read More

.delegate() was used for event delegation, but .on() is improved version of it and will created for clean coding and combination of bind() and delegate()

Other good questions:

  1. jQuery: live() vs delegate()
  2. .delegate() vs .on()
  3. Jquery live() vs delegate()
Read more
August 31, 2012

jquery selector contains equals sign

Question by John Buckwell

I am using a jQuery selector to check for characters in href:

var param = "something";
$("a[href*="+param+"]").css("color", "red");

This works fine until “something” contains an = sign. Eg:

var param = "xkey=123";
$("a[href*="+param+"]").css("color", "red");

then I get no result. Anyone know a solution?

Answer by Starx

It is behaving that way becuase, at the end it will translate to ambiguous selector i.e. $("a[href*=xkey=123]") which indeed is invalid.

Escape the equal sign with \ infront and wrap the parameter part with a quote

var param = "xkey\=123";
$("a[href*='"+param+"']").css("color", "red");
Read more

jquery slide out from record

Question by Matthew

I am looking for some advice on an idea which i am unsure if i can do it or not…

i am loading records out of a database and listing them in individual divs and adding an id number from the databse to the divs,the divs are about 100px wide and right across the screen..

i am wondering if i can use some kinda of plugin by jquery so that if i click on the record a tab would slide out from the right hand side with more data on that individual record from the database.. and then i could close it and it would side back so i can only see the records again..

i have had a bit of a look at the jquery ui page with all the demos but i didnt really find anything…

any help or pointers would be great.. even if u know of something simllar ill be happy to look into it…

thanks in advance for any help

Answer by ComputerArts

Ok so here’s my fiddle

HTML (standard containers, etc)

<div id="container">
    <div id="buttons-container"></div>
    <div id="record">
        <div id="record-content"></div>            
        <a href="#" id="bt-close" onclick="closeRecord(); return false;">Close</a></div>
</div>

CSS

a.bt-record {
    display:block;
    width:100px;
    height:100px;
    background:#999999;
    color:#000;
    line-height:100px;
    text-align:center;
    float:left;
    margin:0 10px 10px 0;
    text-decoration:none;
}

a { color:#fff; }

#container {
    width:100%;
    height:100%;
    overflow:hidden;
    position:relative;
}

#record {
    position:absolute;
    right:-240px;
    top:100px;
    width:200px;
    height:200px;
    background:#000;
    padding:20px;
    color:#fff;
    z-index:1;
}

Javascript

//your data in a array of objects (could be something else)
var data = {
    1 : {name:'Record 1', text:'This is the text 1', options:'Anything 1'},
    2 : {name:'Record 2', text:'This is the text 2', options:'Anything 2'},
    3 : {name:'Record 3', text:'This is the text 3', options:'Anything 3'},
    4 : {name:'Record 4', text:'This is the text 4', options:'Anything 4'},
    5 : {name:'Record 5', text:'This is the text 5', options:'Anything 5'},
    6 : {name:'Record 6', text:'This is the text 6', options:'Anything 6'},
    7 : {name:'Record 7', text:'This is the text 7', options:'Anything 7'},
    8 : {name:'Record 8', text:'This is the text 8', options:'Anything 8'},
    9 : {name:'Record 9', text:'This is the text 9', options:'Anything 9'}
};

$(document).ready(function() {
    populateEntries();        
});

//dynamically populate the entries
function populateEntries() {
    for (entry in data){
console.log(entry);       
        $('#buttons-container').append('<a class="bt-record" href="#" onclick="showRecord(' + entry + '); return false;">' + data[entry].name + '</a>');
    }
}

//show the record
function showRecord(id) {
    //create the html
    var html = '';
    html += '<p>Name : ' + data[id].name + '</p>';
    html += '<p>Text : ' + data[id].text + '</p>';
    html += '<p>Name : ' + data[id].options + '</p>';
    $('#record-content').html(html);
    $('#record').animate({right:0}, 500);
}

function closeRecord() {
    $('#record').animate({right:-240}, 500);
}

In this example, I populate the records dynamically, but if you want a SEO friendly way of doing it, you can create the HTML in the page directly. Let me know if you have questions.

Answer by Starx

Sure, let me show you a simple example. It is rather very easy

<table>
    <tr class="recordrow" id="row-1"> <!-- row-X will be the unique way to identify the row -->
       <td>...</td> <!-- The record field -->
       <td>...</td>
       ....
    </tr>
</table>

<!-- Now we create the details Div, but as reference to the `row-X` -->
<div class="details" id="details-1">
   ... More details of the records
</div>

then a simple jQuery snippet like this will get the job done:

$(".recordrow").click(function() {
    var divid = "details-" + $(this).attr('id').split("-")[1]; //Create the id of the div
    $("#"+divid).show().animate({ "left": '200px'}); //Bring the div from right to left with 200px padding from the screen
});

Demo

Read more

How to store session while sendRedirect

Question by Thunderbird

I have a condition where I want to remove the attribute from the session and I am doing response.sendRedirect after that.

But I am not sure if it will remove the session attribute ? Any thoughts ?

P.S. I have to do sendRedirect, I cannot use forward.

session.removeAttribute(Constants.USER_REQUEST_URI); 
response.sendRedirect(userReqUri);

ANSWER : Just a little debugging solved my concern. I checked the session attribute value by getting the variable and it was null. So it removed the variable from the session.

Answer by Starx

Yes, if Constants.USER_REQUEST_URI gives the correct name as it is stored in session, then it will remove them.

Session work differently than GET and POST request so redirecting and forwarding will make no difference.

Good way to confirm this, would be to check if the variable is accessible after the redirect

session.getAttribute(Constants.USER_REQUEST_URI)
Read more
August 29, 2012

Disabling form button onClick, and then submitting the form

Question by bevanb

My form lets users submit a poem.

Sometimes, there’s a field for a new user name on that page (if nobody’s logged in). In that case, I want to override the button click so that it signs them up first:

$('#submit-poem').click ->
  $('input[type=submit]').attr('disabled', true)
  if $('#new_poet_name_field').length
    signUp();  // This will submit the poem form after registering
    false
  else
    console.log("A poet was already logged in!")
    true

This used to work fine. But now, when there is no new_poet_name_field, the submit button stays disabled. Returning true used to submit the form. Now, I have to explicitly do $('#new_question')[0].submit() if there is no poet_name_field.

Why doesn’t the form submit when true is returned? My workaround is worrisome; it seems possible that the form might submit twice now: once when I explicitly submit it, and once when true is returned.

Answer by brains911

You should bind to the form ‘submit’ event and use preventDefault/return false when you want someone to sign up instead of submitting the poem. This way there is no need to do any disabling/enabling of buttons.

Answer by Starx

I dislike the idea of not having a form. Its invalid and sure to not follow HTML’s Specification.

Every constructive form elements should be wrap inside a form tag. You can control the submission of form in more than one way.


The code you are using is horrible

  1. WHY?? Is there more than one submit button? The code below disables every submit button on the page, which can be of other forms too.

    $('#submit-poem').click ->
      $('input[type=submit]').attr('disabled', true) 
    
  2. This is wrong way to check the authenticity of submission, it can be easily manipulated with tools like firebug.

    if $('#new_poet_name_field').length
        signUp(); 
    

If finding out if the user is logged in or not that important, then you can quickly send an ajax request to a service page, that gets you that information

$('#submit-poem').click(function() {
    $(this).attr('disabled', true)
    $.post("yourservicepage.php", {}, function(data) {
          // RE suppose, data is the boolean value from server indicating logged in or not
          if(data != true) {
             signup(); //if not logged in then signup
          }
          //...
    });
});
Read more
August 28, 2012

Graphical editor using Javascript

Question by aakashbhowmick

I want to make an online card-making application. It should basically allow users to place available images into the template of the card, write text on it and decorate it – basic card customization. What javascript graphics library would be useful for this project ? Finally I would like to have a high resolution/vector image as the output which can be printed easily.

Answer by AlienWebguy

Raphael is great for SVG, etc. http://raphaeljs.com

Answer by Starx

To have a high resolution/vector image, you have to work with SVG (Scalable Vector Graphics), so far the web browser only support this. There are two ways you can do these.

  • Looking up for canvas libraries. I prefer Raphael as it supports SVG and animations as well.
  • With HTML5 and its Canvas features also you can create such system.
Read more
August 27, 2012

Giving text labels to integer ranges in PHP

Question by xxdrivenxx

I am attempting to take simple number ranges (in the example of this project, I am working with different increments of money for each user. FAKE money, by the way…) and group them into classes that can be displayed publicly instead of the absolute number.

Here is a rough sample of code for the long way to write this function as an example:

<?
$money=500001;

if($money > 0 AND $money < 5000) {
    $class = 'Poor';
} elseif ($money >= 5000 AND $money < 25000) {
    $class = 'Lower Class';
} elseif ($money >= 25000 AND $money < 100000) {
    $class = 'Middle Class';
} elseif ($money >= 100000) {
    $class = 'Upper Class';
}
echo $class;
exit();
?>

Now, I know this function will work, but it seems like an absolutely awful way in going about writing it, since if more $class’ are added, it becomes far too long.

Now my question is: Is there a shorter way to write this? Possibly using range() and/or an array of values?

Answer by alfasin

I would go for something like this:

function getClass($sal){
    $classes = array(5000=>"poor", 25000=>"Lower Class", 100000=>"Middle Class");
    foreach ($classes as $key => $value) {
        if($sal < $key){
            return $value;
        }
    }
    return "Upper Class";
}


$salary = 90000;
$sal_class = getClass($salary);    
echo "salary class = $sal_classn";

Output:
sal = Middle Class

Answer by Starx

A bit similar to above answer, but a better one. I will suggest using OO approach.

Class Foo {
    protected $class = array(
        array("poor", 0, 5000),
        array("medium", 5000, 25000)
    );

    function get_class($amount) {
       foreach ($this -> class as $key => $value) {
           if($amount > $value[1] && $amount < $value[2]) {
              return $value[0];
           }
       }
       return null;
    }

    function add_class(array $arr) {
        $this -> class[] = $arr;
    }
}

Usage:

$obj = new Foo();
$obj -> get_class(6000); //Outputs: medium
$obj -> add_class(array("rich", 25000, 50000)); //Add a new class
$obj -> get_class(35000); //Outputs: rich
Read more
...

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