Web Dev Q&A #2 – PHP Sessions, HTML5 Doctypes, and Form Styling
videossessions

Web Dev Q&A #2 – PHP Sessions, HTML5 Doctypes, and Form Styling

We’re back with the second entry in the Nettuts+ Q&A series. Today, we discuss the difference between LESS and Sass, how to pass server-side values to your JavaScript, how to work with PHP and cookies, and the HTML5 doctype. Here we go!


1. LESS and Sass.

Hey Nettuts+. I’m confused. What’s the difference between LESS and Sass? Are they the same?

There are advantages to using both; however, the truth is: both will get the job done wonderfully. It mostly becomes a case of preference, when it comes to the syntax and such. In the past, many preferred LESS, because it had a more friendly CSS-like syntax, though, as of Sass 3, they have a new syntax, known as SCSS (Sassy CSS), which is simply a subset of CSS3′s syntax.

The Envato devs use Sass. Other popular developer prefer LESS. I’d equate it to comparing the 960 CSS framework to Blueprint. They’re both great; so make up your own mind. There are no wrong answers!

Want to learn more about LESS on Nettuts+?


2. Server-side to Client-side

I’ve been trying to figure out how to pass the value of a PHP variable to my JavaScript. How do I do this? Thanks!

The quickest and easiest solution is to echo your desired variable from within your JavaScript. For example, you could query your MySQL database with PHP, and then pass the returned value to your JavaScript by doing something along the lines of:

<?php $myvar = 'some value'; ?> 
<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Tut</title>
</head>
<body>

<script>
	var myvar = '<?php echo $myvar;?>';
	alert(myvar); // some value
</script>
</body>
</html>	

3. Custom Stylesheets with PHP

How can I choose a color scheme stylesheet for my website dynamically?

So you want to, for instance, choose red.css, or blue.css, and that would load a different color scheme for your website. Is that what you mean? There are certainly several ways to accomplish this task, and the correct choice will depend on if you’re using a framework, a CMS, MVC, etc. Let’s keep things simple, and as bare-bones as possible. We can use PHP sessions. First, we need to add a select box, for the user to choose their desired color stylesheet.

<!DOCTYPE html>

<html lang="en">
<head>
	<meta charset="utf-8">
	<title>Tut</title>
</head>
<body>
<h2> Choose your Stylesheet </h2>
<form method="post" action="">
	<select name="colors">
		<option value="default">Default</option>
		<option value="red">Red</option>
		<option value="green">Green</option>
	</select>
	<input type="submit" name="submit" value="Go" />
</form>
</body>
</html>	
Custom stylesheets with PHP

Next, with PHP, we’ll listen for if the page has posted back — or if the Submit button has been clicked. With a simple page like this, we can use the helpful $_SERVER['REQUEST_METHOD'].

The “Request Method” determines which request method was used to access the page: ‘GET’, ‘HEAD’, ‘POST’, ‘PUT’”

At the top of your page, add the following:

<?php

if ( $_SERVER['REQUEST_METHOD'] == "POST" ) {
  // page has posted back
}
else { 
  // user hasn't submitted the form
}

?>
<!DOCTYPE html>

Since we can now confirm when the page has posted back, we can then create a session, and store the value of whatever the user chose from the select box.

<?php
session_start();
if ( $_SERVER['REQUEST_METHOD'] == "POST" ) {
	$_SESSION['color_scheme'] = $_POST['colors'];
}
else { 
      $_SESSION['color_scheme'] = 'default'; 
}
?>

Here, we’re first creating a new PHP session, with session_start(). Next, we create a new key, with $_SESSION, called “color_scheme.” Feel free to name this how you wish. By default, we set this to “default” (see the “else” statement). This means that, if the user hasn’t selected a stylesheet, we’ll use the default one. However, if they did make a choice, we need to determine which option from the select element they chose, and store it in a Session key.

Returning to the mark-up, you’ll find that we applied a name of “colors” to the select element.

<select name="colors">
	<option value="default">Default</option>
	<option value="red">Red</option>
	<option value="green">Green</option>
</select>

When the page posts back, the selected value of this select element will be available to us, via $_POST['colors']. For example, if I choose the “green” option, $_POST['colors'] will then be equal to “green.”

Without sessions and cookies, there would be no way to “remember” this user-selected value. That’s why they’re essential in this case. Now that $_SESSION['color_scheme'] stores our desired value, we only need to load the appropriate stylesheet.

<head>
	<meta charset="utf-8">
	<title>Tut</title>
	<link rel="stylesheet" href="<?php echo $_SESSION['color_scheme'];?>.css" />
</head>

4. Rounded Form Elements

Hi Nettuts+! How do I create rounded form inputs with CSS for all browsers?

So you want stylized, rounded inputs in all browsers, including Internet Explorer? Okie dokie. Consider the following simple mark-up:

<form>
	<label for="name">Name: </label>
	<input type="text" name="name" />
	
	<input type="submit" value="Go" />
</form>
Base markup

Using some simple CSS3, we can create rounded corners for those inputs. Because some browsers got a headstart on the spec, we need to use the -moz and -webkit vendor prefixes, as well as the official version of the “border-radius” property.

<style>
	input {
		border: 1px solid #666;
		-moz-border-radius: 4px;
		-webkit-border-radius: 4px;
		border-radius: 4px;
	}

	input[type=submit] {
		-moz-border-radius: 25px;
		-webkit-border-radius: 25px;
		border-radius: 25px;
	}
</style>
  • -moz: Mozilla browsers (Firefox)
  • -webkit: Webkit browsers (Safari, Chrome)
Rounded corners

By specifying atype attribute of submit, that last snippet will only target submit buttons, and will style accordingly.

That Blasted IE

Unfortunately, as you probably guessed, Internet Explorer is a jerk. While the upcoming IE9 has support for border-radius (without a prefix), the older versions are still at a loss. At this point, you have two choices:

  1. Ignore it. The world won’t end if your readers see 90 degree angles.
  2. Image Fallback. You can target Internet Explorer specifically, and apply a rounded background image.

Modernizr

I’m assuming the asker of this question requires consistency; so we’ll go with the second option. Let’s assume that you’re going to be working heavily with CSS3 and HTML5 in your project. In that case, rather than using an IE-only stylesheet, why not have some fun, and use the helpful Modernizr library?

First, download Modernizr, and reference the modernizr.js file within your project.

<head>
	<meta charset="utf-8">
	<title>Tut</title>
	<script type="text/javascript" src="modernizr-1.5.min.js"></script>
</head>

Next, apply a class of no-js to the Html element on your page.

<html lang="en" class="no-js">

When you view your project in the browser, Modernizr will apply a long string of classes to the Html element, which specifies exactly what your browser is capable of. Note that, obviously, this list of classes will vary, depending upon the browser.

Modernizr

This is a huge help! Now we can use the “cascade” effect to only target the form elements that are children of the html element with a class of “no-borderradius,” and style accordingly.

If the browser does not support a particular feature, the word “no” will be prefixed to the rule.

/* Only targets browsers which don't support border-radius */
.no-borderradius input {
	background: url(path/to/rounded/background/image) no-repeat;
}

And then we relax and have cake.


5. Doctypes

I noticed that you always use the HTML5 doctype. Don’t you think that’s dangerous, when all browsers don’t yet support HTML5?

No, it’s not dangerous at all. For those unfamiliar with the wonderfully simple HTML5 doctype, it’s:

<!DOCTYPE html>

Seriously…that’s it. That’s all there is to it. No more multi-line spats of attributes; just a plain-ole DOCTYPE – as it should be. In older browsers, this doctype will trigger them into standards-mode. …And if you’re still worried, note that even Google uses it! Need more? John Resig was talking about this 2.5 years ago!

“What’s nice about this new DOCTYPE, especially, is that all current browsers (IE, FF, Opera, Safari) will look at it and switch the content into standards mode – even though they don’t implement HTML5. This means that you could start writing your web pages using HTML5 today and have them last for a very, very, long time.”
-John Resig


Read Previous Q&A’s


Ask Nettuts+…

If you have a “not-too-complicated” web development question for us, you can:

  1. Email net@tutsplus.com, and write “Web Dev Q&A” as the subject of the email.
  2. Tweet us @nettuts, and hash “#askNettuts”.
  3. Leave a comment under any “Web Dev Q&A” posting with your new question.

Thanks for reading and watching!

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • sumit

    any good frameworks for forms?

  • http://www.monitojoomla.com jmarreros

    Thanks, Jeffrey

  • http://www.jsxtech.com Jaspal Singh

    Nice tutorial for HTML5, css tricks.
    Thanks for sharing.

  • http://www.ecustom.ca/ Damon Bridges

    Jeffrey, I dunno if this is “allowed”, or if it even works, but I saw a JavaScript page linked to in a website, but the src was a URL where the actual name of the JS file was script.js.php.

    I assume this was done to allow for variables, in an external JS file, but would it work? Because, if it would, it might answer the one question in an alternative way.

    • http://askbahar.com Habib Ullah Bahar

      Yes, its possible.

      Via script.js.php (which is actually a php script), the js is outputted with header ‘text/javascript’. This is usually done to achieve general js or user based js or to implement CDN.

    • Joshua

      This absolutely works. I use it all the time to query wordpress, get random posts from certain categories, and output some javascript to switch between them. Like Mr. Bahar says, just write the header. I use “Header(“content-type: application/x-javascript”);” but “text/javascript” may also work.

  • http://sourcecodemagic.com sourcecodemagic

    thanks for sharing

  • http://www.enciende.cl EmpreJorge

    2. Server-side to Client-side
    How can I do this but with an external file??
    ex:

  • http://www.enciende.cl EmpreJorge

    externalfile.js?myvar=myvalue

  • arnold

    really good tips here jeff.
    is HTML 5 Doctype safe for IE6?

    • MIchael

      yes it is, it will generate the standards-mode..

      you can use it anytime, anywhere. always ;) enjoy it.

      • arnold

        thanks Michael…

      • http://www.dsravago.com evilrave

        i think you better check the DOCTYPE for IE6. Here in my office we still use IE6. All HTML5 sites are not compatible with IE6.

      • http://www.jeffrey-way.com Jeffrey Way
        Author

        Not true. The HTML5 DOCTYPE will simply push IE into standards mode, if it doesn’t understand it.

  • http://www.ifadey.com Fawad Hassan

    These Q&A posts are great :)

  • ShadowAssassin

    Amazing article, really useful, one of the better articles here, I loved 2 – I never knew you could do that, that has seriously saved me from some coding work :)

  • jerryliu

    “The world won’t end if your readers see 90 degree angles.”
    YES, but my boss will end me

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      haha

    • michael

      Hehe, I do this too, since several months.
      I just inform the client, look, if someone uses a modern browser, it looks like this, if someone uses an old browser, it looks like this.

      I don’t longer use fallbacks for simple things like rounded styles, shadows and background-transitions.
      IE6 users just don’t deserve the nicer look ;)

  • Rik de Vos

    Maybe you can explain us how to work with CSS Frameworks :)

    Rik

  • http://www.create.cm Matt

    After reading the article i think this has to be one of better articles Jeffrey has written, very intuitive and precise. Thanks jefferey

  • andrei

    border radius is possible in ie with VM, you can find an implemenation here http://www.dillerdesign.com/experiment/DD_roundies/

  • http://www.jordanwalker.net Jordan Walker

    Good tutorial on less covered web development topics.

  • Derrick Nelson

    $myvar = “‘;\nalert(‘All your cookies are belong to me now.”;

    :(

  • Cipa

    I have some questions myself(probably a stupid one but I could not find an answer).
    Why use LESS over Blueprint? Why use Blueprint over LESS?

    • http://nzmedia.dk Bruno_Dev

      LESS is not the same as Blueprint. Blueprint is the same as the 960 framework, and LESS is the same as Sass

  • http://mediagearhead.com Giles Wells

    I recently was directed to http://css3pie.com and their project to make css3 come to internet explorer. I have to say I was very impressed. With a simple line added to the css of an element that uses css3 properties Internet Explorer can render them all just fine. It nearly knocked me off my chair when I saw it working for the first time.

    I wish that a quick tip could be created for this as it would make many people happy to find such a simple way to get css3 into IE without image fallbacks.

  • http://phpforms.net/tutorial/html-basics/php-forms.html PHP form

    To tell the truth I am afraid of HTML 5

  • ali

    php sessions?

  • http://connorcrosby.me Connor Crosby

    Wow, that doctype for HTML5 is so simple, and that is the way it should be! I am sort of new to HTML and I hate doctypes – trying to figure out which to use.

  • http://sourcecodemagic.com rusty

    thanks nice tutorial

  • http://www.jasoncorbett.com.au Jason

    Jeffrey your my idol!

  • http://no.no.com no

    So….what about Opera? Modernizr picks up the lack up border-radius but it’s surprising that when there are only 4 major rendering images, you can forget about one.

  • Budi Wicaksono

    But Jeff, where’s the video part? i’m not seeing any kind of video stuff in this page..

  • Max

    Thank you, top-notch tips and tricks

  • http://www.frankbr.nl Frank

    $_SESSION['color_scheme'] = $_POST['colors'];

    does seem fair to check wether $_POST['colors'] is filled, especially in these tutorials it is ofter forgotten, which I think is a bad idea because there will be people who copy and paste the example as it is.

  • http://www.marcvonbrockdorff.com Marc von Brockdofff

    Great post – nice set of tips. I’ve never used either LESS or Sass but will be giving them a try after reading this.

  • http://www.4muladesign.com Jamie

    Where is the video?

    • http://www.jeffrey-way.com Jeffrey Way
      Author

      Will record it tomorrow.

      • http://www.4muladesign.com Jamie

        Ah cool, cheers Jeffery.

  • http://imanto.net Anto

    Yea i was gonna say about the thumbnail having a play icon :P and no video. Anywhoo as always Jeff nice post.

  • sunny

    Hi Nettuts+,

    Isnted you started Q&A on video tutorial plus written, so you becoming lazy like me =) .

    But thanks, it helped.

    -Sunny

  • Khalil

    Deary Jeffrey Way,

    Please help me boss. How to select last 3 list items? if there isn’t matching any attributes out there like in my code.

    reply 1
    reply 2
    reply 3
    reply 4
    reply 5

    I have tried a lot. I found this code but it is selecting first three ones not last ” li:lt(3) ” …

    please reply. Thanks

  • Payton

    Thanks Jeff, the custom style sheets with PHP was what I was looking for! Simple enough, woot!