Posts

Saying Goodbye to Google Blogger

Hey guys! How are you? I'm so happy today. I'm almost done re-creating this website. Why? I switched from Blogger to WordPress! Yes, you read it right.

I love WordPress!

Some of you may know that I'm a Google fan. I love Google. There was a time when I worked with a product manager from Google Singapore to improve Google Maps. But you know, everyone has imperfections. I don't have love for all Google products and services.

This is my very first post using a self-hosted WordPress blog. It feels like I'm in heaven. I'm loving it so much and have a million reasons why. I'll list some of them below but first, I want to tell you...

Why I left Blogger?

I know, i know, it sound like breaking up. It's almost the same anyway. Here are some reasons I had in mind.

  1. It is very simple and boring. Simplicity is really good but a time will come when you will want to achieve simplicity with a little bit complexity. It is fun and you'll be thrilled. In this case, I'm learning more about SEO and social media, Blogger does not have enough tools for me to do that. I can't control URLs, meta data, and other factors that may contribute for our site to rank higher.
  2. I don't enjoy programming in the Blogger platform. I understand how the template can be done or modified in Blogger. I even made a responsive blogger template. But it's still very limited. It feels like I cannot unleash the true Ninja within me when I stay. Blogger is not PHP, it is not Android. WordPress allows me to enjoy more of PHP programming or Web development.
  3. Blogger does not have a large community I can relate to. WordPress is made with PHP and other web development technologies that I can absolutely relate to such as HTML, CSS, jQuery and JavaScript.
  4. I'm disappointed with Blogger themes, tools or plugins. I think this is because programming with the blogger platform is something developers hate. WordPress plugins and WordPress themes has thousands of useful items you can choose and developers are actively contributing to it because of this little thing called love.
  5. I forgot some of the reasons why I left blogger, but I'll add it here once I thought of it. You might also want to add yours, just drop it in the comments section below!

Blogger is the very first blogging platform I love. It is very easy to set up, free, hosted by Google and can get you started really well! It is the reason why my Google Adsense account was approved.

But when are learning really well and achieving some levels of success, you will have to upgrade with something you have

Why I love WordPress?

Seriously, do I really even need to have a list for this? Okay, I'll just make it quick since I feel like my brain is shutting down right now.

  1. Really easy to manage posts. Writing features are really great especially the distraction free writing mode.
  2. Makes your site a lot faster. Well, it depends on your hosting server, if you have a high traffic site, a VPS might suit you well.
  3. Themes and plugins. I'm really amazed with a lot of beautiful themes (free or paid), and very useful plugins WordPress can offer - for your site's visual design, SEO, and more!
  4. More control. With a self-hosted WordPress site, you have more control over your data and how they can be used.
  5. Enjoyment. Developing a website or any app with a programming technology or language you know is such a joy. You can do more and feel more productive in everyday of your life.
  6. Add your reason here.

Even though switching to WordPress cost me few bucks, that's really okay. It was covered by my income from my Adsense account, speaking engagements and private tutor services which I was able to do through the discovery of my blog.

So that's it for now guys! If you want to add something to my list, feel free to drop it in the comments section below, I'm willing to update this post for you! I'm shutting down and need some sleep now, Good night!

jQuery UI Autocomplete Example

We, the developers, want to help our users search for the data they are looking for – in an easy manner.

This jQuery UI autocomplete tutorial will help you achieve it!

Having an autocomplete feature in our search box is really good for the user experience, it is like having a user assistant while he is trying to search.

Our code for today will make use of a textbox where the user can type his search term. The sample data we use are person names (firstname and lastname).

So, when the user types a name, our program will suggest some names that might be what the user is looking for.

Project Files

Our code for today includes the following files:

libs/db_connect.php
images/ajax-loader.gif
css/style.css
index.php
results.php

Database

The table structure used and some sample data were provided below:

--
-- Table structure for table `users`
--
 
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(32) NOT NULL,
  `lastname` varchar(32) NOT NULL,
  `gender` varchar(6) NOT NULL,
  `email` varchar(32) NOT NULL,
  `username` varchar(32) NOT NULL,
  `password` varchar(32) NOT NULL,
  `created` datetime NOT NULL,
  `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=76 ;
 
--
-- Dumping data for table `users`
--
 
INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `email`, `username`, `password`, `created`, `modified`) VALUES
(49, 'Justine', 'Bongola', 'Male', '[email protected]', 'jaja', 'jaja123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(51, 'Lourd', 'De Veyra', 'Male', '[email protected]', 'lourd', 'lourd123', '0000-00-00 00:00:00', '2013-03-03 14:06:03'),
(73, 'Mike', 'Dalisay', '', '', 'ninjazhai', 'allisfine', '0000-00-00 00:00:00', '2013-05-12 06:39:04'),
(74, 'Darwin', 'Dalisay', '', '', 'dada', 'dada123', '0000-00-00 00:00:00', '2013-05-12 06:39:24'),
(75, 'Marykris', 'Dalisay', '', '', 'mary143', 'mary123', '0000-00-00 00:00:00', '2013-05-13 16:51:14');

Here’s how we connect to the database, just change the variable values that will make you connected to your database.

<?php
$host = "yourHost";
$db_name = "yourDatabaseName";
$username = "yourDatabaseUsername";
$password = "yourPassword";
 
try {
    $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password);
}catch(PDOException $exception){ //to handle connection error
    echo "Connection error: " . $exception->getMessage();
}
?>

The User Interface

index.php – this is where the user can find the textbox, tries to type on it and our system suggests some keywords as autocomplete, and this is also where we include our jQuery UI theme and jQuery scripts.

<!DOCTYPE HTML>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        <title>jQuery UI auto-complete tutorial live demo</title>
 
        <!-- include the jquery ui theme css and your own css -->
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/themes/smoothness/jquery-ui.css" />
        <link rel="stylesheet" href="css/style.css" />
 
    </head>
<body>
 
<!--
    -this is our text box, we didn't use type='text' but type='search' instead
     to have a clear (x) function in case a user wants to easily remove what's in the textbox
    -placeholder='Search firstname or lastname' - is an HTML5 attribute the can give your
     users a clue on what to search or type in the textbox
-->
<div>Try to type "dalisay" below:</div>
<input type='search' id='nameSearch' placeholder='Search firstname or lastname' />
 
<!--
    -now we'll include the jQuery and jQuery UI libraries
-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.0/jquery-ui.min.js"></script>
 
<script type="text/javascript">
$(document).ready(function(){
 
    // this is how to add autocomplete functionality in a textbox
    // source:'results.php' - where it will pass the search term and generates the JSON data
    // minLength:1 - how many characters user enters in order to start search
    $('#nameSearch').autocomplete({
 
        source:'results.php',
        minLength:1,
        select: function(event, ui){
 
            // just in case you want to see the ID
            var accountVal = ui.item.value;
            console.log(accountVal);
 
            // now set the label in the textbox
            var accountText = ui.item.label;
            $('#nameSearch').val(accountText);
 
            return false;
        },
        focus: function( event, ui ) {
            // this is to prevent showing an ID in the textbox instead of name
            // when the user tries to select using the up/down arrow of his keyboard
            $( "#nameSearch" ).val( ui.item.label );
            return false;
        },
 
   });
 
});
</script>
 
</body>
</html>

4.0 Getting Search Results

results.php – this is where the search term were passed, queries the database and generates the JSON data needed to show the autocomplete terms in the user interface.

<?php
// connect to the database
include "libs/db_connect.php";
 
// get the search term
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";
 
// write your query to search for data
$query = "SELECT 
            id, firstname, lastname 
        FROM 
            users 
        WHERE 
            firstname LIKE "%{$search_term}%" OR 
            lastname LIKE "%{$search_term}%"
        LIMIT 0,10";
 
$stmt = $con->prepare( $query );
$stmt->execute();
 
// get the number of records returned
$num = $stmt->rowCount();
 
if($num>0){ 
 
    // this array will become JSON later
    $data = array();
 
    // loop through the returned data
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
        extract($row);
 
        $data[] = array(
            'label' => $firstname . " " . $lastname,
            'value' => $id
        );
    }
 
    // convert the array to JSON
    echo json_encode($data);
 
}
 
//if no records found, display nothing
else{
    die();
}
?>

Wondering how the returned JSON data looks like?

[
  {
    "label": "Mike Dalisay",
    "value": "28"
  },
  {
    "label": "Darwin Dalisay",
    "value": "40"
  }
]

You can also take a look at your own JSON data by browsing your results.php?term=your_search_term

Adding Some Styles

style.css – this is where you can change the loading GIF image and add some style to our textbox.

.ui-autocomplete-loading {
    /* you can replace ajax-loader.gif with another gif image you want for your design */
    background: white url('images/ajax-loader.gif') right center no-repeat;
}
 
/* some style for our textbox */
#nameSearch{
    padding:.5em;
    width:20em;
}

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Congratulations! Now you can make your users happier by this search assistant feature, and as always, thanks for reading!

Google said “The web should be fast”: How to Optimize Your Website for Speed

Hey guys! Today we have a guest post about some tips on how to speed up your website! He's currently working for an e-commerce website and one of his tasks is to make the site load fast. So enjoy reading below! ~ Mike

Website speed becomes an obsession of search engines like Google and one of the reasons is the rapid growth of mobile internet browsing. If you're working with the https://www.igloosoftware.com/product/integrations/org_chart_now/ (developers, designers, bloggers and students), it is now a requirement to have knowledge in making a website load fast, and our post for today will give you some ideas on why and how to achieve it.

MUST READ NOTE FROM GOOGLE

"Speeding up websites is important — not just to site owners, but to all Internet users. Faster sites create happy users and we've seen in our internal studies that when a site responds slowly, visitors spend less time there. But faster sites don't just improve user experience; recent data shows that improving site speed also reduces operating costs. Like us, our users place a lot of value in speed — that's why we've decided to take site speed into account in our search rankings. We use a variety of sources to determine the speed of a site relative to other sites."

WEBSITE SPEED AND PERFORMACE

Pagespeed Insights - analyzes the content of a web page, then generates suggestions to make that page faster.


Pingdom Website Speed Test - one of the most reliable website speed tester, you can test the load time of your page, analyze it and find bottlenecks.

Yslow – is also a plugin that grades website and gives statistical information of your website performance.

GTmetrix – provides result right away and suggest necessary improvement for your website

Weboptimization - analyzes and gives detailed recommendations for site improvement as well as your web page speed report.

IMAGE OPTIMIZATION

Photoshop - when saving your photo choose the option "Save as for Web and Devices" (see Mike's post here for a more detailed instruction). Compare the result of your image to its original size; see also if the visual quality changed. In my example image, this is the result of my tests.

  1. JPG, 60 quality - 32K
  2. PNG-8, 256 colors - 37K
  3. GIF, 256 colors - 42K
  4. PNG-24 - 146K

Yahoo Smush.It - "drag or paste your photo urls". It is a "lossless" tool, which means it optimizes the images without changing their look or visual quality.

Image optimizer - is also a free tool and can compress image in bulk.Tip: Crop white spaces of images and other unnecessary pixels to reduce file size of your file.

COMPRESS YOUR HTML, CSS AND JAVASCRIPT

HTMLCompressor – is a small java library that minifies codes in html and xml by removing unnecessary characters and whitespaces without changing your codes.4.2JSCompress - copy paste your javascript code and compress it online to reduce 30% to 90% unneeded characters or comments.4.3Prettydiff – Minify, beautify and compare your code online. This tool is used by W3.org and Travelocity.

MinifyCSS – has css and javascript compression tool. It helps you clean and compress codes without manipulating or installing other applications. Copy paste and submit your code online then get the same result right away.Note: If you already use gzip, you don’t need to use some of the tools recommended above.

PERFORMANCE BEST PRACTICES

Scripts

Script position - always put your JavaScripts at the end of your HTML document, usually before the ending tag. What it does is it loads the more important content of your page (like images, text, etc.) before the scripts, and that makes your page load faster.

Use external CSS instead of inline CSS.Good practice:

<link type='text/css' rel='stylesheet' href='//www.yoursite.com/styles/main.css' />

Not recommended to include in your HTML document:

<style>
.myClass{
    padding:0 .5em;
    margin:1em;
}

#myId{
    padding:.5em;
    border:thin solid red;
}
style>

or

<div style='width:20em; border:thin solid #d1d1d1;'>Some div contents here.div>

Combine Rules and use it once in CSS.Use this sample as a guide:

h1 { color: blue; }
p { color: blue; }

Combined rule:

h1, p { color: blue; }

Validate your script at  W3.Org Validator

Cache - Cache your web pages. This is very important specially to an e-commerce website and those sites that have a lot of visitors daily.

Comment Box – If you guys use comment box system, please lazy load it so that it will load only when the user reaches the lower part of your page.

CDN (content distribution/delivery network)

Some may not be familiar with Google CDN but take a moment to learn and take advantage to use the Hosted Libraries.

Cloudflare - we used this in our ecommerce site and other sites for almost 3 years and so far, we are secured and it is free of charge but they also offer advance services with fee.

Use HTML5 codes that gives you a solution for faster page performance and integrationOur HTML5 sample:

<!DOCTYPE html>

Instead of:

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Note: Some tutorials for you to learn HTML5 are my favorite sites when I was starting w3schools and in advance learning html5 rocks tutorials. 

HOSTING SERVICES

Check your Hosting Services if they provide you the best hosting solution and better web performance. You can test their website using the above tools. Shared hosting are usually the worst, especially if your website has a lot of visitors, you should have a dedicated server.Thanks guys for reading my insights, I hope you get new techniques in improving your website speed or projects. Let’s help one another to become a better designer and developer.Feel free to comment and subscribe to our tutorials.

jQuery Tutorial for Beginners – Step By Step Guide!

jquery-step-by-step-tutorial-for-beginners

Previously, we learned how to use Bootstrap to make our web applications look good. This time, we will learn how to use jQuery.

Many of you asked me how to use jQuery. This tutorial is my answer to you. I want to give you links but I feel like it's easier to teach someone about something that is your own version of work! We hope you guys will find this step by step guide useful.

Getting Started with jQuery

What is jQuery? Okay here’s the simplest definition I can give. jQuery is a JavaScript library. It can:

  1. Make your JavaScript code shorter, faster and cross browser.
  2. Manipulate your HTML, like showing or hiding something from the page.
  3. Handles events – it can do something when a user click a button or any other activity a user can do with a mouse.
  4. Animation – for example make a part of your page fade in, fade out or just simply make something move.
  5. AJAX – do a server request without refreshing your whole web page.

This post. I assume you already know basic HTML, CSS and JavaScript. In this post, aside from the simple definition of jQuery above, we are just going to have two parts:

  1. The super straightforward, step by step tutorial or guide in running a very basic jQuery script. (2.0)
  2. We are going to take a look more of the jQuery basic concepts, as shown in #1 (3.0)

Run jQuery in 5 Easy Steps

Follow the steps below – these steps will lead you to run a very basic jQuery script that does a slide and toggle.

Create HTML page with its basic structure.

<!-- step 1 -->
<!DOCTYPE html>
<html>
<head>
    <title>jQuery Tutorial for Beginners</title>
</head>
<body>
 
</body>
</html>

Add element to be clicked. We’re gonna have a button in this example, we added an ID name to this button called myButton. Add the following code inside the "body" tag.

<!-- step 2 -->
<button id='myButton'>Click to Slide or Toggle</button>

Add the element to be shown or hidden. We’re gonna have a "p" tag with bunch of sample words inside. Add the following code below step 2′s code.

<!-- step 3 -->
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis. Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. Nulla metus metus, ullamcorper vel, tincidunt sed, euismod in, nibh. Quisque volutpat condimentum velit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam nec ante. Sed lacinia, urna non tincidunt mattis, tortor neque adipiscing diam, a cursus ipsum ante quis turpis. Nulla facilisi. Ut fringilla. Suspendisse potenti. Nunc feugiat mi a tellus consequat imperdiet. Vestibulum sapien. Proin quam. Etiam ultrices. Suspendisse in justo eu magna luctus suscipit. Sed lectus. Integer euismod lacus luctus magna. Quisque cursus, metus vitae pharetra auctor, sem massa mattis sem, at interdum magna augue eget diam. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi lacinia molestie dui. Praesent blandit dolor. Sed non quam. In vel mi sit amet augue congue elementum. Morbi in ipsum sit amet pede facilisis laoreet. Donec lacus nunc, viverra nec.
</p>

Add the jQuery library. Aren’t you excited? You can also download your own copy of jQuery but in today’s example, we’ll be linking to Google’s copy of jQuery. Add the following code below step 3′s code.

<!-- step 4 -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>

Step 5: Add jQuery script. This script will show or hide the "p" tag and the words inside it. Notice that we selected the button by referencing our button’s ID myButton.

<!-- step 5 -->
<script>
$("#myButton").click(function () {
    $("p").slideToggle("slow");
});
</script>

Download Source Codes

You can download all the code used in this tutorial for only $9.99 $5.55!

Congratulations! You are now a jQuery coder! Just kidding. Not yet. But don’t lose hope!

To achieve being a real jQuery coder, like any other skill, it must be practiced and be well versed with its concepts. So continue to read below and make your jQuery wisdom a little bit better.jQuery Basic Concepts

4.1 Run jQuery when DOM is ready. We didn’t implement this in our example above because I want to give you a quick look on how to run a jQuery script and it is a very small web page anyway.

But in reality, if you use jQuery in larger web pages, you have to run it when the DOM is ready. Here’s how:

$(document).ready(function() {
    // jQuery will run once everthing else in your web page is already loaded.
    // All your jQuery codes here.
});

How to Select an Element in jQuery? Learning jQuery selectors are very important because you’re dealing with HTML elements within your web page.

I’m gonna give you some of the most basic selectors being used:

// selects 'only one' HTML element with ID "myButton", such as our example above
// notice that we use hashes (#) for ids, like that of CSS
$("#myButton");
 
// selects all HTML elements with class "myClass", for instance: <div class='myClass'></div>
// notice that we used dots (.) for classes, like that of CSS
$(".myClass");
 
// selects all button HTML element, for example: <button>Click Me!</button>
$("button");
 
// selects all div element, example: <div>Me and all other div will be selected!</div>
$("div");
 
// selects all anchor link element, for example: <a href="https://codeofaninja.com/">Me and all other 'a' tags will be selected!</a>
$("a");

Learn more jQuery Selectors

jQuery Events. In our example above (2.0), we use a click event, in jQuery it was represented by the click() method. Here are some more jQuery events that you might find useful:

$("button").click(function(){
    // do something when user click the button
});
 
$("form").submit(function(){
    // do something when user submits a form
});
 
$("#myDiv").hover(function(){
    // do something when user hover an HTML element
});
 
$("#myTextbox").keyup(function(){
    // do something when user types on a textbox with ID myTextbox
});

Learn more jQuery Events

Animation Effects with jQuery. On our example above (2.0), the animation effect we used is the slideToggle(). Here are some other animations that you can do with jQuery:

// slide or toggle animation with a <p> tag
// you can change 'slow' to 'fast' or any number in milliseconds
$("p").slideToggle("slow");
 
$("p").slideToggle(1000, function() {  
    // do something when slide up or down animation is done
});
 
// hide the matched elements with a sliding motion.
$( "#book" ).slideUp( "slow", function() {
    // animation complete
});
 
// display or hide the matched elements by animating their opacity.
$( "#book" ).fadeToggle( "fast", function() {
    // animation complete
});

Learn more jQuery Animation Effect

Remember that the examples above are just some of the basics. Continue to practice, search and learn more in the process. And as always, thanks for reading!

5.0 Online Resources

6.0 What's Next?

Learn jQuery UI Tutorial for Beginners - Learn how to use date picker and other user interface interactions, effects, widgets, and themes built on top of the jQuery.

7.0 Related Tutorials

Please explore more tutorials on our start page. Click here.

8.0 Some Notes

Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

Subscribe to CodeOfaNinja

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

Thank You!

Thank you for learning with our jQuery Tutorial for Beginners! Please share this tutorial to one of your friends if you have time.

jQuery UI Tutorial for Beginners – Your Step by Step Guide!

jquery-ui-tutorial-for-beginners

Previously, we learned how to use jQuery to add some interactivity to our web pages. This time, are you getting started with jQuery UI? You've come to the right place!

This step by step tutorial aims to give you a head start in using jQuery UI. You probably know what jQuery is so you want to take a beautiful step forward with jQuery UI, and that's awesome!

jQuery UI jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library.

Whether you're building highly interactive web applications or you just need to add a date picker to a form control, jQuery UI is a perfect choice.

For me, Bootstrap and jQuery UI look good together. It also allows us to choose from different themes available, you can even create your own theme! But this post only covers running a very simple jQuery UI script in your web browser.

Run jQuery UI in 6 Easy Steps

The following steps below will make an awesome date picker with jQuery UI. Let's code!

Prepare your HTML file with just its basic structure.

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

Add a text box inside the tag. User will be able to click this and show a jQuery UI calendar picker later.

<input type="text" id="myDatepicker" placeholder="Click to pick date" />

Add the jQuery library before the ending tag. This is because jQuery UI is built on top of jQuery library.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

Add the jQuery UI library under the code of step 3. This is actually the first step in enabling jQuery UI in your page.

<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>

Add jQuery UI theme via CSS external link, put it inside the tag, after thetag. This CSS will make our UI stylish.

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />

Enable jQuery UI date picker to our text box on Step 1. Add the following code under the code of step 5. This is how you make a simple text box to an awesome jQuery UI date picker.

<script>
$( "#myDatepicker" ).datepicker();
</script>

Quick Tip: Always use the minified version. For instance, use jquery-ui.min.css instead of just jquery-ui.css

Continue to read below, you will see the complete code of the steps above.

jQuery UI Sample Codes

You will have to click the text box saying "Click to pick a date" to see jQuery UI with different themes in action.

By the way, examples 2.1 and 2.2 uses Google's content delivery network to run jQuery UI, meaning you won't have to download the jQuery and jQuery UI library, you just have to include it.


Query UI with Smoothness theme hosted in Google CDN.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - smoothness theme - by codeofaninja.com</title>
         
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.min.css" />
         
    </head>
<body>
 
<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />
 
<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- step 3 -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>
 
</body>
</html>

jQuery UI with Vader theme hosted by Google too.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - vader theme - by codeofaninja.com</title>
         
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/vader/jquery-ui.min.css" />
         
    </head>
<body>
 
<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />
 
<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- step 3 -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>
 
</body>
</html>

What if I don't want a CDN? I want to host my own jQuery UI library? No problem, you can always go to the jQuery UI download builder, you just have to select your preferred theme using the dropdown at the lower part of the page.

jquery ui download builder

jQuery UI library is self hosted in the example code below.

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Tutorial for Beginners - vader theme - by codeofaninja.com</title>
         
        <!-- step 4 - include you jquery ui theme -->
        <link rel="stylesheet" href="jquery-ui-1.10.3.custom/css/le-frog/jquery-ui-1.10.3.custom.min.css" />
         
    </head>
<body>
 
<!-- step 1 -->
<input type="text" id="myDatepicker" placeholder="Click to pick date" />
 
<!-- step 2 -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- step 3 -->
<script src="jquery-ui-1.10.3.custom/js/jquery-ui-1.10.3.custom.min.js"></script>
 
<script>
/* step 5 */
$( "#myDatepicker" ).datepicker();
</script>
 
</body>
</html>

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

Online Resources

Want to see more of jQuery UI? You can always visit:

What's Next?

Up Next: Learn PHP and MySQL CRUD Tutorial for Beginners - build a simple web application with PHP and MySQL database.

Related Tutorials

Please explore more tutorials on our start page. Click here.

Some Notes

Found An Issue?

If you found a problem with this code, please write a comment below. Please be descriptive about your issue. Please provide the error messages, screenshots (or screencast) and your test URL. Thanks!

Before you write a comment, remember to read this guide and our code of conduct.

Subscribe to CodeOfaNinja

We constantly improve CodeOfaNinja. We update our tutorials and source codes. Receive valuable web programming tutorials and updates to your email. Subscribe now!

Enjoy high-quality web programming tutorials.
Subscribe to CodeOfaNinja now for FREE!

Thank You!

Thanks for reading our jQuery UI tutorial for beginners!

jQuery UI Dialog Example with Source Code Downloads

Dialog boxes, modals, confirm boxes can also be done with awesomeness in jQuery UI.

In this post we are going to take a look at the three jQuery UI dialog code examples I commonly use in my projects.

Live demos and code download button links were also provided below. Keep on reading!

jquery ui dialog example

Our jQuery, jQuery UI and jQuery UI theme are hosted by Google. You can choose your jQuery UI theme here.

jQuery UI Basic Modal

I love modals, or a "modal window" or "modal dialog", it is a child window that pops up in your application that requires a user interaction. It can display information, gives you choices or even contain an HTML form!

In jQuery UI, when you set modal: true parameter, it will be able to dim the background of your page when showing the dialog. If it is set to false, the background will remain as is.

This is useful when a client (like mine) did not like dimming the background. But I like dimming the background when showing a dialog, so in our code below, we'll set the modal to true.

basic-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Modal Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />
 
<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -you can set the dialog title via the 'title' tag 
-->
<div id="basicModal" title="A message from codeofaninja.com">
    Thank you for visiting codeofaninja.com!
</div>
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* -select the div you want to be a dialog modal, in our case it is 'basicModal'
       -you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        height: 300,
        width: 400
    });
     
});
</script>
 
</body>
</html>

jQuery UI Confirm Dialog

Instead of the old JavaScript confirm dialog box, I use jQuery UI. This is for a better user interface and to control the number of buttons and their labels, instead of just "ok" and "cancel".

confirm-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Confirm Dialog Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show confirm dialog!' id='showDialog' />
 
<!-- 
    -this is the actual dialog, yes, it is included in your html body, it is just hidden
    -we did not set the dialog 'title' here, we set it in the js parameter
-->
<div id="basicModal">
    Go to codeofaninja.com?
</div>
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* select the div you want to be a dialog, in our case it is 'basicModal'
    you can add parameters such as width, height, title, etc. */
    $( "#basicModal" ).dialog({
        modal: true,
        title: "Are you sure?",
        buttons: {
            "YES": function() {
                window.open("https://codeofaninja.com/", '_blank');
            },
            "NO": function() {
                $( this ).dialog( "close" );
            }
        }
    });
     
});
</script>
 
</body>
</html>

jQuery UI Load Content from URL

URL to be loaded must be in the same domain or subdomain name. If you really want to load from different domain, use iframes, example code here.

In this example, we will use sample_page.php as the file of URL to be loaded, it has the following contents:

<?php
echo "Here's the sample page loaded.<br /><br />";
echo "Only a page from the same domain/subdomain can be loaded using this technique.<br /><br />";
echo "If you really want to load a page from another domain/subdomain, use an iframe.<br /><br />";
echo "<a href='http://stackoverflow.com/a/14570255/903298' target='_blank'>Example code here</a>";
?>

Save the loaded URL content

Here's is the default behaviour of the jQuery UI dialog, it appends the URL content to the HTML body.

load-url-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />
 
<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
 -->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* here you can specify the url */
    var url = "sample-page.php";
     
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
     
    console.log("url: " + url);
     
    /* show the image loader */
    $('#imgLoader').show();
     
    $.ajax({
        url: url,
        success: function( data ) {
         
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450
            }).dialog('open');
 
            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
     
});
</script>
 
</body>
</html>

To prove that the URL contents will be appended in the body of your HTML document, see the screenshot below, I used Google Chrome's inspect element to view this live source code of the current page.

jquery ui dialog not destroyed or removed

LIVE DEMO

Destroy or remove the loaded URL content

By default, the jQuery UI append the URL contents in your HTML body, if you want to prevent it, we can we add the close parameter on the dialog and use the jQuery remove() method.

load-url-destroy-dialog.html code:

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>jQuery UI Dialog Example by codeofaninja.com</title>
         
        <!-- include you jquery ui theme -->
        <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/smoothness/jquery-ui.css" />
         
        <!-- you can have your own style -->
        <style>
        body {
            font-family: "Trebuchet MS", "Helvetica", "Arial",  "Verdana", "sans-serif";
            font-size: .8em;;
        }
         
        /* dialog div must be hidden */
        #basicModal{
            display:none;
        }
         
        </style>
         
    </head>
<body>
 
<!-- sample content in your page -->
<div>You can click the button to show the basic jQuery UI dialog box.</div>
<input type='button' value='Show basic dialog!' id='showDialog' />
 
<!-- 
    -this time, we don't have the dialog html in the body, it is in another url
    -we use the image loader to add some good effect when the system loads the url (after user click)
-->
<img src="images/ajax-loader.gif" id="imgLoader" style="display:none;" />
 
<!-- include the jquery library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
 
<!-- include the jquery ui library -->
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
 
<script>
// show the dialog on click of a button
$( "#showDialog" ).click(function(){
 
    /* here you can specify the url */
    var url = "sample-page.php";
     
    /* container of the content loaded from a url */
    var tag = $("<div></div>");
     
    /* show the image loader */
    $('#imgLoader').show();
     
    $.ajax({
        url: url,
        success: function( data ) {
         
            tag.html(data).dialog({
                modal: true,
                title: "Content is loaded from a URL!",
                width: 600,
                height: 450,
                close: function(){
                     tag.dialog('destroy').remove()
                }
            }).dialog('open');
 
            /* hide the image loader */
            $('#imgLoader').hide();
            console.log("success!");
        }
    });
     
});
</script>
 
</body>
</html>

To prove that the URL content did not append in the HTML body, see the screenshot of the live source code below.

jquery ui dialog was destroyed and removed

Download Source Code

You can download all the code used in this tutorial for only $9.99 $5.55!

If you think of any other jQuery UI dialog example, please drop it in the comments section below, we'll try our best to add it in this post. Thanks!

Optimize Image for Web Using Photoshop and Thoughts on Faster Web Pages

This post is supposed to be a quick-tip on how you can optimize your images for web pages. But it feels like I also want to give some thoughts about website speed. There are many websites saying that your images must be optimized for the web, that should be updated and say, "your images must be optimized for web and mobile devices" in which the amazing Adobe Photoshop can help us with.

But before the tutorial and showing you the amazing results, I just want to give some thoughts on faster web pages. Optimizing your images can benefit, youyour users and search engines such as Google.

WEBSITE OWNER

I love fast loading web pages. Over a month ago, Alexa says this website's load time is around 4 to 6 seconds. That's horrible. So I decided to make this website load faster. Here are some of the things I've done to make it possible:

  1. I removed Infolinks ads to achieve speed in exchange for few bucks.
  2. I removed my Twitter and Google plus follow buttons.
  3. I removed Facebook like box, it loads images of Facebook users which is slow. The one you're seeing on the right sidebar is just an optimized image.
  4. I removed some jQuery plugins such as the "Recent Posts" plugin, the one you're seeing in the right sidebar is just a hard coded HTML.
  5. I limited "Related Posts" plugin to show just 5 items. Each item is a callback that makes a slow page load.
  6. I removed my stylesheet hosted in Google drive. Google drive HTML/CSS hosting is really slow.
  7. In short, lessen your HTTP requests.

Now a page from this site loads around 1 to 2 seconds. They say that it should be 1.5 seconds or less. But for now, the current speed is just okay for me. I'm still looking for ways to improve it, it's just I don't have much time for that yet.

YOUR VISITORS

You readers or website visitors also love your website to be fast even though you won't hear them saying it to your face. Everyone loves instant nowadays, instant noodles, instant result, etc. The same with web pages, users wants to read, or should I say scan, your content and get what's in your brain in an instant. One way to do this is making your web pages load fast.

GOOGLE

What you and your users love, Google love. If your visitors like their experience to your site, they might share it or link back to it. And Google can see it, which can give your website a chance to rank higher in search results. Currently, around 80% of this site's traffic comes from Google. Thank you Google!

HOW TO OPTIMIZE AN IMAGE FOR WEB AND DEVICES USING PHOTOSHOP?

Easy. Watch the video I made for you below

THE RESULT.

I chose to have a 'high' quality image. So from 80 kilobytes, it becomes 14 kilobytes.Here's the 80 kilobytes version:

...and now here's the 14 kilobytes version.

As for my eyes, it makes almost no difference aside from it's file size which is more than 4x smaller compared to the original. You can download the two images above and view their properties. Or you can do the few easy steps on the video above to see for yourself.I think this is a nice start for making your web pages load faster, and as always, thanks for reading!

jQuery AJAX Post Example with PHP and JSON

RELATED TUTORIAL: PHP, MySQL and AJAX CRUD Tutorial – Step by Step Guide!

Today I’m gonna give you some code examples on how you can post a form and JSON data using jQuery AJAX.

A PHP file will receive the posted data and print the response.

I think this is one of the most useful code when you’re coding with jQuery, especially if you’re building a web app with modules that deals with so many forms or post request in one page.

Why use jQuery for AJAX requests?

I think it is to make things easier, have shorter more readable code. You can see some code examples of doing an AJAX request without jQuery here and here.

As you can see on those links, some tasks include creating a catch for different browser XMLHttpRequest, opening the url, checking if the request is in ready state and setting the request header.

jQuery solves this by having a short, more readable syntax.

Let’s code!

Alright, now we’ll get straight to the code examples. We’re gonna have three example below, continue to read!

jQuery post form data using .ajax() method

This is a great way to show someone that you are now an AJAX programmer. Because of this .ajax() piece of code in your HTML page, you may now face the world with confidence and with a beautiful smile in your face.

Just kidding. But seriously, this piece of code is useful.

<html>
    <head>
        <title>jQuery post form data using .ajax() method by codeofaninja.com</title>
         
    </head>
<body>
 
<h1>jQuery post form data using .ajax() method</h1>
<div>Fill out and submit the form below to get response.</div>
 
<!-- our form -->  
<form id='userForm'>
    <div><input type='text' name='firstname' placeholder='Firstname' /></div>
    <div><input type='text' name='lastname' placeholder='Lastname' /></div>
    <div><input type='text' name='email' placeholder='Email' /></div>
    <div><input type='submit' value='Submit' /></div>
</form>
 
<!-- where the response will be displayed -->
<div id='response'></div>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){
     
        // show that something is loading
        $('#response').html("<b>Loading response...</b>");
         
        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.ajax({
            type: 'POST',
            url: 'post_receiver.php', 
            data: $(this).serialize()
        })
        .done(function(data){
             
            // show the response
            $('#response').html(data);
             
        })
        .fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;
 
    });
});
</script>
 
</body>
</html>

jQuery post form data using .post() method

.post() method has a more descriptive syntax, it is a shorthand of .ajax() method above. See how it was commonly used with the code below:

<html>
    <head>
        <title>jQuery post form data using .post() method by codeofaninja.com</title>
         
    </head>
<body>
 
<h1>jQuery post form data using .post() method</h1>
<div>Fill out and submit the form below to get response.</div>
 
<!-- our form -->  
<form id='userForm'>
    <div><input type='text' name='firstname' placeholder='Firstname' /></div>
    <div><input type='text' name='lastname' placeholder='Lastname' /></div>
    <div><input type='text' name='email' placeholder='Email' /></div>
    <div><input type='submit' value='Submit' /></div>
</form>
 
<!-- where the response will be displayed -->
<div id='response'></div>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
    $('#userForm').submit(function(){
     
        // show that something is loading
        $('#response').html("<b>Loading response...</b>");
         
        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.post('post_receiver.php', $(this).serialize(), function(data){
             
            // show the response
            $('#response').html(data);
             
        }).fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;
 
    });
});
</script>
 
</body>
</html>

jQuery post JSON data using .post() method

Sometimes you don’t want to post data from an HTML form. You can do it by creating a JSON string, and here’s how you’ll be able to post it.

<html>
    <head>
        <title>jQuery post JSON data using .post() method by codeofaninja.com</title>
         
    </head>
<body>
 
<h1>jQuery post JSON data using .post() method</h1>
<div>Click the button below to get response.</div>
 
<!-- our form -->  
<input type='button' value='Post JSON' id='postJson' />
 
<!-- where the response will be displayed -->
<div id='response'></div>
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js "></script>
<script>
$(document).ready(function(){
 
    $('#postJson').click(function(){
     
        // show that something is loading
        $('#response').html("<b>Loading response...</b>");
         
        /*
         * 'post_receiver.php' - where you will pass the form data
         * $(this).serialize() - to easily read form data
         * function(data){... - data contains the response from post_receiver.php
         */
        $.post('post_receiver.php', { user_id: "143", username: "ninjazhai", website: "https://codeofaninja.com/" }, function(data){
             
            // show the response
            $('#response').html(data);
             
        }).fail(function() {
         
            // just in case posting your form failed
            alert( "Posting failed." );
             
        });
 
        // to prevent refreshing the whole page page
        return false;
 
    });
});
</script>
 
</body>
</html>

Posting a JSON string using the .ajax() method is also possible, you can just replace the serialize() part with your JSON string.

Posted Data

Where did the posted data go? To the file where you want the posted data to be processed! But in our example, we just print the posted data. post_receiver.php has the following code

<?php
echo "<pre>";
    print_r($_POST);
echo "</pre>";
?>

Download Source Code
You can download all the code used in this tutorial for only $9.99 $5.55!

If you want to learn how to create, read, update and delete data with AJAX, go ahead and learn from our AJAX CRUD Tutorial Using jQuery, JSON and PHP – Step by Step Guide!.

Related Tutorials

Please explore more tutorials on our start page. Click here.

Thank you for learning our post about jQuery AJAX Post Example with PHP and JSON!

RELATED TUTORIAL: PHP, MySQL and AJAX CRUD Tutorial – Step by Step Guide!