Showing posts with label Jquery. Show all posts
Showing posts with label Jquery. Show all posts

How to Guide to Create ​Mobile ​Responsive ​Design


Introduction:

Hey Guys! Last article was about "How to Install Ubuntu 15.04 Along With Windows 8 (Dual Boot)".

Unlike a conventional desktop oriented website, the one which has been created for the mobile screens is a lot more in demand. It is a responsive website which automatically adjusts itself to fit the screen of device that the site is being viewed on. All the content, whether it is the text, images or video get moderated to ensure best display on the screen under focus. Whether you're a publisher, a designer or a developer, taking care of your site's mobile responsive design is something that can render flawless experience to the targeted users. In this post, I'll be walking you through the vital steps that must be followed for building a fine quality mobile responsive design.

What kind of mobile responsive design are we going to create in this tutorial?

Here, I'll be creating a simple e-commerce product detail page for a t-shirt firm. So, while ensuring that the customers are able to make the purchases conveniently, we'll also be making the product review easy-to-access, followed by utilizing customer's location for enhancing the overall mobile shopping experience.

A look at the basic structure

It is essential to author a semantic HTML5 markup that will allow you to ensure completely manageable and fully accessible adaptive experiences. The reason for this being that semantic markup is fully portable and can be easily accessed on a variety of mobile devices, desktop browsers, tablets etc.

Coming to the individual steps for creating mobile responsive design

Step 1- Set the Viewport

While for a majority of non-mobile-optimized websites, most of the contemporary browsers set up a larger browser viewport, in case of designing a website using mobile responsive design, we'll be using viewport meta tag for setting the screen width to the device width as shown below:


<meta name="viewport" content="width=device-width, initial-scale=1" />

Step 2- Adding the flexibility to load the website content conditionally

Here, we'll be creating two new HTML documents for the auxiliary content viz: reviews.html and related.html. Unlike the default way in which the content is accessible via links available on the page, we can use a little bit of javascript for loading the content as and when user requests for the same or when the screen's resolution reaches a specific breakpoint.

Step 3- Use HTML special characters

As an attempt to decrease the need for background images, it is recommended to use HTML special characters. In this tutorial, I've used $#9733 for creating a solid star (★) and ☆ for creating empty stars (☆) for the product ratings.

Step 4- Include a clickable link within footer

Here, we'll use the tel URI scheme for including a clickable link to customer service number, within the footer. Here's a look at the tel URI scheme:


<a href="tel:1234567891">123 456 7891</a>

Step 5- Add style enhancements

With a strong semantic markup in place, it's time to add some style enhancements as explained below:

Create separate style sheet for screens with larger displays

Here, we'll be creating two CSS files viz: style.css and enhanced.css for delivering basic styles for screens with dimension less than 967px. We'll be using media queries for serving the new styles for screens with dimension greater than 967px as shown below:


<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<link rel="stylesheet" href="style-967.css" type="text/css" media="screen  and (min-width: 967px)" />
<!--[if (lt IE 9)&(!IEMobile)]>
<link rel="stylesheet" href="ie9.css" type="text/css" />
<![endif]-->

Adding Mobile-first styles

Next, we can start off with adding shared styles and advanced layout rules as shown below:



/* Avoid this style */
.customer-list img {
  width: 30%;
  float: left;
}
@media screen and (max-width: 967px) {
  .customer-list img{
    width: auto;
    float: none;
  }
}


The mobile-first approach will now look like this:



@media screen and (min-width: 967px) {
.customer-list img {
    width: 30%;
    float: left;
  }
}


Next, we'll be applying media queries as shown in the below code snippet:


/*Display 2 per row for medium displays*/
@media screen and (min-width: 480px) {
  . customer-list li {
    width: 50%;
    float: left;
  }
}
/*Display 3 to a row for large displays*/
@media screen and min-width: 768px) {
  . customer-list li {
    width: 33.33%;
    float: left;
  }
}



Step 6- Use CSS for reducing HTTP requests

Have a look at the below CSS which will play a vital role in saving HTTP requests so as to improve the overall performance of your website. For instance, CSS gradients can replace background images for decreasing the count of image requests and rendering a greater control over the original design.



/*Using CSS gradients rather than background images*/
header {
  background: #333; 
  background: +linear-gradient (top, # 333 0%, #555 100%);
}


Step 7- Add Javascript enhancements

To start off, we'll be adding functionality to the site's navigation. In the HTML5 Markup, we'll using a list #top-menu for toggling the visibility of navigation as well as the search bar on all small screens. Have a look at this:


<ul  id="top-menu" class="top-menu">
  <li><a href="#">Menu</a></li>
  <li><a href="#">Search</a></li>
</ul>
<nav id="main-menu" class=" main-menu">
  <ul role="main-menu">
    <li><a href="#">Home</a></li>
    <li><a href="#">About</a></li>
    <li><a href="#">Services</a></li>
  </ul>
</nav>


Additionally, we will include a resize listener which will find whether there's any possibility of displaying the search bar and navigation. Have a look at this:



var swidth, sheight ;
$(window).resize(function(){
  swidth = document.documentElement.clientWidth;
  sheight = document.documentElement.clientHeight;
  setElements();
});
  
//Set elements according to differ screen size
function setElements() {
  device = (swidth < breakpoint) ? true : false;
  if (!device) { 
    $('#top-menu').show(); 
  } else {
      $('#top-menu').hide();
  }
}


Adding functionality to the Image Gallery

To start off, we'll be adding functionality to the site's navigation. In the HTML5 Markup, we'll using a list #top-menu for toggling the visibility of navigation as well as the search bar on all small screens. Have a look at this:

Have a look at the below code snippet which will allow us to build an image carousel using the available thumbnail images:



function intslide() {
  container.html('<div id="img-slider"><ul /></div>');
  imgSlider = $('#img-slider');
  $('nav a:first-child').addClass('active');
  
  $('nav a').each(function() {
    var href = $(this).attr('href');
    imglist += '<li data-src="'+href+'"></li>';
  });
  
  imgSlider.find('ul').append(imglist);
      
  $('nav a').on('click', function(e) {
    var slidepos = $(this).parent().index();
    e.preventDefault();
    loadImg(slidepos);
    if(swipeEnabled) {
      mySwipe.slide(index, 500);
    }
    updateNav(slidepos);
  });
}



Adding functionality for Related Content

A code snippet will allow us to pull in related content in case any one of the below two conditions are met:

 When a mobile user clicks on related t-shirts or the product reviews links

 When screen has enough space for loading the auxiliary content

The code snippet that I'm referring to is shown below:



function setElements() {
    device = (swidth < breakpoint) ? true : false;
  
  if (!device) {
    loadContent(); 
  }
}

//Set up content
function loadContent() {
  var $content = $('.content');
  $content.each(function(index) {
    var $this = $(this);
    var contentLink = $this.find('a');
    var contentFragment = contentLink.attr('href');
    var realContent = $this.find('.demo');
    if (realContent .size()===0 && $this.hasClass('loaded')===false) {
      getContent(contentFragment,$this);
    }
  });
}

function getContent(src,container) {
  container.addClass('showcontent');
  $('<div class=”demo” />').load(src +' #content > div',function() {
    $(this).appendTo(container);
  });
}


As an approach to keep the web pages lightweight, I recommend using Closure Compiler for chopping off all the unused bits of the jQuery library. Other impressive alternatives include popular micro-frameworks like Zepto.js etc. Finally, don't forget to pay special attention to ensuring seamless off line access to your website. This will serve as a brilliant surprise to mobile users who aren't connected to the Internet at times.

We're done!

Conclusion:

With that it's a wrap on this post which made you familiar with the basic steps of creating a mobile responsive design. Hope by having a responsive design, it will become convenient for you to adapt to all the future mobile devices and browsers quite conveniently and instantly.

Author Biography:

Samuel Dawson is a comprehensive expert in Designs2HTML Ltd involved in the process of to convert HTML to Wordpress in a top manner.

Facebook style profile picture upload using PHP + JQuery +Ajax Part1


Introduction:

Hello Friends! 

In the last article we talked about “How to build Facebook style Autocomplete using Angular JS, Cygnite PHP, Mysql and Bootstrap template” . Recently I received a request from one of my reader that “How to build Facebook style profile photo upload, creating thumbnail and save into server ?”. I will write the same here today. You might have notice in many social network site, in profile page when you mouseover in your photo "Update Picture" or "Upload Photo" displays. It's looks cool, as it is not displaying such old type of file upload html element. In this post I will not be able to cover whole tutorial. So I decided to divide the post into part. In this tutorial I will tell you the best way to make "Facebook style profile photo upload using PHP, JQuery and Ajax."

To build this app, I am using Cygnite PHP Framework, JQuery, Ajax, Bootstrap template etc. Using framework make my job easier (Since bootstrap theme, inbuilt libraries, MVC, Widget etc), well structured, also gives flexibility to maintain code. If you don't wish use entire framework you can also use Cygnite File Component to do the same.

Installing Composer and Cygnite Framework:

So the first step is to install Cygnite framework to build our application, I am not going to write "How to install Cygnite PHP Framework", as it has covered in my previous article. Below links for Installation of Cygnite Framework but Cygnite v1.2.4 doesn't include File Upload feature, so please update composer.json to download latest framework code (dev-master) or manually update the framework core.

Cygnite Framework- Composer Installation

Manual Download from GITHUB

  Live Demo   Download

Step 1:
Let me consider you have already Cygnite installed into your machine. I have installed it into /www/cygnite/ directory. Now create a controller called ProfileController.php into your /cygnite/apps/controllers/ProfileController.php.

We will render the default view page using indexAction. We are not using layout here, but you can also use layout to make your view page much modular, flexible. Paste below code into your controller to call your view page.

 


namespace Apps\Controllers;

use Cygnite\Foundation\Application;
use Cygnite\Mvc\Controller\AbstractBaseController;
use Apps\Models\Country;
use Cygnite\Common\File\Upload\Upload;
use Cygnite\Common\UrlManager\Url;
use Cygnite\FormBuilder\Form;

class ProfileController extends AbstractBaseController
{
   protected $templateEngine = false;

   //Plain PHP layout
   //protected $layout = 'layout.base';
  /*
   * Your constructor.
   * @access public
   *
   */
   public function __construct()
   {
      parent::__construct();
   }

  /**
   * Default method for your controller. Render welcome page to user
   * @access public
   *
   */
  public function indexAction()
  { 
     $this->render('index');
  }


   // Upload profile picture
  public function uploadAction()
  {
    $status = Upload::process(function($upload)
    {
        $upload->file = 'document'; // Your file input element name
        $upload->ext = array("JPG", "PNG"); // Add validation for image upload
        //$upload->size = '6144';// limit the size

        if  (isset($_FILES['document'])) {

            if ($upload->save(array("destination"=> "upload",  "fileName"=>"user_profile_".time()))) {

                $response= array('status' => true, 'msg' => 'Uploaded Successfully!' );
            } else {
                $response = array('status' => false, 'msg' => implode(', \n', $upload->getError()) );
            }

            header('Content-type: application/json');
            return  json_encode($response);

        }
    });

    echo $status ;
  }
}


Step 2:
When you create a new controller you also need to create a folder into views/ as same name as controller but lowercase inside /cygnite/apps/views/ directory. I am creating my view page called index.view.php inside /apps/views/profile/index.view.php and paste below code to render our profile default image.



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

<div class="col-sm-9">
    <form enctype="multipart/form-data">
        <div id="profile">
         <a href="javascript:void(0);">
             <img src="<?php echo Url::getBase(); ?>/assets/img/no_image.jpg" class="profile-image"  id="profileImg"/>
               <span id="uploadTrigger"><b>Update Picture</b></span>
               <input name="document"  type="file"  id="file-id" class="active"/>
             </a>
        </div>
        <div style="top:2px;"> </div>
        <div id="status_msg"> </div>
    </form>

</div>

Step 3:
Create a js file called profile.js into cygnite/assets/js/profile.js and paste below code. Cygnite is shipped with bootstrap so you can use it or use cdn link.



$(document).ready(function () {

    $("#uploadTrigger").on('click', function(event) {
        $("#file-id").trigger('click');
    });

//$('.hidden').removeClass('hidden').addClass( 'active');

$(":file").change(function() {

    var file = this.files[0],  name = file.name, size = file.size, type = file.type;
    //Your validation
    var imageType = new Array("image/png","image/jpeg", "image/gif", "image/bmp");

    if(jQuery.inArray(type, imageType )  == -1) {
        $("#status_msg").html("Valid file formats are: jpg, jpeg,png, gif").css('color', '#F00000');
        return false;
    }  else {

        $("#status_msg").html(" ");
        if ($("#file-id").val() !== '') {
            var formData = new FormData($('form')[0]);

            $.ajax({
                url: 'upload',  //Server script to process data
                type: 'POST',
                //Ajax events
                beforeSend: function () {
                    $('#profileImg').addClass( 'profile-image-loading')
                                    .removeClass('profile-image')
                                    .attr('src', '/assets/img/fb_loading.gif');
                },
                success: function (data) {

                    if (data.status) {
                        var reader = new FileReader();
                        reader.onload = function (e) {

                        $('.profile-image-loading')
                            .addClass('profile-image')
                            .removeClass('profile-image-loading')
                            .attr('src', e.target.result);
                           return false;
                        }
                        reader.readAsDataURL(file);

                        $("#status_msg").html(data['msg']).css('color', '#009900');
                    } else {
                        $("#status_msg").html(data['msg']).css('color', '#F00000');
                        return false;
                    }
                },
                // Form data
                data: formData,
                //Options to tell jQuery not to process data or worry about content-type.
                cache: false,
                contentType: false,
                processData: false
            });
        } else {
        alert("Please select valid image.");
        return false;
        }
        }

});

});


Using Standalone Cygnie File Component for File Upload:

If you have already built an application and willing to use only standalone file component you can simply install Cygnite/File component using composer. I have installed composer globally in my system.

Create a composer.json file into your root directory where you want to install component, paste below code and save it.


{
  "require": {
    "php": ">=5.4.0",
    "cygnite/file" : "dev-master"  
  },
  "autoload": {
    "psr-0": {
        "Cygnite\\Common\\File": "cygnite/file/"
     }
   }
}


Now open terminal/command prompt, change to your project directory where composer.json exists and issue below command to install File Upload Component to do the same stuff.



composer install 


I am creating index.php file to access Cygnite File component, and below code to access File Upload feature.




require 'vendor/autoload.php';

use Cygnite\Common\File\Upload\Upload;

$upload = new Upload();

//$upload->setUploadSize(62092);
$upload->file = 'document';
$upload->ext = array("JPG");
$upload->size = '1024';

if(isset($_FILES['document'])) {

    if ( $upload->save(array("destination"=> "upload", /* "fileName"=>"demo_icon","multiUpload"=>true*/)) ) {
        $response = json_encode(array('status' => true, 'msg' => 'Uploaded Successfully!' ));
    }  else {
        $response = json_encode(array('status' => false, 'msg' => $upload->getError() ));
    }

    echo header('Content-type: application/json') .$response;exit;
}


Or you can also use Closure beautiful syntax as below.



require 'vendor/autoload.php';

use Cygnite\Common\File\Upload\Upload;

function fileUpload()
{
    $status = Upload::process( function($upload)   {
        $upload->file = 'document';
        $upload->ext = array("JPG");
        $upload->size = '5000000';

        if  (isset($_FILES['document'])) {

            if ( $upload->save(array("destination"=> "upload",  "fileName"=>"demo_".time(),/*"multiUpload"=>true*/)) ) {
                $response= array('status' => true, 'msg' => 'Uploaded Successfully!' );
            }  else {
                $response = array('status' => false, 'msg' => implode(', \n', $upload->getError()) );
            }

            header('Content-type: application/json');
            return  json_encode($response);
        }
    });

    echo $status ;
}


Now you can call the fileUpload function as usual in core php and calling this method in ajax url will process your ajax file upload. Don't forget to Include all above necessary css and jquery files in order to make the app work.

Finally go to browser and call the application by issuing below url.



http://localhost/cygnite/index.php/profile/


Conclusion:

We sincerely hope you found this article helpful. In my next article (Part2) I will explain “How to create a thumbnail image / How to crop image using PHP?”. If you have specific topic in mind which you want me to discuss you may request tutorial.  Please don’t forget to share this article with friends or leave your comments below.

Keep visiting for upcoming posts. Have a nice day. :)

Facebook style wall posting using Cygnite PHP Framework, Jquery, Ajax


Introduction:

The last article was about “Reading and importing CSV file into database using PHP” . Today I have interesting thing for you guys. Are you looking for social script as facebook comment posting with MVC architecture? Which contains share thoughts on wall, comment posting, delete using jquery, load more, ajax, you want to share Facebook like video. You may get many script from different sites but mostly paid and not modular MVC architecture and you will end up restructuring into MVC. So I thought to share with you the application where you will find all these features and many more on coming days. Also you can find the script hosted on GITHUB.

Step 1:

Download and extract (wallscript-master.zip) the code from GITHUB. Rename wallscript-master to wallscript.

Step 2:

Configure your database name into /wallscript/apps/configs/database.php. I have configured database: “tutorials” localhost with empty password, you can change if you have different.

Step 3:

Find the demo sql script inside /wallscript/apps/database/wallscript.sql. Run the sql file into your database using phpmyadmin or Mysql Workbench.

Step 4:

That's all. You are done. Now go to your browser and type url : http://localhost/wallscript/ You can see the screen as below.


Extract video from url:



 

Conclusion:

Hope this small application is useful. You may alter the script to build much more features like Facebook or any other social network. 

If you are finding this tutorial helpful, please don't forget to share with friends, also leave your comments below. Have a nice day. Keep visiting for interesting articles.


Auto reload page content every 3 sec using JQuery, Ajax & PHP


Hello Friends!

Did you read my last blog “How to auto resize textarea based on the user input?”

If you have noticed that the Facebook/Twitter social networking sites repetitively search for new comments/tweets to display to the end user. It is pretty simple concept, which we can achieve using a simple script. It is approx. 10 lines of code. 

I thought this may be helpful for newbie and here I am going to write about "How to auto reload partial page and display number of tweets" with very few steps.

Step 1:

Create a index.php file and paste below code into it. Don't forget to include Jquery and Ajax framework in your page.


  
  
  $(document).ready(function(){ 
   var auto= $('#tweets'), refreshed_content;	
       refreshed_content = setInterval(function(){
        auto.fadeOut('slow')
            .load("result.php?id=123").fadeIn("slow");
            }, 3000); 										
    console.log(refreshed_content);										 
    return false; 
  });
  

Above script will call result.php page on every 3 seconds and fetch the number of tweet count. Replace id=123 with logged in user id. Next we are going to place a div where tweets count will get displayed. 


<div class=”container”>
<div id="tweets"> </div> 
</div>

Now let us create result.php to perform twitter live search and return the tweet count to the user. Copy  below piece of code and paste it into result.php to perform live database search. Here user_id is referred to the logged in user id to search against the database.


$userid = (string) (isset($_GET['id'])) ? $_GET['id'] : '';

$link = mysql_connect("localhost", "root", "");
mysql_select_db("twitter", $link);
$sql = "Select * FROM user_tweets where user_id = '$userId' ";
$result = mysql_query($sql, $link);
$num_rows = mysql_num_rows($result);

echo "Total $num_rows new Tweets ";exit;


That’s it. We are done. 

This small script will automatically fetch the number of tweets on regular interval and display to end user. You may modified this script accordingly to create a live notification system. 

Hope it will be helpful. Please do not forget to leave your comment below & share with friends.



How to populate a select box using jQuery ajax json, php?





Hello Friends! With the help of Ajax and PHP you can easily populate a select box without refreshing the page. You can also do it using only PHP script but requires you to refresh the page every time you change the select box value. Here is a very simple and useful example how you can populate a select box without refreshing page.

Prerequisites

1. Latest version of JQuery.

2. Very basis understanding of JSON.

3. A server side scripting knowledge to respond to Ajax request. In this tutorial I am going to use PHP as a scripting language.

Code:

There are 4 parts in this DEMO.

HTML page

The JQuery & Ajax (Client side code)

JSON structure

Server side code to populate dynamic page.

HTML:


  <select id="category">

      <option value=""> Select Job Type</option>

      <option value="1">Technical </option>

      <option value="2"> QA </option>

  </select>

 <select id="sub-category">

      <option value=""> Select Area Lead</option>

  </select>


JQUERY & AJAX REQUEST:

Include latest version of Jquery in your HTML page. Below ajax script will call server side script to get JSON data and populate select box. Add below script in your page.

 


$(function(){ 
    $('#category').change(function() {
        
        $.ajax({
            type: "POST",
            url: 'https://appsntechinfo.com/demo/list_ajax',
            data: {'categoryID': $(this).val(),'isAjax':true},
            dataType:'json',
            success: function(data) {

               var select = $("#sub-category"), options = '';
               select.empty();

               for(var i=0;i<data.length; i++) {
                 options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";              
               }

               select.append(options);
            }
        });
    });
});


And now in your server side page you may write below to fetch data from database.

SERVER SIDE SCRIPT:

We will first validate the category id and fetch data from database then return JSON response to UI.

 

if (isset($_POST['categoryID'])) {

    $id = trim($_POST['categoryID']);
    $result = array();
    $id = mysql_real_escape_string($id);
    $res = mysql_query("SELECT * FROM sub_categories WHERE category_id = $id");
    while ($row = mysql_fetch_array($res)) {

    $result[] = array(
      'id' => $row['subcatid'],
      'name' => $row['description']
    );

    }

    echo json_encode($result);
}

SAMPLE JSON:

 

[
  {"id":10, "name": "Anderson"},
  {"id":11, "name": "Shane"},
  {"id":12, "name": "Shelly"}
]

Follow Us On Facebook Open Source Web Developers by Appsntech facebook group Twitter Open Source Web Developers by Appsntech twitter group Google+ Open Source Web Developers by Appsntech Google group Linkedin Open Source Web Developers by Appsntech, LinkedIn group
Copyright @2011-2015 appsntech.com. All rights reserved.