...

Hi! I’m Starx

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

How to play a notification sound on websites?

Question by valmar

When a certain event occurs, I want my website to play a short notification sound to the user.

The sound should not auto-start (instantly) when the website is opened.
Instead, it should be played on demand via JavaScript (when that certain event occurs).

It is important that this also works on older browsers (IE6 and such).

So, basically there are two questions:

  1. What codec should I use?
  2. What’s best practice to embed the audio file? (<embed> vs. <object> vs. Flash vs. <audio>)

Answer by Starx

How about the yahoo’s media player
Just embed yahoo’s library

<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script> 

And use it like

<a id="beep" href="song.mp3">Play Song</a>

To autostart

$(function() { $("#beep").click(); });
Read more

checking a cookie exists Login Logoff using jquery / js

Question by SOLDIER-OF-FORTUNE

I have a DNN login/logoff control which isnt working properly. I want to therefore make my own using JS/JQUERY.

When the user is logged in the HTML on the page looks like this:

<a href="javascript:__doPostBack('dnn$dnnLOGIN$cmdLogin','')" class="SkinObject" id="dnn_dnnLOGIN_cmdLogin">Logout</a>

and when they are ‘logged out’ it looks like this:

<a href="javascript:__doPostBack('dnn$dnnLOGIN$cmdLogin','')" class="SkinObject" id="dnn_dnnLOGIN_cmdLogin">Login</a>
  • I would like to check if the cookie has been set, if it has then
    display Logoff link and if it hasnt then display the Login link.

  • Clicking on Login will check if the cookie exists (it should as Login
    was displayed) and take them to the login page.

  • Clicking on Logoff should delete the cookie and the refresh the page
    which will then change the link back to ‘Login’ again because no cookie was found.

I was using this as an example guide: http://jsfiddle.net/MadLittleMods/73vzD/

This is what i have done so far:

HTML:

<a id="dnn_dnnLOGIN_cmdLogin" href="Login">
    Login
</a>

||

<a id="dnn_dnnLOGIN_cmdLogin" href="Logoff">
    Logoff
</a>

<br />

<a id="see" href="#">
    see
</a>

JS:

//set the cookie once user has logged in
//for testing purposes clicking login should set the cookie to 1
//clicking on Logoff 'should' set the cookie to 0
$('#dnn_dnnLOGIN_cmdLogin').live('click', function() {
    var action = $(this).attr('href');
    var cookie_value = (action == 'Login') ? 1 : null;

    $.cookie('DNN-COOKIE', cookie_value);

    return false;
});

// clicking on 'see' should bring up an alert box display the cookie value of 1 or 0
$('#see').live('click', function() {

    alert($.cookie('DNN-COOKIE'));

    return false;
});

Answer by Starx

The demo of cookie is working just fine. Its seems you forgot to include the plugin.

See a working one here


Update:

You can check the preexisting of a cookie like this

var preval = $.cookie('cookie-name');
if(preval != null) {
    //... 
}

Demo

Read more

Height:100% in IE7

Question by steventnorris

UPDATE

Margin for html and body needed to be 0 to fill page completely.

END UPDATE
*UPDATE*

I have fixed using the below suggestion of adding the height property to the html and body tags. Now there is a slight scroll down required to view the entire page. Ideas on why this is happening?

END UPDATE

I am using CSS to make a div fill the screen as needed. I’ve got width and height set to 100%, but the div doesn’t fill the height of the screen. Is this a known issue with IE7 or am I possibly just missing something? Code below.

HTML

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <link rel="Stylesheet" href="test.css" />
</head>
<body>
<div id="divy"></div>
</body>
</html>

CSS

#divy
{
    width:100%;
    height:100%;
    background-color:Blue;
}

Answer by rlemon

The issues is the container must have height of 100% for it’s child element to assume 100%…

In this case the container is <html> -> <body> so a quick fix would be

html, body {
    margin: 0;
    padding: 0;
}
html, body, #divy {
    width:100%;
    height:100%;
}

Answer by Starx

Whenever you are defining a 100% height, it’s ancestors or all subsequest ancestor, must have 100% as their height as well.

So, give 100% height, to the body, as well as html.

html, body { height: 100%; }
Read more

Codeigniter : Unable to locate the model you have specified

Question by WebNovice

I have upgraded my PHP from version 5.2.9 to 5.3.1 and have encountered the following with my codeigniter application:

Unable to locate the model you have specified: some_model

Codeigniter version 2.1, with HMVC extension
Server: Centos 5

The model names are all in lower case and it is also loaded by calling their lower case letter. Everything used to work before the PHP upgrade.

Answer by Starx

If you are using HMVC, then you have to provide the module name as well.

Like this

$this -> load -> model('module/model_name');
Read more

Jquery form validation – pop up to specific checkbox

Question by holian

I use Jquery form validation. Before visitor submit i need to check the ‘Terms&Cond’ checkbox. If not checked i would like to see the message an alert box. (other messages shown near in the textboxes)

How to set this? I try this:

 $("#myform").validate({
      errorPlacement: function(error, element) {
            if ( element.is(":checkbox") ) {
                alert(error.html());
            }
            },
        rules: {
            name: {
                required: true,
                minlength: 3,
                maxlength: 40,
                lettersonly: false
            },
            ad: {
.....

But this did not work.

Thank you for help.

Answer by Starx

error does not have a html() function. You were probably trying to alert the markup of the element.

alert(element.html());
Read more

create a scroll bar in a sidebar

Question by dan

I’m trying to create a scroll bar inside the #main div so that I can scroll that without scrolling the page or the title but it isn’t working. What am I missing?

My code is as follows:

CSS

#topbar {
    height: 40px;
    background-color: blue;
}

#sidebar {
    position: absolute;
    top: 40px;
    bottom: 0px;
    width: 80px;
    overflow: hidden;   
}

#title {
    height:30px;
    background-color: red;
}

#main {
    height: auto;
    overflow: scroll;
}

HTML

<div id="topbar">
    hello
</div>
<div id="sidebar">
    <div id="title">
        title
    </div>
    <div id="main">
        <!-- lots and lots of text-->
    </div>
</div>

You can find an example JSFiddle here: http://jsfiddle.net/PTRCr/

Thanks

Answer by Starx

CSS are stylesheet whose only purpose are to style document. They cannot investigate a pre-existing elements.

The only ways are whether the size of the div has to be fixed or you have to use some JavaScript to find out the exact height. The ways of which this can be done with CSS have already been presented by other users.

So, here is a way you can do using jQuery

$("#main").height($(document).innerHeight()-$("#title").outerHeight() - $("#topBar").outerHeight());

Demo

Read more

Jquery ajax loading status message

Question by sly_Chandan

$.ajax({
                type: "POST",
                url: "Services/Services.asmx/GetAllDoctors",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    for (var i = 0; i < data.d.length; i++) {
                        var centerAddress = CreateAddressToBind(data.d[i]);
                        doctorTemplates[i] = { row_ID: data.d[i].row_ID, DOCTOR_ID: data.d[i].DOCTOR_ID, DOCTOR_NAME: data.d[i].DOCTOR_NAME, LINE1_BLDG: data.d[i].LINE1_BLDG, LINE2_STREET: data.d[i].LINE2_STREET, LINE3_AREA: data.d[i].LINE3_AREA, CITY: data.d[i].CITY, PINCODE: data.d[i].PINCODE, MEDICALCENTER_ADDRESS: data.d[i].MEDICALCENTER_ADDRESS, STATE: data.d[i].PINCODE, OTHER_DETAILS: data.d[i].OTHER_DETAILS, CONTACT_DETAILS: data.d[i].CONTACT_DETAILS, modified: 0 }
                        $("#doctorTable").append("<tr id='tableRow'><td id='rowid' class='hiddenColumn'>" + data.d[i].row_ID.toString() + "</td><td id='doctorid'>" + data.d[i].DOCTOR_ID.toString() + "</td><td id='doctorname'>" + data.d[i].DOCTOR_NAME.toString() + "</td><td id='centerAddress'>" + data.d[i].MEDICALCENTER_ADDRESS.toString() + "</td><td id='doctorAddress'>" + data.d[i].LINE1_BLDG.toString() + "," + data.d[i].LINE2_STREET.toString() + "," + data.d[i].LINE3_AREA.toString() + "," + data.d[i].CITY.toString() + "," + data.d[i].PINCODE.toString() + "," + data.d[i].STATE.toString() + "</td><td id='cdetails'>" + data.d[i].CONTACT_DETAILS.toString() + "</td><td id='odetails'>" + data.d[i].OTHER_DETAILS.toString() + "</td><td><a href='#' onclick='EditRecord(this)'>Edit</a></td><td><a href='#' onclick='DeleteRecord(this)'>Delete</a></td><td class='modified'>0</td></tr>");
                    }
                    $("#doctorTable").dataTable();
                }
            });

How can I show a ajax status message loading while the content is loaded?

Answer by Starx

Just give some html message, in the selector which you are updating after before the send the request. Like this

$("#doctorTable").text("loading");
$.ajax(....);
Read more

Return false not working sometimes

Question by Vladimir

I have a page with photo gallery http://dev.dolina-imeniy.ru/fotogalereya/kp_usadba_tishnevo/
I use this to bind click event and return it false

$('a.link_photo').click(function(e) {
var new_img = $(this).attr('href');
var photo_title = $(this).attr('title');
var photo_info = $('.photo_info', this).html();
$('#photo_view img').attr({
    src : new_img
});
$('#photo_title').html(photo_title);
$('#photo_info').html(photo_info);
return false;
    });

But on some images it not work! Why it appears?

Try click on 10 image (ut-1-foto.jpg) in my example to see it.

Answer by c9220

The reason for this is that the function only binds to the elements that are already in existent when it is called. Every link created after the the document has loaded will not be bound to this function. To listen for the creation of these elements and to then bind the function to them, you could use the jQuery plugin liveQuery. I hope that helps.

Answer by Starx

For some reason you code is breaking, so it does not reach to return false.

You can use e.preventDefault(); to stop the default action

e.preventDefault();
Read more
April 10, 2012

Is there a performance friendly way to list results for each letter in the database?

Question by Gerben Jacobs

I want to create an index page with a couple of results for each letter of the alphabet.

At the moment I have this:

SELECT url_slug, name FROM artists WHERE name LIKE "A%" ORDER BY rand() LIMIT 10 
SELECT url_slug, name FROM artists WHERE name LIKE "B%" ORDER BY rand() LIMIT 10 
SELECT url_slug, name FROM artists WHERE name LIKE "C%" ORDER BY rand() LIMIT 10 
SELECT url_slug, name FROM artists WHERE name LIKE "D%" ORDER BY rand() LIMIT 10 
SELECT url_slug, name FROM artists WHERE name LIKE "E%" ORDER BY rand() LIMIT 10 
SELECT url_slug, name FROM artists WHERE name LIKE "F%" ORDER BY rand() LIMIT 10 

Is there another, a more performance friendly, way to achieve this?

P.s. I know ‘order by rand()’ isn’t very good. But this is just in development.

Answer by Starx

For the purpose you are trying to get, the query does not get better than that IMO. However, if the table is enormous, if might want to make occasional cache table holding the values of a fixed letter separately.

And indexing, index you records, as per the fields.

Read more

Is htmlspecialchars required if you are not outputting html?

Question by user1278496

I have a script that registers users based on their user input. This uses prepared statements plus whitelists to prevent sql injection. But I am struggling to understand the prevention of XSS.

From what I understand, you only need to prevent XSS if you are outputting HTML onto the page? What does this mean???

Im guessing that with this register page it doesn’t apply because I am not outputting HTML to the web page? Is that right?

If I was to prevent XSS, do I use htmlspecialchars?

Answer by JT Smith

Generally correct, if you are having any returned values show up on the page, or if you are inserting information into the database for later retrieval and display (like user profile information) you will want to use htmlspecialchars.

For me, when I do my user registration, if they fail to enter a correct value in an input field, I redisplay the page with the values they entered. In this case, I have it encoded with htmlspecialchars.

If at any point ever, you plan on redisplaying the information from the DB into a webpage (as mentioned with profiles and the like) you should use htmlspecialchars.

Better safe than sorry I always say – never trust user input

Answer by Starx

Basically, XSS happens when you are taking the user’s input un-sanitized and display in your webpage.

For example: A user inputs

<script>alert('hello you are hacked');</script>

In a text box, and you show this in your webpage after it is registered like

Hello, $username

This suddenly gets turned into

Hello, <script>alert('hello you are hacked');</script>

This is one of the form of XSS


One of a effiecient way to prevent XSS is like this

echo htmlspecialchars($varname, ENT_QUOTES, 'UTF-8');
Read more
...

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