Sep 9, 2011

More PHP in this blog lately

Recently I work too much with PHP so naturally this blog will go in this direction. I’m trying to be short and at the point, with small but useful snippets of code. I hope that they will help you in some way.
I can’t write long and meaningless chunks of text and when I read developers books I tend to read only the code. In very rare occasions I read some other explanations - they are good when you talk about methodology or algorithm but examples are best when you talk about basics. Actually, this is just an excuse. The main reasons for more code than text in this blog is that I can’t write text.

How to make tar and tar.gz archives with PHP

This question is somewhat painful for me. Maybe I am too stupid. Anyway, if you want to make tar archive without using exec, for example on Windows machine without tar tool or any other stupid reason, here is how to do it with PHP. Its actually very easy if you know how to do it.

For example lets have a directory called dir and we want to make an archive with its content. The solution for our problem is Phar.

Here is the code that do the job:

<?php

// we want to archive all files from this directory
$dir = "dir/";

// the name of our new tar
$phar = new Phar("ourarchive.phar.tar");

// build from our dir
$phar->buildFromDirectory($dir);

// we are using gzip comppression
$phar->compress(Phar::GZ);

?>
Look carefully at the name of our archive - the parameter that we give when we create Phar object. It ends with phar.tar. If you use only .tar it will return error:
Fatal error: Uncaught exception 'UnexpectedValueException' with message 'Cannot create phar 'ourarchive.tar', file extension (or combination) not recognised
This is not fun if you are trying to create tar and you receive this message. So using file name that ends with phar.tar will fix the problem.

If you receive error:
Fatal error: Uncaught exception 'BadMethodCallException' with message 'Unable to add newly converted phar "/www/pro/ourarchive.phar.tar" to the list of phars, a phar with that name already exists'
most likely your tar file already exist.

Learn here how to make Zip archives with PHP

How to make Zip archives with PHP - part 1

Actually working with zip archives isn’t that obvious that it looks from the documentation. But if you want an adventure try to make tar or tar.gz. Actually in one of my next posts I will describe the procedure. Now, we are talking about zip here.

Example: Create archive and add file to it
<?php
 // the file that we want to compress
 $file = "path/filetocompress.txt";

 
 // how we want to name the file in the archive
 $name = "filename.txt";
 
 // we need to create new object
 $zip = new ZipArchive();

 
 // we are using ZipArchive::open with flag CREATE to make new zip archive
 if ($zip->open("ournew.zip", ZipArchive::CREATE) === TRUE) {

  
  // here the first parameter is the file on our system
  // the second is the name to be used for this file in our new zip 
     $zip->addFile($file, $name);

     
     // close is used for both close and save
     $zip->close();
 } else {

     echo 'Error';
 }
?>

Fast PHP example - FTP file upload

Here is one fast and simple example on how to do FTP file uploads with PHP.
<?php

$ftp_server = "ftp.server.url";

$ftp_user = "user";
$ftp_password = "password";

$file_to_upload = "localfile.txt";
$remote_location = "/location/file.txt";

// set up connection or exit with message
$flink = ftp_connect($ftp_server) or exit("Can't connect to ftp server: $ftp_server");

// login or at least try  
if(ftp_login($flink, $ftp_user, $ftp_password)) {

 
 // if login successful use ftp_put to upload the file
 // if you upload binary files use mode FTP_BINARY
 if(ftp_put($flink, $remote_location, $file_to_upload, FTP_ASCII)) {

  echo "Success! File is uploaded!";
 } else {
  echo "Can't upload file";

 }
} else {
 echo "Can't login with this user & password";

}

// close the connection
ftp_close($flink);

?>
You can get more information at http://www.php.net/manual/en/ref.ftp.php

Aug 19, 2011

PHP : Handling file uploads - easy tutorial with example

Handling file uploads with PHP is very easy task and here you will learn how to do it. And because I believe that people learn best with examples lets start with this.
Now lets upload one file to some user directory on a server. Lets create file upload_form.php on our server. It will contain mainly html code:

upload_form.php
<html>
<body>
<form enctype="multipart/form-data" action="upload.php" method="POST">

    File: <input name="ourfile" type="file" />
    <button type="submit">Upload</button>

</form>
</body>
</html>

Its very simple file with only one form. Don’t forget to add enctype="multipart/form-data" to your form when its used for file uploads. In this form we have to fields - the first is our file and the second is the submit button.
Now we need another file upload.php. Here is its content

upload.php
<?php
$dir = '/var/www/files/';

$destinationfile = $dir . basename($_FILES['ourfile']['name']);

if (move_uploaded_file($_FILES['ourfile']['tmp_name'], $destinationfile)) {

   echo "Upload successful!";
} else {
   echo "File attack!\n";

}
?>

Here we have destination directory for our uploads - $dir = '/var/www/files/'. Our file will be saved in this directory and will have the name of the uploaded file.
The function move_uploaded_file checks if the file (first parameter) is a valid uploaded file and if its valid it moves it to $destinationfile. If you just want to check the file without moving it use is_uploaded_file instead.
And that’s all. Now if you have done everything the right way you must see “Upload successful!” when you use upload_file.php and upload file.

The original of this tutorial is here http://ldeveloper.blogspot.com/2011/08/php-and-handling-file-uploads-easy.html

Aug 16, 2011

PHP: Playing with StdClass

What is StdClass and where does it live?

StdClass is a document class in PHP with no predefined members. Its the class that is created when you cast something to object like this:

$obj = (object) $something;

Sounds good but how to get its members if we don’t know about them? Actually, its very easy and we have several approaches.

First, we can iterate through its members with foreach:
foreach ($obj as $key => $value) {
   
}
Second we can cast our object to array:

$array = (array) $obj;

Or get its members as array:

get_object_vars($obj);

What else we can do with StdClass?
We can create objects and assign members:
$std = new StdClass();
$std->key = "value";
and access them:
echo $std->key;
If you see an error like this:
Catchable fatal error: Object of class stdClass could not be converted to string
the culprit is our stdClass of course. Maybe you are trying to print an object of this class.

Read how to use SOAP with PHP

Aug 11, 2011

How to use SOAP with PHP - very simple tutorial and example

Using SOAP with PHP can be very easy if you do everything right. First your PHP must be configured with --enable-soap. With Windows and WAMP you only need to check PHP > PHP extensions -> php_soap. You can read more about the configuration here http://www.php.net/manual/en/soap.configuration.php but most likely you don’t need to do anything else.

$client = new SoapClient("http://localhost/SomeSoap.wsdl");
$something = $client->SomeFunction();
var_dump($something);

And that’s all.
If you get Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host in the row of
$something = $client->SomeFunction();
your problem may be in your soap configuration or something like this.

How to stop Skype from using port 80

Its very annoying when you want to use port 80 with apache for example and you must stop Skype, start the service and start Skype again.
Also its annoying when you install WAMP Server and its not working or at least apache is not working because Skype is on port 80 and you’ve totally forgotten about it. If you are little absent minded like me, you may spend even few hours looking for the problem and installing WAMP again.

Open Skype, select Tools from the menu, then Options, go to Advanced Settings and then Connection. There is a checkbox with the text
Use port 80 and 443 as alternatives for incoming connections
Uncheck it and hit Save. That’s it. You may need to restart Skype for the changes to take effect. I hope that this will help you.

PHP - Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host in …

I receive this nasty error yesterday and it took me some time to figure out the problem. This line passes without any problems

$client = new SoapClient($url);

and this

var_dump($client->__getFunctions());

shows the function prototypes correctly. So it connects and gets the data but when I try to call a function I receive this error

Fatal error: Uncaught SoapFault exception: [HTTP] Could not connect to host in MyFile.php:23 Stack trace: #0 [internal function]: SoapClient->__doRequest('__call('myFunction', Array) #2 …

I made fast research and found that people receive this error when their php installation isn’t right or because they are trying to use it with https without the openSSL extension. So you can receive this problem with various situations. Anyway my code was right so I took a look at the service description that I received from the server and there was the problem. The server wasn’t configured right

<service name='myService'>
 ...
  <soap:address location='http://some_other_url'/>
 ..
</service>

It was configured to send invalid url and the function calls were using that invalid url. So there are two solutions - one correct and one that is almost correct but it works for testing purposes when you wait for people to fix their server. So the first is to configure the server correctly. The other is to give __doReguest the correct location.
I hope this will help somebody because founding the problem was very frustrating for me.

Nov 30, 2009

Walking around with JQuery

Selecting, traversing, and manipulating DOM elements is relatively easy with JQuery. You can play with them and do many cool things.

Let’s start with simple selecting. We may need a list of all the images in a document. This can be achieved very easy:

 $("img")
Let’s hide them:
       $("img").hide();

Now, if we don’t want all images but only images located in div tag we can do this:
       $("div > img").hide();
Selecting element with a specific id is very simple:
       $("#myId")
And we can obtain a list of images located in this specific div with the expression:
       $("#myId > img")
We can get a list of elements from a certain type and having a specific class. For example we can get a list of all div elements who have css class text and hide them.
       $("div .text").hide();

If we get a list of elements from another source (for example some function) and we want to obtain only the ones with a exact property we can do it with filter. In this example I’ll select all div elements and check them:
       $("div").filter(".text").hide();

After hiding all elements we may want to show the first one. Here we have several approaches. If the circumstances are right we can just select the first element:
        $(".text:first").show();
Of course we may want the last one:
        $(".text:last").show();
We can get the n-th element using eq. Keep in mind that arrays start from 0.
        var n = 1; // we want the second element in reality
        $("div:eq("+n+")").show();
We can obtain all elements on a page that contain a specific text:
        $("div:contains(text)"). css("background-color","yellow");
Or we can obtain all div elements containing a specific text (text) and not specific css class:
         $("div:contains(text):not(.title)"). css("background-color","yellow");
I’ll continue with more later.

Nov 16, 2009

How to write your own jquery plugins – random size plugin

Let’s continue our plugin example. I’ll change the plugin from the first post to something a little more fun.

RandomSize plugin – it will change the font size of all inner html elements with random values. For this goal we need a list of 'this' element children.

var c = $(this).children();

We can generate random numbers with the expression:

Math.floor(Math.random() * max)

where max is our max value. Also it is better to have a min value because people can’t read font with size 1. So our expression will evolve this way:

Math.floor(min + Math.random() * (max - min))

Here is the plugin code:
(function($) { 
$.fn.randomSize = function(settings) {
    var config = { 
     'min':'10', 
  'max':'30',
  'fontWeight' : 'bolder'};
    
     if (settings) 
      $.extend(config, settings);
 
     this.each(function() {
  var c = $(this).children();
  c.each(function() {
   var rand = Math.floor(
    parseInt(config.min) + 
    (Math.random() * 
    (config.max - config.min)));
    
   var cssObj = { 
       'font-size':rand + 'px', 
       'font-weight':config.fontWeight};
   $(this).css(cssObj);
  });
   
     });
 
     return this;
};
})(jQuery);

Sample html:
<div>
 <span>Element 1</span>
 <span>Element 2</span>
 <span>Element 3</span>
</div>

And we call it like this:
$("div").randomSize();

How to write your own jQuery plugins

Packing your code into plugins will make it easier for maintenance and reuse. JQuery plugins can accelerate the development process and simplify the final product. Writing your own plugins isn’t hard either.

Ok, let’s start with a very simple plugin. I have very little imagination, so my plugin will do very stupid work – it will change the font size and weight of an element. I’ll call it … demoPlugin. Original, isn’t it?

Let’s define it:
$.fn.demoPlugin = function(settings) {
}
And we will call it this way:
$("div").demoPlugin();
Some initial configuration like this:
var config = {'fontSize' : '30px', 'fontWeight' : 'bolder'};
And we will extend it with the parameters provided by the user.
if (settings) 
 $.extend(config, settings);
And our main code goes here:
this.each(function() {
   $(this).css({

      'font-size':config.fontSize, 
      'font-weight':config.fontWeight});
       });
Here is the full plugin code:
(function($) { 
 $.fn.demoPlugin = function(settings) {

   var config = {
    'fontSize' : '30px', 
    'fontWeight' : 'bolder'};

       if (settings) 
    $.extend(config, settings);
 
       this.each(function() {
   $(this).css({

      'font-size':config.fontSize, 
      'font-weight':config.fontWeight});
       });
 
       return this;

  };
})(jQuery);


Don't forget to return this at the end. It is very important in order to use chain calls.

I’ll continue with less trivial plugin example later.

Next plugin article.

Nov 7, 2009

Selecting elements with JQuery – examples

JQuery Library is a very convenient way for selecting page elements. You can select elements by type, by parent, by index and so on.
The easiest way to select an item is by its id. I’ll use it for my control buttons. For all three of them I’ll bind functions to their click event.
Here are my buttons as HTML code:

<button id="all">Show/Hide ALL</button>
<button id="nth">Show/Hide nth</button>
<button id="odd">Show/Hide ODD</button>

And my test javascript code here:

$(document).ready(function() {
 $("#all").click(function () {
  alert("Clicked ALL");
 });
 $("#nth").click(function () {
  alert("Clicked NTH");
 });
 $("#odd").click(function () {
  alert("Clicked ODD");
 });
});

Now we will change the code to select and toggle the desired elements. We will start with the first because it is the easiest of them all. Selecting elements by type in JQuery is very simple and is done through their name. To select all paragraphs we simply need to use $("p") and call toggle on it. $("p") will return all matched elements – all ‘p’ tags on the page.
The code:
$("#all").click(function () {
 $("p").toggle();
});

To select the n-th element – in our case the third one we will use $("p:eq(3)") and to select all odd paragraphs $("p:odd").

Here is the full example code:
<html>
<head>
<title>Selecting elements with JQuery</title>
<script  src="jquery.js"></script>

<script>
$(document).ready(function() {
 $("#all").click(function () {
  $("p").toggle();
 });
 $("#nth").click(function () {
  $("p:eq(3)").toggle();
 });
 $("#odd").click(function () {
  $("p:odd").toggle();
 });
});
</script>
</head>
<body>
JQuery example - selecting items.
<div>
<p>Paragraph 0</p>
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<p>Paragraph 3</p>
<p>Paragraph 4</p>
</div>
<div>
<table>
<tr><td>All Paragraphs: </td><td><button id="all">Show/Hide ALL</button></td></tr>
<tr><td>Third paragraph: </td><td><button id="nth">Show/Hide nth</button></td></tr>
<tr><td>All odd paragraphs: </td><td><button id="odd">Show/Hide ODD</button></td></tr>
</table>
</div>
</body>
</html>

As you can see – very simple and intuitive.

Nov 2, 2009

How to make very simple JavaScript slideshow with JQuery

I’ll continue my article about JQuery Effects - with this one. It would be short information on how to make custom JQuery slideshow animation.

Let’s start with a div containing our images. Here is the code:

<div id="slideshow">
    <img src="img1.jpg" />
    <img src="img2.jpg" />
    <img src="img3.jpg" />
    <img src="img4.jpg" />
    <img src="img5.jpg" />
    <img src="img6.jpg" />
</div>

I’m not really good at using CSS so it would be pretty simple.

#slideshow {
    position:relative;
    height:200px;
    width: 210px;
}
#slideshow img {
    position:absolute;
    top:10px;
    left:5px;
}

I’ll use some initializing code to hide all the images, and then I’ll show only the first one. Here is the code packed in a function.

function init() {
 $('#slideshow img').hide();

 $('#slideshow img:first').show();
}

And now, we must write the logic of our slideshow. We need to obtain the visible image, hide it and show the next one. When we hit the end, we need to revert back at the first element.
So let’s start with obtaining the visible image. It is simple with JQuery selectors:

var $top = $('#slideshow img:visible');

And get the next image:

$next = $top.next();

This won’t help us when we reach the last image. I’ll make a check for the last element:

var $next;
 if($top.next().length > 0)
  $next = $top.next();

 else
         $next = $('#slideshow img:first');

And now the action:

$top.hide();
$next.show();

Our slide function must be called on a regular basis. We will obtain this with the JS function setInterval.

setInterval( "slide()", 3000 );

And here is the full code:

<html>
<head>
<title>JQuery Slideshow examples</title>
<style>

#slideshow {
    position:relative;
    height:200px;
 width: 210px;
}
#slideshow img {
    position:absolute;
    top:10px;
    left:5px;
}
</style>
<script  src="jquery.js"></script>
<script>
function init() {
 $('#slideshow img').hide();

 $('#slideshow img:first').show();
}
function slide() {
    var $top = $('#slideshow img:visible');

    var $next;
 if($top.next().length > 0)
  $next = $top.next();

 else
        $next = $('#slideshow img:first');

 $top.hide();

 $next.show();
}

$(document).ready(function() {
 init();
    setInterval( "slide()", 3000 );
});

</script>
</head>
<body>
<div id="slideshow">
    <img src="img1.jpg" />

    <img src="img2.jpg" />
    <img src="img3.jpg" />
 <img src="img4.jpg" />

 <img src="img5.jpg" />
 <img src="img6.jpg" />
</div>
</body>
</html>

Working demo

Oct 27, 2009

Intro to Struts (1.x) - Practical Example

This would be simple and easy tutorial on how to use Apache Struts in Java web projects.

What do you need for this tutorial?
  • Java
  • Tomcat
  • Java IDE (For example Eclipse or NetBeans)
  • Struts 1.x version http://struts.apache.org/download.cgi#struts1310

I’ll write another document for Struts 2.x. They are different frameworks with somehow different ideas but both are excellent choice.

For clearness it would be very simple code - I won’t use packages or other good practices. Consider this only as an introduction not a reference.

Struts programming is centered at the MVC pattern. MVC stands for Model-View-Controller, an idea to separate the business logic, application data and the presentation layer. I won’t discuss here what the advantages of using MVC architecture in web application are – just make a fast search, there is plenty of information out there.

Let’s start with creating a new project. Our web application would ask visitors for a name and redirect them to a Hi! page. At part 2 it won’t like some of the visitors and will return back them with an error message.

Here is my directory and file structure for Struts1Example project:
Struts1Example
 src
  NameAction.java
  NameActionForm.java
 webroot
  WEB-INF
   classes
   lib
   struts-config.xml
   web.xml
  ask.jsp
  greet.jsp

Lets start with writing our ActionForm – I’ll name the class NameActionForm. It would be very plain – only one field and a setter-getter pair. Here is the code:

NameActionForm.java
import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;


public class NameActionForm extends ActionForm {
 private String name = null;

 
 public void reset(ActionMapping mapping, 
    HttpServletRequest request) {

        this.name = null;
 }

 public String getName() {

  return name;
 }

 public void setName(String name) {

  this.name = name;
 }
}

And our action:

NameAction.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class NameAction extends Action {

 public ActionForward execute(ActionMapping mapping, 
    ActionForm form,
    HttpServletRequest request, 
    HttpServletResponse response) {
  return mapping.findForward("success");
 }
}

In Struts the Action class goal is to process a request, do the logic and pass a forward object (ActionForward). Our Action is very simple – it is doing nothing, just passes our forward object. The “success” forward is defined in our struts-config.xml.

We will have two jsp files – ask.jsp and greet.jsp. In ask.jsp we will ask visitors for a name.
ask.jsp
<%@ page language="java" contentType="text/html; 
  charset=utf-8" %>

<%@ taglib uri="http://struts.apache.org/tags-html" 
  prefix="html" %>

<html:html>

<head>
<title>Say Hi!</title>
</head>
<body>
 <html:form action="nameAction">
  What's your name?
  <html:text property="name"></html:text>

  <html:submit>Send!</html:submit>
 </html:form>
</body>
</html:html>

greet.jsp
<%@ page language="java" contentType="text/html; 
  charset=utf-8" %>

<%@ taglib uri="http://struts.apache.org/tags-bean" 
  prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" 

  prefix="html" %>
<html:html>
<head>
<title>Say Hi!</title>
</head>
<body>

Hi, <bean:write name="nameForm" property="name" />
</body>
</html:html>

And now the cool part – web.xml

web.xml
<?xml version="1.0"?>
<web-app>
  <display-name>Struts 1x Example</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
     org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>

      <param-name>config</param-name>
      <param-value>
       /WEB-INF/struts-config.xml
      </param-value>
    </init-param>
    <load-on-startup>2</load-on-startup>

 </servlet>
  <servlet-mapping>
    <servlet-name>action</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

And our struts configuration – struts-config.xml

struts-config.xml
<?xml version="1.0" ?>
<struts-config>

    <form-beans>
     <form-bean 
      name="nameForm" 
      type="NameActionForm"/>

    </form-beans>

    <global-forwards>
        <forward
            name="/nameAction"
            path="/nameAction.do"/>

    </global-forwards>
    
    <action-mappings>         
       <action path="/nameAction" 
         type="NameAction" 

         input="ask.jsp" 
          name="nameForm" >
        <forward name="success" 

          path="/greet.jsp"/>
        <forward name="failure" 
          path="/ask.jsp"/>

       </action>
    </action-mappings>
</struts-config>

struts-config.xml is used to initialize Struts. It describes the action mappings for the project and must be placed in the WEB-INF directory. We have a form-bean tag describing our NameActionForm and an action-mapping for our NameAction.

This is our base code. In some future post I’ll add field validation, error handling and some other good stuff.

Oct 22, 2009

Fun with JQuery Effects – few examples

You can use JQuery Effects in many different ways. I'll write few examples just to show how cool and fun is to work with this API.

Using toggle:

toggle.html
<html>
<head>
<title>JQuery examples</title>
<style>
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#our_button").click(function() {
$("#our_image").toggle();
});
});
</script>
</head>
<body>

<button id="our_button">Hide/Show</button> the image.
<br /><br />
<div id="our_image">
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSMhLVeVRnBTwKXkBjFX-nOQusSJyKsneDo-yTxCWJtDGVFg2FMzr4vSEWTDjCm7WgGWW1KFYadgz0y3gyXd7kuBMcMIlWijcK3ikxqRVciTwJWdaaiT6Z62m6pGWQNhKILC2oWF4Hmw/s320/flower.jpg" />
</div>
</body>
</html>


And the result:


the image.



Using slide toggle:

slide.html
<html>
<head>
<title>JQuery examples</title>
<style>
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#our_button").click(function() {
$("#our_image").slideToggle("slow");
});
});
</script>
</head>
<body>

<button id="our_button">Hide/Show</button> the image.
<br /><br />
<div id="our_image">
<img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgSMhLVeVRnBTwKXkBjFX-nOQusSJyKsneDo-yTxCWJtDGVFg2FMzr4vSEWTDjCm7WgGWW1KFYadgz0y3gyXd7kuBMcMIlWijcK3ikxqRVciTwJWdaaiT6Z62m6pGWQNhKILC2oWF4Hmw/s320/flower.jpg" />
</div>
</body>
</html>


And the result:


the image.



Easy, isn't it? Tomorrow I'll continue with animate function.

Oct 12, 2009

More JQuery examples - Intro to JQuery - part 3

How to use JQuery filter? (Easy example)



Filter is used to filter some results from a set. (of course) For example let’s have a document with many divs in it. We want to select only the ones with css class “.text” and hide them. We can do this using filter.

At the beginning lets write some dummy html file with the basics in it. Here it is our filter.htm:

<html>
<head>
<title>Our JQuery examples</title>
<style>
.text {
}
.comment {
}
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function(){
// our javascript examples will go here
});
</script>
</head>
<body>
<!-- our text will go here -->
</body>
</html>


Let’s make some divs and set class text to some of them and comment to the others.

<div class="comment">
123
</div>
<div class="text">
This will be selected.
</div>
<div class="comment">
This wont be selected.
</div>
<div class="text">
This div will be selected.
</div>
<div class="text">
Selected!
</div>

This row will hide all divs with class text.

$("div").filter(".text").hide();

It would be easy to make a button that shows and hides these divs. Here is the full source:

<html>
<head>
<title>Our JQuery examples</title>
<style>
.text {

}

.comment {

}
</style>
<script src="jquery.js"></script>
<script>
$(document).ready(function() {
$("#toggle").click(function() {
$("div").filter(".text").toggle();
});

});
</script>
</head>
<body>
Show and hide filtered divs. <br />
<button id="toggle">Toggle Show/Hide</button>
<div class="comment">
123
</div>
<div class="text">
This will be selected.
</div>
<div class="comment">
This wont be selected.
</div>
<div class="text">
This div will be selected.
</div>
<div class="text">
Selected!
</div>
</body>
</html>


Here is our work:


Show and hide filtered divs.

123
This will be selected.
This wont be selected.
This div will be selected.
Selected!

Intro to JQuery - part 1
Intro to JQuery - part 2

Sep 13, 2009

Web authorization and OAuth

OAuth is an open protocol that defines secure api authorization methods. More and more sites in internet adopt its idea and start to use it.

So what is so cool about it?
OAuth offers a way to work with protected data while securing sensitive user account information. Imagine you want to access your twitter, yahoo or google account from some third party site or application with someadditional functionality. What will happen if the consumer site or application is not so trustworthy and steal your account? OAuth is the key to protect your account in this case.
There is a very popular parallel in the web. OAuth is like the valet key that offers a limited use of your car. Not all cars came with valet keys but anyway it is a good comparison.

With OAuth the user grants access to his protected resources without sharing his username and password with third parties. Imagine a website that offers you great functionality to add and remove many Twitter followers. One way to use it is to share your credentials with it. The other is to use special token to give only few privileges but to protect your sensitive information.

Some terminology:
Service Provider – web service that offers some functionality to third parties.
Consumers – website or application that accesses protected resources of a Service Provider.

How to use it? Do I need to reinvent the wheel?
Nop. The wheel is invented. There are some ready libraries out there. http://oauth.net/code
Here is one useful tool http://googlecodesamples.com/oauth_playground/.

For more information on OAuth visit http://oauth.net/ .

Nov 13, 2008

Simple AJAX with JQuery(part 1) – ugly example

After getting some experience with JQuery from the previous tutorials, you may be ready for some fun. AJAX development is relatively easy with the JQuery framework.

For this part I’ll show how to use “load” in a basic example. We will have a online book and we will load the chapters without reloading the whole page. This is a stupid example, for many reasons. First – online publishers prefer more reloads. The AJAX functionality is a better decision for online business solutions, not for online reading. But I have no imagination for other relatively simple demo and I am lazy.

So – our example. It is an online book. We will select our chapter with prev(previos) and next buttons. The full ugly working example can be seen here - http://ldeveloper.hit.bg/book.load.html

We will store our chapter names in a JavaScript array:


var bookchapters = new Array( "chapter1.html", "chapter2.html", "chapter3.html" );



The load – loads a html and injects it into the DOM element. It can also filter the incoming document – very convenient if you don’t need the whole page.

So back to our example – the html:



<body >
<h1>JQuery and AJAX tutorial - part 1</h1>
<br />
<br />
<form>
<input type="button" value="Prev" id="prev">
<input type="button" value="Next" id="next">
</form>
<br>
<br>
<strong>Book Title</strong>
<div id="book">
</div>
</body>



And we load a chapter with the following(For this example our chapters are in a folder “book”):


$("#book").load("book/" + bookchapters[index]);



The whole code(html, js and css):


<html>
<head>
<title>JQuery and AJAX tutorial</title>
<style type="text/css">
#book {
background-color: #F0FFF0;
border : thin ridge;
height: 450px;
overflow: scroll
}
input {
background-color : White;
color : #006400;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var bookchapters = new Array( "chapter1.html", "chapter2.html", "chapter3.html" );
$(function () {
var index = 0;
$("#book").load("book/" + bookchapters[index]);
$("#prev").click(function () {
if(index > 0) {
index--;
$("#book").load("book/" + bookchapters[index]);
}
else {
alert("first chapter");
}
});
$("#next").click(function () {
if(index < bookchapters.length - 1) {
index++;
$("#book").load("book/" + bookchapters[index]);
}
else {
alert("last chapter");
}
});


});
</script>
</head>
<body >
<h1>JQuery and AJAX tutorial - part 1</h1>
<br />
<br />
<form>
<input type="button" value="Prev" id="prev">
<input type="button" value="Next" id="next">
</form>
<br>
<br>
<strong>Book Title</strong>
<div id="book">
</div>
</body>
</html>





Filtering the incoming page



This example shows how to use it. The “div:first” after the url in the load parameter string selects only the first div of the incoming document.


<html>
<head>
<title>JQuery and AJAX tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#page").load("in.html div:first");       
});
</script>
</head>
<body >
<h1>JQuery and AJAX tutorial - part 1</h1>
<br />
<br />
<br>
<div id="page">
</div>
</body>
</html>



And the in.html:


<html>
<body>
<div>
First part of the document that will be loaded!
</div>
<br>
<div>
Next part, that won't show into the other.
</div>
</body>
</html>



Nov 6, 2008

Intro to JQuery - part 2 - JQuery examples

If this is your first encounter of JQuery, I recommend the post – Intro to JQuery.

This is a short document on how-to use JQuery API. Necessary knowledge for this post includes JavaScript, HTML and CSS basics.


Let’s change the last example of the previous post a little. We can handle the logic without the counter variable:


<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
var c = parseInt($(this).html());
$(this).html(c + 1);
});
} );
</script>



We can add more complex code with the html(), not only one number. For example:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("#ourID").click(function () {
$(this).html(String($(this).html() + "<br/><b>We added a row!</b>"));
});
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
Click in the box:
<div id="ourID" style="font-size: larger;background-color: #FFA500;border : medium dashed;text-align: center; width: 250px">
This is our test div element.
</div>
</body>
</html>



Be careful to add a correct html for the html() function value or you will end with unexpected results.

JQuery have more methods for DOM manipulations. For full list of these methods I recommend reading the documentation - http://docs.jquery.com/Manipulation

Very power JQuery functionality is the opportunity to easily traverse the DOM tree. One very useful element in this part is the each(). It is used to execute a function within the context of every matched element. This is simple example of its usage:


<html>
<head>
<title>JQuery basic tutorial</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("div").each(function () {
$(this).css({border : "medium double Red", backgroundColor: "orange"});
}
);
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div>First div element
</div>
<div>Second div element
</div>
</body>
</html>



And now a little more complex example:
The code bellow gets all the <p>(paragraph) childs of the <div> elements and sets them a css class “our class”. There are many other ways to achieve the same thing, this is just example of using each() and children().


<html>
<head>
<title>JQuery basic tutorial</title>
<style type="text/css">
.ourclass {
border : medium double #FFA500;
width: 90px;
height: 90px;
}

</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function () {
$("div ").each(function () {
$(this).children("p").each(function () {
$(this).addClass("ourclass");
});
}
);
} );
</script>
</head>
<body>
<h1>JQuery basic tutorial</h1>
<div style="border : 1px solid Black;">First div element<div></div>
</div><br/>
<div style="border : 1px solid Black;">Second div element with two paragraphs
<p>First <b>p</b></p>
<p>Second p</p>
</div>
<p style="border : 1px dotted Black;">This is a paragraph but it is not a div child</p>
</body>
</html>

Popular Posts