Jquery and Java List example

Json + JqueryThere is no direct way to iterate over a Java List with jQuery, see the following case study : Spring controller @RequestMapping(value = “/”, method = RequestMethod.GET) public ModelAndView getPages() { List list = new ArrayList(); list.add(“List A”); list.add(“List B”); list.add(“List C”); list.add(“List D”); list.add(“List E”); ModelAndView model = new ModelAndView(“somepage”); model.addObject(“list”, list); return model; } JSP page, you can…

 

Upload Multiple Images with Jquery

In this post of Upload Multiple Images with Jquery code allows to user can select and upload multiple images in single shot, Quick look this live demo. Download Script     Live Demo Sample database design for Users. Users Contains user details username, password, email, profile_image and profile_image_small etc. CREATE TABLE `users` ( `user_id` int(11) AUTO_INCREMENT PRIMARY KEY, `username` varchar(255) UNIQUE KEY, `password` varchar(100), `email`…

Read More »

 

Auto Load More Data On Page Scroll using Jquery and PHP

This tutorial about my favorite place Dzone like data loading while page scrolling down with jQuery and PHP. We have lots of data but can not display all. This script helps you to display little data and make faster your website.
Load Data while Scrolling Page Down with jQuery and  PHP

Read More »

Hide and Seek with jQuery.

This tutorial about Hide and Seek with jQuery and PHP. This script helps you to present all modules in single page. Take a look at live demo click buttons

 


Download Script     Live Demo

Javascript Code

// <![CDATA[
javascript” src=”http://ajax.googleapis.com/ajax/
// ]]>
libs/jquery/1.3.0/jquery.min.js”>
<script type=”text/javascript”>
$(function()
{

$(“.button”).click(function()
{
var button_id = $(this).attr(“id”);

//Add Record button

if(button_id==”add”)
{
$(“#results”).slideUp(“slow”);
$(“#save_form”).slideDown(“slow”);
}

//Cancel button

else if(button_id==”cancel”)
{
$(“#save_form”).slideUp(“slow”);
$(“#results”).slideDown(“slow”);
}

// save button
else

{

// insert record
// more details Submit form with jQuery

}

return false;

});
});
</script>

HTML Code
Contains javascipt code. $(“.button”).click(function(){}- button is the class name of buttons(Add, Save and Cancel). Using $(this).attr(“id”) calling button id value.

<div id=”results” >

<a href=”#”color: blue;”>button” id=”add” >Add Record </a>
</div>

<div id=”save_form” style=”display:none” >

<a href=”#”color: blue;”>button” id=”save” >Save </a>
<a href=”#”color: blue;”>button” id=”cancel” >Cancel </a>
</div>

<div id=”update” >

</div>

Pagination with jQuery, MySQL and PHP.

I received lot of requests from my readers that asked to me how to implement Pagination with jQuery, PHP and MySQL. so I had developed a simple tutorial. It’s looks big but very simple script. Take a look at this live demo
Pagination with jQuery, MySQL and PHP.


The tutorial contains three PHP files and two js files includes jQuery plugin.

-config.php (Database Configuration)
-pagination.php
-pagination_data.php
-jquery.js
-jquery_pagination.js

Download Script     Live Preview

Database Table

CREATE TABLE messages
(
msg_id INT PRIMARY KEY AUTO_INCREMENT,
message TEXT
);
 

jquery_pagination.js
Contains javascript this script works like a data controller.

$(document).ready(function()
{

//Display Loading Image

function Display_Load()
{
$(“#loading”).fadeIn(900,0);
$(“#loading”).html(“<img src=”bigLoader.gif” />”);
}

//Hide Loading Image

function Hide_Load()
{
$(“#loading”).fadeOut(‘slow’);
};

//Default Starting Page Results

$(“#pagination li:first”)
.css({‘color’ : ‘#FF0084’}).css({‘border’ : ‘none’});
Display_Load();
$(“#content”).load(“pagination_data.php?page=1”, Hide_Load());

//Pagination Click

$(“#pagination li”).click(function(){
Display_Load();

//CSS Styles

$(“#pagination li”)
.css({‘border’ : ‘solid #dddddd 1px’})
.css({‘color’ : ‘#0063DC’});

$(this)
.css({‘color’ : ‘#FF0084’})
.css({‘border’ : ‘none’});

//Loading Data

var pageNum = this.id;
$(“#content”).load(“pagination_data.php?page=” + pageNum, Hide_Load());
});

});

config.php
You have to change hostname, username, password and databasename.

<!–?php

$mysql_hostname = “localhost”;
$mysql_user = “username”;
$mysql_password = “password”;
$mysql_database = “database”;
$bd = mysql_connect($mysql_hostname, $mysql_user, $mysql_password)
or die(“Opps some thing went wrong”);
mysql_select_db($mysql_database, $bd)
or die(“Opps some thing went wrong”);

?>

pagination.php
User interface page.

<?php

include(‘config.php’);
$per_page = 9;

//Calculating no of pages
$sql = “select * from messages”;
$result = mysql_query($sql);
$count = mysql_num_rows($result);
$pages = ceil($count/$per_page)

?>

// <![CDATA[
javascript” src=”http://ajax.googleapis.com/ajax/
// ]]>
libs/jquery/1.3.0/jquery.min.js”>
// <![CDATA[
javascript” src=”jquery_pagination.js”>
// ]]>

<div id=”loading” ></div>
<div id=”content” ></div>
<ul id=”pagination”>
<?php
//Pagination Numbers

for($i=1; $i<=$pages; $i++)
{
echo ‘<li id=”‘.$i.‘”>’.$i.‘</li>’;
}

?>
</ul>

pagination_data.php
Simple php script display data from the messages table.

<?php

include(‘config.php’);
$per_page = 9;
if($_GET)
{
$page=$_GET[‘page’];
}

$start = ($page-1)*$per_page;
$sql = “select * from messages order by msg_id limit $start,$per_page”;
$result = mysql_query($sql);

?>

<table width=”800px”>

<?php

while($row = mysql_fetch_array($result))
{
$msg_id=$row[‘msg_id’];
$message=$row[‘message’];

?>

<tr>
<td><?php echo $msg_id; ?></td>
<td><?php echo $message; ?></td>
</tr>

<?php

}

?>

</table>

CSS Code
CSS code for page numbers.

#loading

{
width: 100%;
position: absolute;
}

li

{
list-style: none;
float: left;
margin-right: 16px;
padding:5px;
border:solid 1px #dddddd;
color:#0063DC;
}

li:hover

{
color:#FF0084;
cursor: pointer;
}

Reference: 9lessons.info

Android Downloading File by Showing Progress Bar

English: A download symbol.

When our application does a task that takes a considerable amount of time, it is common sense to show the progress of the task to the user.
This is a good User Experience practice. In this tutorial i will be discussing the implementation of a process-progress dialog.

As an example, i am displaying a progress bar that runs while the app downloads an image from the web. And once the image is downloaded
completely i am showing the image in a image view. You could modify this example and try it with any file type you may wish. That could be fun!

Download Code

Creating new Project

1. Create a new project and fill all the details. File ⇒ New ⇒ Android Project
2. Open your main.xml are create a button to show download progress bar. Also define a ImageView to show downloaded image. Paste the following code in your main.xml

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <!-- Download Button -->
    <Button android:id="@+id/btnProgressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download File with Progress Bar"
        android:layout_marginTop="50dip"/>
    <!-- Image view to show image after downloading -->
    <ImageView android:id="@+id/my_image"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

3. Now in your main activity class import necessary classes and buttons. I am starting a new asynctask to download the file after clicking on show progress bar button.

public class AndroidDownloadFileByProgressBarActivity extends Activity {
    // button to show progress dialog
    Button btnShowProgress
    // Progress Dialog
    private ProgressDialog pDialog;
    // Progress dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0;
    // File url to download
    private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // show progress bar button
        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
        // Image view to show image after downloading
        my_image = (ImageView) findViewById(R.id.my_image);
        /**
         * Show Progress bar click event
         * */
        btnShowProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // starting new Async Task
                new DownloadFileFromURL().execute(file_url);
            }
        });
    }

4. Progress Dialog can be shown using ProgressDialog class. It is a subclass of normal AlertDialog class. So add an alert method in your main activity class.

/**
 * Showing Dialog
 * */
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type:
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

5. Now we need to add our Async Background thread to download file from url. In your main activity add a asynctask class and name it as DownloadFileFromURL(). After downloading image from the web i am reading the downloaded image from the sdcard and displaying in a imageview.

/**
 * Background Async Task to download file
 * */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }
    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();
            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            // Output stream to write file
            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                // writing data to file
                output.write(data, 0, count);
            }
            // flushing output
            output.flush();
            // closing streams
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }
    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
   }
    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissDialog(progress_bar_type);
        // Displaying downloaded image into image view
        // Reading image path from sdcard
        String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
        // setting downloaded into image view
        my_image.setImageDrawable(Drawable.createFromPath(imagePath));
    }
}

6. Open your AndroidManifest.xml file and add internet connect permission and writing to sdcard permission.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidDownloadFileByProgressBarActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <!-- Permission: Allow Connect to Internet -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Permission: Writing to SDCard -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

7. Run your Application and click on show progress bar button to see your progress bar. You can see the downloaded image in imageView once it is downloaded.

android download file and showing progress bar

Final Code

package com.example.androidhive;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class AndroidDownloadFileByProgressBarActivity extends Activity {
    // button to show progress dialog
    Button btnShowProgress;
    // Progress Dialog
    private ProgressDialog pDialog;
    ImageView my_image;
    // Progress dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0;
    // File url to download
    private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // show progress bar button
        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
        // Image view to show image after downloading
        my_image = (ImageView) findViewById(R.id.my_image);
        /**
         * Show Progress bar click event
         * */
        btnShowProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // starting new Async Task
                new DownloadFileFromURL().execute(file_url);
            }
        });
    }
    /**
     * Showing Dialog
     * */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }
    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }
        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // this will be useful so that you can show a tipical 0-100% progress bar
                int lenghtOfFile = conection.getContentLength();
                // download the file
                InputStream input = new BufferedInputStream(url.openStream(), 8192);
                // Output stream
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    // writing data to file
                    output.write(data, 0, count);
                }
                // flushing output
                output.flush();
                // closing streams
                output.close();
                input.close();
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;
        }
        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }
        /**
         * After completing background task
         * Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);
            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
            // setting downloaded into image view
            my_image.setImageDrawable(Drawable.createFromPath(imagePath));
        }
    }
}

jDigiClock

HTC Desire

Digital Clock (HTC Hero inspired)

Author: Radoslav Dimov
Version: 2.1 (Changelog)
Download: jdigiclock.zip
Licence: Dual licensed under the MIT and GPL licenses.

Contents

  1. Introduction
  2. Examples
  3. Getting started
  4. Configuration
  5. Compatibility

Introduction

jDigiClock is a jQuery plugin inspired from HTC Hero Clock Widget.

Example :DEMO

http://www.jqueryrain.com/?G7QuaYmH

Getting started

To use the jDigiClock plugin, include the jQuery library, the jDigiClock source file and jDigiClock core stylesheet file inside the <head> tag of your HTML document:

	css" href="css/jquery.jdigiclock.css" />

To setup jDigiClock, add the following code inside the <head> tag of your HTML document:

// <![CDATA[
    $(document).ready(function() {
        $('#digiclock').jdigiclock({
            // Configuration goes here
        });
    });
// ]]>

jDigiClock accepts a lot of configuration options, see chapter “Configuration” for further informations.

jDigiClock expects a very basic HTML markup structure inside your HTML document:

<div id="digiclock"></div>

Configuration

jDigiClock accepts a list of options to control the appearance and behaviour of the Digital Clock. Here is the list of options you may set:

Property Type Default Description
clockImagesPath string “images/clock/” Clock images path.
weatherImagesPath string “images/weather/” Weather images path.
am_pm boolean false Specifies the AM/PM option.
weatherLocationCode string “EUR|BG|BU002|BOURGAS” Weather location code (see: WeatherLocationDatabase.txt).
weatherMetric string “C” Specifies the weather metric mode: C or F.
weatherUpdate integer 0 Weather update in minutes.
proxyType string “php” Specifies proxy type: php or asp (see: README.txt).

Compatibility

jDigiClock has been tested and works on the following browsers:

  • Internet Explorer 7 (PC)
  • FireFox 3.5 (PC/Linux)
  • Google Chrome 3.0 (PC)
  • Safari 4.0 (PC)

JQuery Image Slider Plugin

JQueryNivo slider is a image slider with

  • 11 unique transition effects
  • Simple clean & valid markup
  • Loads of settings to tweak
  • Built in directional and control navigation….

Direct Link Demo

 jQuery & WordPress Image Video Slider

An easy-to-use Windows & Mac app for creating beautiful, professional, responsive jQuery Slider, YouTube Video Slider, WordPress Slider Plugin and Joomla Slideshow Module.Amazing Slider comes with awesome transition effects: Fade, Cross Fade, Slide, Slice, Blinds, 3D, 3D Horizontal, Blocks and Shuffle. Each effect can be further customised to meet your own needs. The pre-made and highly configurable skins can give your slider a professional and unique looking.

Direct Link Demo

Most complete responsive jQuery/WordPress Slider

jQuery Slider Shock. A fully responsive slider and the most complete over the web right now. Available for you to download it as a jQuery code to use it wherever you need, or as a plugin for the most used CMS: WordPress. We wanted to make something that could take advantage of all the power that the jQuery code has to offer and this is the result. Take a look into this post and the features that our slider has to offer.
Do you want to build your own Slider? Sure, you can do it!. Look at the controls available to do so.

Features:

  • You can easily add thumbnails on any of the sides of the slider ( top, bottom, left, right ) allowing users to navigate easily between slides.
  • jQuery Slider Shock supports not only images but also allows you to show Videos from YouTube playlists, RSS Feeds, Twitter Feeds, Flickr and Instagram images from an account.
  • You can create an slider from each of the following sources: Custom Slides, Posts (WordPress), Custom Post Types (WP), Taxonomies (WP), External RSS, YouTube, Flickr, Twitter and Instagram.
  • Add videos from YouTube, Vimeo or Hulu.
  • Create a unique slider adding not only videos or only images, but both of them between slides.
  • You can have as many sliders as you want in the a single page.
  • Add a flat color or a pattern based background the captions in the slides.
  • You can adjust both the position and width of the slider captions.
  • You can also include external URL images. By doing that, you can add completely different background patterns to your slider.
  • You can choose a fixed width for your images, or adjust them to the 100% of its parent width..
  • Add image descriptions within the thumbnail labels and display them on top, bottom, left or right side of your slider.
  • Like the images, the labels can have their own background.
  • You can adjust both the position and width of your captions.
  • Pick one from 31 available effects (premium) or let them be random.
  • Responsiveness can be deactivated, allowing your slider to remain the same disregarding the screen size.
  • You choose the skin that fits on your site the best from 39 skins.

Direct Link Demo

 

Simple Tutorial to Make a Chrome Extension that uses jQuery UI

20756_Free Shipping Plus VIP Exclusive Perks & Savings with code: CX13J027

English: The text "jQuery" in the of...

Google Chrome has had extensions for a while now, but because the Linux client is a little farther behind I never got farther than the simple hello world tutorial. Today, however, I am pleased to announce that Chrome extensions are totally boss, and it is extremely easy to get a jQuery UI skinned template app going in 15 minutes, just by following three easy steps.

Step 1 – Brushing up on the Hello World Extension Tutorial

Follow the Getting Started (Hello World) tutorial. The tutorial is very well written and will help you get your bearings about what extensions can do and the minimum you need to get started. A key part is the manifest.json

CrashPlan for Business

{
  "name": "My First Extension",
  "version": "1.0",
  "description": "The first extension that I made.",
  "browser_action": {
    "default_icon": "icon.png"
  },
  "permissions": [
    "http://api.flickr.com/"
  ]
}

The name, version, and description fields are all self explanatory. The browser action one is interesting. It means that your extension will add a button to the browser (right after the address bar) with the specified icon. So far as I can tell the only thing that the button can do now is display a popup, though this popup can communicate with other parts of your extension. Permissions are also important, they specify what domains you can access via xmlhttprequests.

At this point you should have a working hello world tutorial, if not please continue to follow the rest of the directions on the full tutorial page, I’ll wait.

Step 2 jQuerying it up

After you finish the tutorial you may come to feel that raw JS is pretty harsh stuff and it would be great to get a little jQuery action in there. No need to fear, just add this to your “popup.html” file:

// <![CDATA[
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js" type="text/javascript">
// ]]>

You don’t even need to add a file anywhere in your extension. Neat! Now you can rewrite the part of the tutorial that connects to the Flickr API like so:

$.get("http://api.flickr.com/services/rest/", {
    method: "flickr.photos.search",
    api_key: "90485e931f687a9b9c2a66bf58a3861a",
    text: "hello world",
    safe_search: 1,
    content_type: 1,
    sort: "relevance",
    per_page: 20
  }, function(data, status, request) {
    var photos = request.responseXML.getElementsByTagName("photo");    for (var i = 0, photo; photo = photos[i]; i++) {
      var img = document.createElement("image");
      img.src = constructImageURL(photo);
      document.body.appendChild(img);
    }
  }
);

Love that fresh jQuery scent. Note that I left the constructImageURL function unchanged, so you’ll still need it if you want the extension to continue working.

Step 3 Adding jQuery UI (It’s Easy!)

This is the easy part. Go to the jQuery UI custom build your own download. Keep all the UI stuff checked and choose your favorite theme, you’ll have plenty of time later to choose exactly what you want or need, but for now just focus on seeing how easy it is to integrate. Now download the zip and extract in into your extensions root directory.

You can go to chrome-extension://extensionId/index.html and see all the magic of the jQuery UI demo, but working from inside a Chrome Extension. Of course extensionId is whatever that giant random string of characters that Chrome assigned to your extension was, something like opnnhifacfpohionnikhlecfgheooenk. (Learn more here)

Congratulations!

Although getting a simple skeleton/hello world extension up only takes a short amount of time, learning about all the possibilities and actually making an extension that does great things will take much longer. I hope that with this tutorial that starting will be very easy and nothing will stand in the way of your dreams.

Peace!