...

Hi! I’m Starx

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

given an offset how can i convert the current time to UTC time in javascript

Question by whatf

a = new Date();
Sun Apr 08 2012 16:58:03 GMT+0530 (IST)

Is there any way i can get the current UTC time?
I thought of getting an offset doing maths:

b = a.getTimezoneOffset()
-330

then subtract, get the value:

c = a - b
1333884483552

but again getting c as a to look is difficult. So the question:
How can i get the current UTC time, in javascript?

Answer by Starx

There is a plugin called jstimezonedetect which you can use to detect the timezone. You can find it here

Or use date’s UTC methods like

var now = new Date(); 
var now_utc = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());

Demo

Outputs

Date {Sun Apr 08 2012 18:31:50 GMT+0545 (Nepal Standard Time)}

Date {Sun Apr 08 2012 12:46:50 GMT+0545 (Nepal Standard Time)}

Read more

PHP & MySQL : What's Wrong with Code to Add to a Database & Retrieve

Question by Ed Cox

It’s supposed to let you add a personal link to a database, and the Server is running Windows Server 2008 R2 with MySQL & Active Directory.

<?php 
$dbl = mysql_connect('localhost', 'USERNAME', 'PASSWORD') or die('failed to connect to mysql'); 
mysql_select_db('linksdatabase') or die('failed to select database'); 

if(isset($_POST['linkaddress']) && isset($_POST['linkname'])) 
$sql = "INSERT INTO userlinks (username, linkaddress, linkname) VALUES ('%s','%s','%s')";
mysql_query ( sprintf ( $sql, mysql_real_escape_string ( $_SERVER ['AUTH_USER'] ), mysql_real_escape_string ( $_POST ['linkaddress'] ), mysql_real_escape_string ( $_POST ['linkname'] ) ) );

echo '<p>Links:</p><ul>'; 

$result = mysql_query ( sprintf ( "SELECT linkaddress, linkname FROM userlinks WHERE username = '%s'", mysql_real_escape_string ( $_SERVER ['AUTH_USER'] ) ) );

while($row = mysql_fetch_array($result)) 
    echo '<li><a href="', htmlentities($row['linkaddress']), '">', htmlentities($row['linkname']), '</a></li>'; 

echo '</ul>'; 
?> 

<form action="" method="post"> 
 <fieldset> 
  <legend>Add a Link</legend> 
  Address: <input type="text" name="linkaddress" /><br /> 
  Name: <input type="text" name="linkname" /><br /> 
  <input type="submit" value="Add" /> 
 </fieldset> 
</form>

Answer by Baba

You are having some single quote ' issues

Replace

   mysql_query('INSERT INTO userlinks (username, linkaddress, linkname) VALUES ('' . mysql_real_escape_string($_SERVER['AUTH_USER']) . '', '' . mysql_real_escape_string($_POST['linkaddress']) . '', '' . mysql_real_escape_string($_POST['linkname']) . '''); 

With

$sql = "INSERT INTO userlinks (username, linkaddress, linkname) VALUES ('%s','%s','%s')";
mysql_query ( sprintf ( $sql, mysql_real_escape_string ( $_SERVER ['AUTH_USER'] ), mysql_real_escape_string ( $_POST ['linkaddress'] ), mysql_real_escape_string ( $_POST ['linkname'] ) ) );

Replace

$result = mysql_query('SELECT linkaddress, linkname FROM userlinks WHERE username = '' . mysql_real_escape_string($_SERVER['AUTH_USER']) . ''');

With

$result = mysql_query ( sprintf ( "SELECT linkaddress, linkname FROM userlinks WHERE username = '%s'", mysql_real_escape_string ( $_SERVER ['AUTH_USER'] ) ) );

This code might help you to find the error

error_reporting(E_ALL);
ini_set('display_errors','On');

$dbl = mysql_connect ( 'localhost', 'USERNAME', 'PASSWORD' ) or die ( 'failed to connect to mysql' );
mysql_select_db ( 'linksdatabase' ) or die ( 'failed to select database' );

if (count ( $_POST ) < 1) {
    var_dump ( "Nothign was posted" );
} else {
    var_dump ( $_POST );
}

if (isset ( $_POST ['linkaddress'] ) && isset ( $_POST ['linkname'] )) {
    $sql = "INSERT INTO userlinks (username, linkaddress, linkname) VALUES ('%s','%s','%s')";
    mysql_query ( sprintf ( $sql, mysql_real_escape_string ( $_SERVER ['AUTH_USER'] ), mysql_real_escape_string ( $_POST ['linkaddress'] ), mysql_real_escape_string ( $_POST ['linkname'] ) ) );

    if (mysql_errno ()) {
        var_dump ( "MySQL error " . mysql_errno () . ": " . mysql_error () );
    } else {
        var_dump ( "OK Insert" );
    }

}

echo '<p>Links:</p><ul>';

$result = mysql_query ( sprintf ( "SELECT linkaddress, linkname FROM userlinks WHERE username = '%s'", mysql_real_escape_string ( $_SERVER ['AUTH_USER'] ) ) );

if (mysql_errno ()) {
    var_dump ( "MySQL error " . mysql_errno () . ": " . mysql_error () );
} else {
    var_dump ( "OK Select" );
}

while ( $row = mysql_fetch_array ( $result ) )
    echo '<li><a href="', htmlentities ( $row ['linkaddress'] ), '">', htmlentities ( $row ['linkname'] ), '</a></li>';
echo '</ul>';

Answer by Starx

You are missing a closing bracket ) at the end of your query.

mysql_query('INSERT INTO userlinks (username, linkaddress, linkname) VALUES ('' . mysql_real_escape_string($_SERVER['AUTH_USER']) . '', '' . mysql_real_escape_string($_POST['linkaddress']) . '', '' . mysql_real_escape_string($_POST['linkname']) . '')'); 
Read more

Comparing multiple field values ​​together

Question by jennifer Jolie

How can I compare multiple input field values and if there is a match alert ‘There are similar values’ using jQuery?

<input value="111"> //similar
<input value="222">
<input value="111"> //similar
<input value="333">

This html code above should alert ‘There are similar values’, as it has 2 values which are the same. How can it be done with jQuery?

My tried(Following code doesn’t work):

DEMO: http://jsfiddle.net/HpWLQ/

$('input').each(function () {
    var $this = $(this);
    var val = $this.val();
    vals.push(val);
});
for (var i = 0; i < vals.length; i++) {
    for (var n = 0; n < vals.length; n++) {
        if (n !== i) {
            if (vals[i] === vals[n]) {
                alert('There are similar values');
            }
        }
    }
}

Answer by vzwick

Edit: In order to satisfy @Raynos, here’s a pure JS solution.

var vals = {};
var flag = false;
var collection = document.getElementsByTagName('input');
collection = [].slice.call(collection);

collection.forEach(function(element, index, array) {
    if (flag === true) return;
    var i = element.value;
    if (vals[i])
    {
        flag = true;
        alert('There are duplicates!');
    }
    else
    { 
        vals[i] = 1;
    }
});


Bonus: I ran my solutions through jsperf; the last one is obviously by far the fastest.

Edit: Here’s what would probably be the jQuery way of solving your problem (Working fiddle here). My original answer remains below.

var duplicatefound = false;
$('input').each(function(index, item){
    if (duplicatefound) return;
    val = $(item).val();
    if ($('input[value="' + val + '"]').length == 1) return;
    duplicatefound = true;
    alert('There are similar values');
});


Alternative solution in case you need to capture some or all of the duplicate values (Working fiddle here):

var collection = $('input');
var duplicates = $.map(collection, function(item){
    val = $(item).val();
    return ($('input[value="' + val + '"]').length > 1) ? val : null;
});

if(duplicates.length > 0) alert('There are similar values');

As others have mentioned, you were missing a declaration of vals as an array, therefore, .push() was failing.

You might find an object based solution to be more elegant: Working fiddle

var vals = {};

$('input').each(function() {
    var index = $(this).val();
    if (vals[index])
    {
        vals[index]++
    }
    else
    { 
        vals[index] = 1;
    }
});

var duplicates = $.map(vals, function(val, key){
    return (val > 1) ? key : null;
});

if (duplicates.length > 0) alert('There are duplicates!');

Answer by Starx

You haven’t defined the vals to be an array. You can define it like

vals = [];

Demo

Read more

html form button link to url

Question by Ferguzz

I have a simple search form with a box and a button.

<form action = "/search/" method = "get">
<input id = "search_box" type ="text" name = "location" value placeholder = "Where are you?" />
<input id = "search_button" type="submit" value = 'Go' />
</form>

This sends me to /search/?location=whatever

How do I get this to send me to /search/whatever instead? – i.e. no GET data, just an URL.

Answer by Starx

You cannot rewrite the form post methods like that. A way to do this efficiently is through a .htaccess at the root.

RewriteEngine On
RewriteRule ^search/?location=(.*)$ search/$1

This changes /search/?location=whatever to /search/whatever

Or, If you are looking for a complicated JS solution. Here is one using jQuery

$("form").submit(function() {
    var search = $("#search_box").val(); //get the element
    $(this).attr("action", $(this).attr("action")+search);  //attach to the post url
    $("#search_id").remove();  //remove the element, so it doesnot get sent
    console.log($(this).attr('action')); //check the console, if the action was changed and yes it was
    //return false; //continues the post to the new url if commented
});

Demo

Read more

Changing width property of a :before css selector using JQuery

Question by 4r1y4n

I have a page that has an image in it and I styled it using :before CSS selectors.
The image is dynamic so it hasn’t a fixed width; So I need to set :before rule’s width dynamically.
I want do it in client side using JQuery.
Assume this:

.column:before{
    width: 300px;
    float: left;
    content: "";
    height: 430px;
}

.column{
    width: 500px;
    float: right;
    padding: 5px;
    overflow: hidden;
    text-align: justify;
}

How Can I only change the width property of class with :before selector (and not one wothout it) using JQuery?

Thanks

Answer by m90

I don’t think there’s a jQuery-way to directly access the pseudoclass’ rules, but you could always append a new style element to the document’s head like:

$('head').append('<style>.column:before{width:800px !important;}</style>');

See a live demo here

I also remember having seen a plugin that tackles this issue once but I couldn’t find it on first googling unfortunately.

Answer by Starx

Pseudo-elements are not part of the DOM, so they can’t be manipulated using jQuery or Javascript.

Read more

Mysql query and foreach query with double items

Question by ciprian

I am just grabbing user data from a few tables but users have the option of adding more than one skill or exp.

$query_str = "SELECT a.*, b.*, c.*, d.*, e.* FROM edu a
              JOIN exp b ON a.user_id=b.user_id
              JOIN user_profiles c ON a.user_id=c.user_id
              JOIN skills d ON a.user_id=d.user_id
              JOIN comp e ON a.user_id=e.user_id
              WHERE a.user_id = ?";

$query = $this->db->query($query_str, $end_user);
            if($query->num_rows() > 0) {
                    foreach($query->result_array() as $stuff) {
                            $data[] = $stuff;
                    }
                    return $data;
                    } else {
            return false;
                    }

Everything is fine until I try to display the data. If a user has two exp, everything else is showing up twice. I m not sure how to write this. Would it be easier to do separate them? One query for each item?

public function get_education()
    {
           $one_edu = $this->test_model->one_edu($end_user);
            if ($one_edu != false)
            {
                    foreach($one_edu as $edas) {
                            $one_edu_html .='<p>'.$edas['objective'].'</p>';
                    }

                    foreach($one_edu as $exp) {
                            $one_edu_html .= '<p>'.$exp['exp_title'].'</p>';

                    }

                    foreach($one_edu as $educ) {
                            $one_edu_html .= '<p>'.$educ['edu_title'].'</p>';
                    }

                    $result = array('status' => 'ok', 'content' => $one_edu_html);
                    echo json_encode($result);
                    exit();
            }else{
                    $result = array('status' => 'ok', 'content' => '');
                    echo json_encode($result);
                    exit();
            }
    }

Now it s returning something like this:

Objective
Exp title1
Exp title2
Edu title
Edu title <- Extra

Using codeigniter

Answer by Starx

The main reason for this is because you haven’t grouped your rows. Add a grouper, like GROUP BY a.id at the end


Update

The rows are duplicating because they are different, you can group the field on a single rows, using GROUP_CONCAT

SELECT a.user_id, a.education, GROUP_CONCAT(a.edu_title SEPARATOR ",") "Edu_Title", GROUP_CONCAT(b.exp_title SEPARATOR ",") "Experience Title" ,b.experience, c.objective, d.skill, e.comp FROM edu a
JOIN exp b ON a.user_id=b.user_id
JOIN user_profiles c ON a.user_id=c.user_id
JOIN skills d ON a.user_id=d.user_id
JOIN comp e ON a.user_id=e.user_id
WHERE a.user_id = 243;

Demo

Read more

List of li elements in jquery

Question by Gabriel Żukowski

I don’t know why my code doesn’t work.

$("#example").find('LI A').hasClass("sth").each(function(){alert($(this))});

Firebug says:

$(“#example”).find(‘LI A’).hasClass(“sth”).each is not a function

The problem in this code is each, because if I delete it, it giving me no errors.

I need to pass founded value of “a” element to array.

Answer by gdoron

hasClass function returns boolean not a jQuery object. thus it doesn’t have the each function.

You probably meant this:

$("#example").find('LI A.sth').each(function(){alert($(this))});

Or this (which is better):

$("#example li a.sth").each(function(){alert($(this))});

Read the docs:

.hasClass( className ) Returns: Boolean

Description: Determine whether any of the matched elements are assigned the given class

Answer by Starx

Your application of hasClass is incorrect. It does not return a jQuery Object, but a boolean, so .each() cannot be applied to it.

You have to attach the class to the selector

$("#find").click(function (){
    $("#example").find('a.sth').each(function(){
        $("#test").append($(this));
    });
 });

Demo

Read more

Change javascript according to window width

Question by awDemo

I think this is quite simple but after 2 days of trying I’m still clueless. Basically, I need to run one set of commands if the screen is over 767 pixels wide and another if the screen is under 767 pixels.

When the screen is wider than 767 pixels, I want to:

<script type="text/javascript">

    var jsReady = false;//for flash/js communication

    // FLASH EMBED PART
    var flashvars = {};
    var params = {};

    params.quality = "high";
    params.scale = "noscale";
    params.salign = "tl";
    params.wmode = "transparent";
    params.bgcolor = "#111111";//change flash bg color here
    params.devicefont = "false";
    params.allowfullscreen = "true";
    params.allowscriptaccess = "always";
    var attributes = {};
    attributes.id = "flashPreview";

    swfobject.embedSWF("preview.swf", "flashPreview", "100%", "100%", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

    <!-- and much more code... -->

</script>

When the screen is narrower than 768 pixels, I want to run:

<script type="text/javascript">  

        jQuery(function($){
            $.supersized({
                //Background image
                slides  :  [ { image : 'img/some_image.jpg' } ]                 
            });
        });

</script>

That’s right… For desktops and tablets, I want to show a full-screen video background. For smaller screens (less than 767 pixels), I want to show a single still image background.

Answer by Starx

You can get the currect size of windows using $(window).width() and attach a handler on the resize event of the form. For a simple use, It is as simple as

$(window).resize(funcion() {
    $width = $(window).width();
    if($width < 767) {
            $.supersized({
                //Background image
                slides  :  [ { image : 'img/some_image.jpg' } ]                 
            });
    } else {
        //if width is greater than 767
    }
});
Read more
April 7, 2012

multiple forms in same page Jquery Ajax submit

Question by KJA

I am iterating a form in phtml page
how can i Submit or validate the form when i click in the button.
because when i am iterating the form , the id is the same for all form

i am using Zend Framework , i initiate the Form in my view like this to get different ids for each form

<?php
$commentForm = new Application_Form_Comment**($answerId)**;
 echo $commentForm?>

and i sent the $answer[‘answer_id’] to put it in the form id to be like this
<form id="comment_form64623" method="post" action="">

is that the best way ? or there is a way in Jquery to handle that?

Answer by Starx

I will say, no its not the good way, attaching ID, like that. Configure zend’s form to take the id as a hidden paramter, which at last renders as

<form id="comment_form" method="post" action="">
    <input type="hidden" name="answer_id" id="answer_id" value="64623" />

Next configure jQuery to change the position of the form to different places and update, like

$("form").appendTo($("#newDiv")); //Place the for somewhere else
$("#answer_id").val(newval); //Set a new id for the form
Read more
...

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