Showing posts with label php. Show all posts
Showing posts with label php. Show all posts

Tuesday, November 10, 2015

MCQ test application in php


First of all Thank you very very much For your love and support we have reached 1k Like on FB PAGE so on this occasion i am releasing my new project “TestiFY” an online MCQ test application in php. This MCQ test application has good amount of feature. For this MCQ test application i have used Dirty PHP so that it will be easy for me to explain stuff to you guyz.
Live Demo Download Script

Friday, May 9, 2014

Multiple File upload with Ajax

Sry Guyz for the late post. I was out of station thats why and my gf my computer was not with me but now I Am Back. In this post we i will show how to create a awsm Multiple File upload with percentage and results with ajax. So get Started.

Live Demo Watch Video Tutorial Download Script

html

markup for this is very simple we are just using a <form> with <input type="file"> and Submit button and we have give the multiple attribute to the file so that the user can select multiple file. We have created 3 empty div for putting result via javascript
<form action="upload.php" method="post" enctype="multipart/form-data">
 <fieldset>
  <legend>File upload</legend>
  <input type="file" name="file[]" id="file" multiple required/>
  <input type="submit" name="upload" id="upload"/>

  <div id="per"></div>
  <div id="sucess"></div>
  <div id="error"></div>
 </fieldset>
</form>

php

In this php script we are getting the file from the html file and checking it if the file is valid we r uploading the file and stroing it in a array else we are storing the error message in a array and in last we are encoding the success and error array into json format
<?php
header('Content-Type: application/json');

//function to get the extension of the file
function getExt($name){
 $array = explode(".", $name);
 $ext = strtolower(end($array));
 return $ext;
}

//create global array
$allowed = array('gif', 'png', 'jpg');
$success = array();
$error = array();

if(isset($_FILES['file']) && !empty($_FILES['file'])){
  foreach ($_FILES['file']['name'] as $key => $name) {
   $tmp = $_FILES['file']['tmp_name'][$key];
   $ext = getExt($name);
   $size = $_FILES['file']['size'][$key];

   // check the extension is valid or not
   if(in_array($ext, $allowed) == true){
    $filename = md5($name) . time() .'.'.$ext;
    //check the size of the file
    if($size <= 2097152){
     if(move_uploaded_file($tmp, 'uploads/'.$filename) === true){
      $success[] = array('name' => $name, 'location' => 'uploads/'.$filename);
     }else{
      $error[] = array('name' => $name, 'msg' => 'File is not uploaded');
     }
    }else{
     $error[] = array('name' => $name, 'msg' => 'File size more than 2MB');
    }
   }else{
    $error[] = array('name' => $name, 'msg' => 'File Type not allowed');
   }
  }
  
  //encode the result in json format
  $json = json_encode(array(
   'success' => $success,
   'error' => $error
  ));

  echo $json;
  exit();
}
?>

javascript

we are sending a XMLHttpRequest to the server and displaying the response given by the upload.php page back to the user in empty div which we have created earlier 
<script type="text/javascript">
 var form = document.querySelector('#upload'),
   fileToUpload = document.querySelector('#file'),
  button = document.querySelector('#submit'),
  per = document.querySelector('#percentage'),
  sucessDiv = document.querySelector('#success'),
  errorDiv = document.querySelector('#failed'),
  sucessMarkup = '',
  errorMarkup = '';

 form.addEventListener('submit', function(e){
  e.preventDefault();

  var files = fileToUpload.files;

  var formdata = new FormData();

  //loop throught all the files

  for (var i = 0; i < files.length; i++) {
   var file = files[i];

   formdata.append('file[]', file);
  }

  var xhr = new XMLHttpRequest();
  xhr.open('POST', 'upload.php');

  xhr.addEventListener('readystatechange', function(){
   if(xhr.readyState === 4){
    if(xhr.status === 200){
     var uploaded = JSON.parse(xhr.response);
     //put the json response to the div
     //success files 
     for(var i = 0; i < uploaded.success.length; i++){
      var name = uploaded.success[i].name;
      var location = uploaded.success[i].location;

      sucessMarkup += "<a href='view.php?id="+location+"' target='_blank'>"+name+"</a>";
     }

     //error file

     for (var i = 0; i < uploaded.error.length; i++) {
      var name = uploaded.error[i].name;
      var msg = uploaded.error[i].msg;

      var errorH1 = document.createElement('h2');
      errorH1.innerHTML = 'Unfortunately '+uploaded.error.length+' files are not uploaded';
      errorDiv.appendChild(errorH1);
      errorMarkup += '<p>'+name+' - '+msg+'</p>';
     };
     
     //put the results in the div
     sucessDiv.innerHTML = sucessMarkup;
     errorDiv.innerHTML = errorMarkup;
    }
   }else{
    console.log('error');
   }
  }, false);
 
  //code for showing the upload percenatge
  xhr.upload.addEventListener('progress', function(e){
   if(e.lengthComputable === true){
    var per = Math.round((e.loaded / e.total) * 100);
    percentage.innerHTML = per + '% uploaded';
   }
  })

  
  xhr.send(formdata);

 }, false);
</script>

Thursday, April 10, 2014

File Upload with Progress bar by Raw AJAX & php

Hey Guyz in the tutorial i am going to teach you how to create a file upload system with progress bar with raw ajax. This is very useful for the hosting website because it give a great feedback to the user how much their file has been uploaded. This type to project can be created easily with a code library like jQuery but its greate to create it via raw ajax it give a greate understanding that what is going on
live Demo Download Watch Video

html

html markup is super easy in this we have a form a progressbar and a empty status div
<form action="upload_back.php" method="post" enctype="multipart/form-data" id="form">
  <input type="file" name="file1" id="file1">
  <input type="submit" name="submit" id="submit" value="upload"> 
 </form>
 <br>
 <div style="width:400px;">
  <div id="progressbar">
   <div id="progress" style="width:0px;"></div>
  </div>
 </div>
 <div id="status"></div>

css

in css we are designing the progress bar fro more details view my previous post on Css3 Progress Bar
<style type="text/css">
#progressbar{
 width: 100%;
 background: #eee;
 padding: 3px;
 border-radius: 3px;
 box-shadow: inset 0px 1px 3px rgba(0,0,0,0.2);
 }
#progress{
 height: 20px;
 background: cornflowerblue;
 display: block;
 border-radius: 3px;
 -webkit-transition: width 0.8s ease;
 -moz-transition: width 0.8s ease;
 transition: width 0.8s ease;
}
</style>

JavaScript

in javascript we are sending the uploded data to the upload_back.php page and by diving the kb send and total kb we get the percentage of how much the file is uploaded
<script type="text/javascript">
 var ajax = new XMLHttpRequest();
 function $(id){
  return document.getElementById(id);
 }
 function upload(e){
  e.preventDefault();
  var file = $("file1").files[0];
  var formdata = new FormData();
  formdata.append('file1', file);

  ajax.upload.addEventListener('progress', progressHandler, false);
  ajax.addEventListener('load', completeHandler, false);
  ajax.addEventListener('abort', abortHandler, false);
  ajax.addEventListener('error', errorHandler, false);
  ajax.open('POST', 'upload_back.php');
  ajax.send(formdata);
 }

 function progressHandler(e){
  var percent = (e.loaded / e.total) * 100;
  percent = Math.round(percent);
  $('progress').style.width = Math.round(percent)+'%';
  $('status').innerHTML = percent + '% uploaded plzz wait.....';
 }
  function completeHandler(){
   $('status').innerHTML = ajax.responseText;
   $('progress').style.width = '0%';
  }

  function abortHandler(){
   alert('file upload aborted');
  }

  function errorHandler(){
   alert('file upload has an error');
  }
         //when form is submited
 $('form').addEventListener('submit', upload, false);

</script>

upload_back.php

in php file first we are getting the extension of the image and if iuts valid then we upload the file and show the link
<?php
 function getext($img){
  $name = strtolower($img);
  $data = explode(".", $name);
  $ext = count($data) -1;
  return $data[$ext];
 }
 if(isset($_FILES)){
  $allowed = array('jpg','png','gif');
  $ext = getext($_FILES['file1']['name']);
  $size = $_FILES['file1']['size'];
  if(in_array($ext, $allowed)){
   if($size < 2097152){
    $name = $_FILES['file1']['name'];
    if(move_uploaded_file($_FILES['file1']['tmp_name'], './upload/'.$name)){
     echo '<a href="./upload/'.$name.'">'.$name.'</a>';
    }else{
     echo "file upload has an error";
    }
   }else{
    echo "File size more than <strong>2MB<strong>";
   }
  }else{
   echo "file type not allowed";
  }
 }else{
  echo "not";
 }
?>

Tuesday, March 25, 2014

Tumblr & facebook like DropDown Search with jQuery & php

Hi Guyz in this post i am going to teach u how to create a tumblr like drop down search with jQuery and php. Its really simple and easy but looks very greate and give very nice user interface to the website.
Tumblr like Dropdown search with jQuery and PHP
Download Live Demo Watch Video

Database

we have to create a table name `tumblr_search` were we have fields like id, name & pic
CREATE TABLE IF NOT EXISTS `tumblr_search` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(150) NOT NULL,
  `pic` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;

html

html is super easy in this we have a <input> field with id search and a <ul> tag

<div id="container">
  <div id="search-container">
   <input id="search" type="search" placeholder="Quick Search"/>
   <ul>
   </ul>
  </div>
 </div>

css

body{
 margin: 0px;
 padding: 0px;
 background:#529ecc url('https://24.media.tumblr.com/5e222941828bd79bec2bdaa8a309558a/tumblr_n2fks20OyJ1qzv12bo1_1280.jpg') no-repeat;
 background-size: 100% 100%;
}
#container{
 height: 700px;
 width: 800px;
 margin:0 auto;
 padding: 10px;
}
a{
 color: black;
 font-weight: bold;
 font-size: 20px;
}
h1{
 color: white;
}
#search-container{
 float: right;
}
#search{
 height: 25px;
 width: 180px;
 font-weight: bold;
 color: #444;
 border-radius: 15px;
 border: 1px solid transparent;
 outline: none;
 padding: 7px;
 background: white;
 opacity: 0.6;
}
#search:focus{
 opacity: 1.0;
}
#search-container ul{
 list-style: none;
 margin: 0px;
 padding: 0px;
 margin-top: 10px;
}
#search-container ul li{
 height: 30px;
 border: 1px solid #ccc;
 background: white;
 padding: 3px;
 font-family: verdana;
}
#search-container ul li:hover{
 background: lightblue;
 cursor: pointer;
}
#search-container ul li img{
 height: 31px;
 border-radius: 5px;
 float: right;
}

javaScript

In javascript we are getting the value of your input field and sending it to the search.php page were all the result from the database is fetched and putting the response from the search.php page in the <ul>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
 $(document).ready(function(){
  $('#search').bind('keyup', function(){
   var searchTerm = jQuery.trim($(this).val());
   if(searchTerm == ''){
    $('#search-container ul').html('');
   }else{
    //send the data to the database
    $.ajax({
     url: 'search.php',
     type: 'GET',
     data: {search:searchTerm},
     beforeSend: function(){
      $('#search-container ul').html('<li>Loading...</li>');
     },
     success: function(data){
      $('#search-container ul').html(data);
     }
    });
   }
  });
 });
</script>

Search.php

in search.php we are spliting the search term with preg_split function and in the foreach loop we are creating the query if the term is 1 then search only name and if term is more than 1 we prefix and in the query. then we are fetching the data from the database and displaying the result
<?php
/*
 code For Connecting to the databse
*/
 if (isset($_GET['search']) && !empty($_GET['search'])) {
  $search = mysql_real_escape_string($_GET['search']);
  $terms = preg_split('/[\s]+/', $search);//split the search term
  $term_count = 0;
  $query = '';
  foreach ($terms as $term) {
   $term_count ++;
   if($term_count == 1){
    $query .= "`name` LIKE '%$term%' ";
   }else{
    $query .= "AND `name` LIKE '%$term%'";
   }
  }
  //execute the query
  $result = mysql_query("SELECT * FROM tumblr_search WHERE $query");
  //if result found
  if(mysql_num_rows($result) > 0){
   while($row = mysql_fetch_assoc($result)){
    echo '<li>'.$row['name'].'<img src="'.$row['pic'].'"></li>';
   }
   //result not found
  }else{
   echo '<li>Not Found try hus</li>';
  }
  
 }
?>

Thursday, March 13, 2014

Drag & Drop Multiple File Upload Like Facebook

In this post me your Dost and Host Husain Saify(hunk husain) is going to teach you to to create a facebook like Drag and Drop Multiple file upload with jQuery & php. For this we are using a uploadFile plugin  Developed by Ravishanker Kusuma Thanx Sir For Developing it.
Drag and Drop Multiple File Upload With jQuery and Php
Live Demo Download
jQuery File UPload plugin provides Multiple file uploads with progress bar. jQuery File Upload Plugin depends on Ajax Form Plugin

JS & CSS files

In the First Step we are Including the jquery.js , jquery.uploadFile.js, uploadFile.css in the Head
<link href="https://googledrive.com/host/0B7XFDKT_0Oz4T3ZOcHk2eks4bmc/uploadfile.css" rel="stylesheet">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://googledrive.com/host/0B7XFDKT_0Oz4T3ZOcHk2eks4bmc/jquery.uploadfile.js"></script>
you can use your CDN

html

In html we have to just create a div and give it a id i have named it uploadDiv
<div id="uploadDiv">Select File</div>

javascript

In Javascript we are just using uploadFile function in the div $('div').uploadFile(); and giving some object read more about it click here
<script>
$(function(){
 $('#uploadDiv').uploadFile({
  url: "upload.php",
  allowedTypes: "png,jpg,gif",
  multiple: true,
  fileName: "hunklessons"
 });
});
</script>

upload.php

upload.php has the code for single and multiple file upload the if the file is single if block get executed and if its multiple else block get executed
<?php
$output_dir = "uploads/";
if(isset($_FILES["hunklessons"])){ 
 $return = array();
 $error = $_FILES["hunklessons"]["error"];
 //if uploading single file
 if(!is_array($file)){
  $file = $_FILES['hunklessons']['name'];
  move_uploaded_file($_FILES["hunklessons"]["tmp_name"];, $output_dir.$file);
  $return[] = $file;
 }else{ //if uploading multiple file
  foreach ($_FILES['hunklessons']['name'] as $file) {
   move_uploaded_file($_FILES["hunklessons"]["tmp_name"];, $output_dir.$file);
   $return[] = $file;
  }
 }
    echo json_encode($ret);
 }
 ?>
Any Question Plzz Comment

Thursday, March 6, 2014

Facebook like Profile Tooltip with jQuery, Ajax, Php & Mysql

In this post i am going to tell u guz how to create a facebook like profile tooltip with jQuery php & mysql. Probably this will be my last post till 26 march 2014 because currently my paper are going on and i get very less time for my girlfriend (computer) so we will meet after 26 march 2014 byeeeeeee
facebook like profile tooltip with jQuery and php

Live Demo Download

Database

first we are creating a database with general info id, fullname, headline, avatar, cover
CREATE TABLE IF NOT EXISTS `fb_profile_tooltip` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `fullname` varchar(255) NOT NULL,
  `headline` varchar(255) NOT NULL,
  `avatar` text NOT NULL,
  `cover` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

html

Html is having nothing special we just have html5 data-id (anchor tag) with store the user id and that id will be fetched by jQuery and send to php to create a dynamic profile tooltip & a div with a class p-tooltip
 <div class="p-tooltip"></div>
 <table cellpadding="20">
  <td><a href="#" class="profile" data-id="1">user1</a></td>
  <tr>
  <td><a href="#" class="profile" data-id="2">user2</a></td>
  <tr>
  <td><a href="#" class="profile" data-id="3">user3</a></td>
  <tr>
  <td><a href="#" class="profile" data-id="4">user4</a></td>
 </table>

css

body{
font-family: verdana;
}
a{
text-decoration: none;
}
.p-tooltip{
background: #fafbfb;
border: 1px solid #BFBFBF;
width: 320px;
margin: 0 auto;
border-radius: 5px;
position: absolute;
display: none;
padding: 0 0 10px 0;
}
.p-tooltip-cover img{
width: 100%;
height: 120px;
}
.p-tooltip-avatar{
text-align: left;
margin-top: -45px;
margin-left: 10px;
}
.p-tooltip-avatar img{
height: 75px;
width: 75px;
padding: 4px;
background: #fff;
border: 1px solid #ccc;
cursor: pointer;
}
.p-tooltip-info{
text-align: left;
}
.p-tooltip-info .p-username{
float: none;
margin-top: -70px;
margin-left: 100px;
font-size: 14px;
font-weight: bold;
color: white;
}
.p-tooltip-info .p-headline{
float: none;
margin-top: 6px;
margin-left: 100px;
font-size: 12px;
color: black;
}
.p-tooltip-button{
float: right;
margin-top: 5px;
}
.p-tooltip-button button{
cursor: pointer;
}

jQuery
we have created two function 1> showProfileTooltip(); 2> hideProfileTooltip(); when user mouseover a link we use the showProfileTooltip(); this function get the data from a get_profile.php and feed the data in the p-tooltip div and when the mouseleave we use hideProfileTooltip();
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script type="text/javascript">
 $(document).ready(function(){
  function showProfileTooltip(e, id){
   var top = e.clientY + 20;
   var left = e.clientX - 10;

   $('.p-tooltip').css({
    'top':top,
    'left':left
   }).show();
   //send id & get info from get_profile.php
   $.ajax({
    url: 'get_profile.php?id='+id,
    beforeSend: function(){
     $('.p-tooltip').html('Loading..');
    },
    success: function(html){
     $('.p-tooltip').html(html);
    }
   });
  }

  function hideProfileTooltip(){
   $('.p-tooltip').hide();
  }

  $('.profile').mouseover(function(e){
   var id = $(this).attr('data-id');
   showProfileTooltip(e, id);
  });

  $('.p-tooltip').mouseleave(function(){
   hideProfileTooltip();
  });
 });
 </script>

get_profile.php

in this page we are getting the user id and generating the content based on its uniquer id fetched from the html5 data-id anchor tag
<?php
 //include '../connect.php';
 ///connect to mysql 
 mysql_connect('localhost','root', '');
 mysql_select_db('hunklessons');
 //get the user id
 if(isset($_GET['id']) && !empty($_GET['id'])){
  $id = mysql_real_escape_string($_GET['id']);
  //get info of user based on user id
  $q = mysql_query("SELECT * FROM fb_profile_tooltip WHERE id='$id'");
  if(mysql_num_rows($q) == 1){
   $row = mysql_fetch_assoc($q);
   //output the html
   ?>
  <div class="p-tooltip-cover">
   <img src="<?php echo $row['cover'];?>">
  </div>
  <div class="p-tooltip-avatar">
   <img src="<?php echo $row['avatar'];?>" />
  </div>
  <div class="p-tooltip-info">
   <a target="_blank" href="http://hunklessons.blogspot.in/" style="text-decoration:none;">
    <div class="p-username"><?php echo $row['fullname'] ?></div>
    <div class="p-headline"><?php echo $row['headline'] ?></div>
   </a>
  </div>
  <div class="p-tooltip-button">
   <a target="_blank" href="http://hunklessons.blogspot.in/">
    <button>Add as friend</button><button>message</button>
   </a>
  </div>
   <?php
  }else{
   echo "Error";
  }
 }
?>

Monday, March 3, 2014

facebook like hashtag system with Php, Mysql & jQuery

Now a days hashtag is the fundamental part of a social networking site. Hashtag was first started by twitter but latter followed by every social network like tumblr, facebook, instagram etc. hashtag let you know how much people are talking about that particular topic in the world. Hashtag look like this #hashtag if you dont know what is hashtag you probably havent used a social network.
Live View & Download

Structure of database

Before starting we have to create a table with name message in our database with 3 field id ,message & hashtag
CREATE TABLE IF NOT EXISTS `message` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `message` text NOT NULL,
  `hashtag` varchar(255) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Database will look something like that

Function to Filter Hashtag

In this function we are matching the hashtag from the text filed and separating them with the help of regular experation. we are using preg_match_all() to match the #hashtags
<?php
//function to filter the hashtag
 function hashtag($msg){
  //filter the hastag
  preg_match_all('/(^|[^a-z0-9_])#([a-z0-9_]+)/i', $msg, $matched_hashtag);
  $hashtag = '';
  //if hashtag found
  if(!empty($matched_hashtag[0])){
   //fetch hastag from the array
   foreach ($matched_hashtag[0] as $matched) {
    //append every hastag to a string
    //remove the # by preg_replace function
    $hashtag .= preg_replace('/[^a-z0-9]+/', '', $matched).',';
    //append and , after every hashtag
   }
  }
  //remove , from the last hashtag
  return rtrim($hashtag, ',');
 }
?>

Function to convert http:// and #hashtag into links

<?php
//function to convert the url & hashtag into link
 function convert_to_links($msg){
  $final_message = preg_replace(array('/(?i)\b((?:https?:\/\/|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))/', '/(^|[^a-z0-9_])@([a-z0-9_]+)/i', '/(^|[^a-z0-9_])#([a-z0-9_]+)/i'), array('<a href="$1" target="_blank">$1</a>', '$1<a href="">@$2</a>', '$1<a href="index.php?hashtag=$2">#$2</a>'), $msg);
  return $final_message;
 }
?>

Html

html is supe reasy in this we are just having a form with the id postForm a textarea a submit button & a span with id of loader to show loading when submit button is pressed
<h2>Facebook Styled Hashtag</h2>
 <form action="" method="post" id="postForm">
  <textarea id="message" placeholder="Whats on your Mind?"></textarea>
  <input type="submit" value="post">
  <span id="feedback" style="display:none;"><img src="loader.gif" style="height:25px;float:right;"></span>
 </form>

jQuery (javascript)

With jQuery we are just sending the post to the update.php file and prepending the post into the post_contaiiner div
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.0/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $('#postForm').submit(function(){
  var feedback = $('#feedback');
  var message = $('#message');
  //check that the message is empty or not
  if(message.val() != ''){
   feedback.show();
   $.post('update.php', {msg:message.val()}, function(response){
    $('#post_container').prepend(response);
    feedback.hide();
    message.val('');
   });
  }else{
   alert('Please enter a message');
  }
  return false;
 });
});
</script>

connect.php

Before we insert the message into the database we need to connect to the database to cooonect to the database we use mysql_connect() function
<?php
 //connect to the database
 define('host', 'localhost');
 define('username', 'root');
 define('password', '');
 define('db', 'hunklessons');
 $connect = mysql_connect(host,username,password) or die(mysql_error('Could not Connect To database'));
 $database = mysql_select_db(db) or die(mysql_error('Database not found'));
?>

Update.php

in this file we are first getting the hashtag by using Your hashtag function and then inserting the data into the database and then displaying the message and that message is picked by jQuery and display in index.php page
<?php
 require 'connect.php';
 require 'function.php';
 if(isset($_POST['msg']) && !empty($_POST['msg'])){
  $msg = mysql_real_escape_string(strip_tags(trim($_POST['msg'])));
  //get the hastag 
  $hashtags = hashtag($msg);
  //insert into db
  $query = mysql_query("INSERT INTO `message` (`message`,`hashtag`) VALUES ('$msg', '$hashtags')");
  $final_msg = convert_to_links($msg);
  echo '<div id="posts">
  <ul>
  <li><img src="image.jpg"></li>
  <li>'.$final_msg.'</li>
  <ul>
  </div>';
 }
?>

index.php

in this page we are displaying the message if the hashtag is requested then we display only the post related to hashtag and else if it is not requested we display all the post
 
<?php
  //if hashtag is requested
  if(isset($_GET['hashtag']) && !empty($_GET['hashtag'])){
   $hashtag = mysql_real_escape_string(strip_tags(trim($_GET['hashtag'])));
   $query = mysql_query("SELECT * FROM message WHERE hashtag LIKE '%$hashtag%' ORDER BY id DESC");
   $title = "Search Result For <span style='color:red;'>".$hashtag."</span> <a href='index.php'>clear</a>";
  }else{ // if not
   $query = mysql_query("SELECT * FROM message ORDER BY id DESC LIMIT 15");
   $title = "All Updates";
  }
 ?>
 <div id="post_container">
  <?php
  echo $title;
  //display the messages
  if(mysql_num_rows($query) > 0){
   while ($row = mysql_fetch_assoc($query)) {
    $final_msg = convert_to_links($row['message']);
    echo '<div id="posts">
     <ul>
     <li><a target="_blank" href="http://hunklessons.blogspot.in/"><img src="image.jpg"></a></li>
     <li>'.$final_msg.'</li>
     <ul>
     </div>';
   }
  }
  ?>
  <!--post will go here-->
 </div>


Like Us on Facebook / Add Hunk As Friend


Friday, February 14, 2014

jQuery Username Availability check.

jQuery Username Availability check.

Hi in this lessons i am going to teach you how to check that a username is available with jQuery. This is very useful for developer as well as the users because they see a nice UI
jQuery username Availability Check.

Download Script View Demo 

index.php

in index.php page their is a simple input field were user put their username and that data is send to a php file this is done is real time using jQuery .keyup(function(){ }); and in the ajax request we have give a response variable in the success object this variable get the response text from the username.php file

,
<form method="post">
 <input type="text" id="username" placeholder="username">
 <span id="feedback"></span>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
 $('#username').keyup(function() {
  var username = $(this).val();
  //send the data to a username.php file
  $.ajax({
   url: './username.php',
   type: 'POST',
   data: {username:username},
   beforeSend: function(){
    $('#feedback').text('Searching....');
   },
   //get the response text from the username.php file
   success: function(response){
    $('#feedback').html(response);
   }
  });
 });
});
</script>

username.php

In username.php file the username is coming from the input filed which is in the index.php file. In username.php we are check that the username already in the database or not and outputing the result.


<?php
 //connect to the database
 mysql_connect('localhost','root','');
 mysql_select_db('hunklessons');

 if(isset($_POST['username'])){
  $username = mysql_real_escape_string($_POST['username']);
  $q = mysql_query("SELECT * FROM users WHERE username='$username'");
  $num = mysql_num_rows($q);
  if($num >= 1){
   echo "<span style='color:red'>".$username." Not Available</span>";
  }else{
   echo "<span style='color:green'>".$username." Available</span>";
  }
 }
?>

Tuesday, February 11, 2014

Select And Upload Multiple Images With jQuery & Ajax

HII Guyz my name is Husain Saify Welcome To hunklessons. In this lessons i am going to teach you guyz how to upload images without refreshing the page. For this we are using jQuery and jQuery form plugin it has a Just few lines of JavaScript code, Using this you can upload files, image and videos without refreshing the page.
Select And Upload Multiple Images With jQuery & Ajax
Select And Upload Multiple Images With jQuery & Ajax

Download Script View Demo 

index.php

in index.php there is some jQuery code that perform ajax request to the server and prepend the uploaded image to the View div. In plain english we can say that every time the INPUT FILE TAG is change we are submitting the form to upload.php using ajaxForm Method.
<html>
<head>
 <title>jQuery & Ajax Multiple Image Upload</title>
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
 <script type="text/javascript" src="./js/jquery.form.js"></script>
</head>
<body>
 <div id="view" style="height:auto"></div>
 <form action="upload.php" method="post" enctype="multipart/form-data" id="imgform">
  Upload Image:
  <div id="imageloader" style="display:none;"><img src="https://fbstatic-a.akamaihd.net/rsrc.php/v2/yb/r/GsNJNwuI-UM.gif" style="height:20px;"></div>
  <div id="imagebutton"><input type="file" name="file"/></div>
 </form>
 <script type="text/javascript">
 $('#imgform').on('change',function(){ //submit the form when image is selected
  $('#imgform').ajaxForm({target: '#view',
   beforeSend: function(){//show the loader
    $('#imageloader').show();
    $('#imagebutton').hide();
   },success: function(){ //show the file button
    $('#imageloader').hide();
    $('#imagebutton').show();
   },error: function() {
    $('#imageloader').hide();
    $('#imagebutton').show();
   }
  }).submit();
 });
 </script>
</body>
</html>

upload.php

upload.php is a simple php page. this page simply check that the image file is valid or not. if the file is valid then it upload it to the server by using move_uploaded_file() function in php
';
<?php
function getExt($name){
 $str = strtolower($name);
 $data = explode(".", $str);
 $n = count($data) -1;
 return $data[$n];
}
 if(isset($_FILES['file'])){
  $name = $_FILES['file']['name'];
  $size = $_FILES['file']['size'];
  $tmp = $_FILES['file']['tmp_name'];
  $ext = getExt($name);
  $valideFormat = array('jpg','png','gif');
  //if file is had a valid format
  if(in_array($ext, $valideFormat)){
   //if size is fine
   if($size < 220833){
    //upload the file
    $newname = time().".".$ext;
    if(move_uploaded_file($tmp, './upload/'.$newname)){
    echo '<img src="./upload/'.$newname.'" style="width:250px;margin:5px;">';
    }
   }else{
    echo "Size more than 200kbs";
   }
  }else{
   echo "Invalid Format. Select a jpg png or gif image";
  }
 }

?>