I received many tutorial requests from my readers that asked to me how to design Facebook style ajax background image upload and position adjustment using Jquery. I have been published many tutorials about ajax image upload, this one is very interesting and it is a combination of many features. I has implemented this in Wall Script, this post will explain you how to design timeline HTML frame, CSS techniques and database design for background image system.
Download Script Live Demo
Note: Try this demo with mobile device.
Users Table
User table contains all the registered user details.
CREATE TABLE users(
user_id INT auto_increment primary key,
username VARCHAR(30),
email VARCHAR(100),
name VARCHAR(100),
passcode VARCHAR(100),
profile_background VARCHAR(300),
profile_background_position VARCHAR(10));
user_id INT auto_increment primary key,
username VARCHAR(30),
email VARCHAR(100),
name VARCHAR(100),
passcode VARCHAR(100),
profile_background VARCHAR(300),
profile_background_position VARCHAR(10));
User database store like this.
INSERT INTO users
('username','email','name','profile_background','profile_background_position')
VALUES
('srinivas','[email protected]','Srinivas Tamada','142384801.jpg','-18px');
('username','email','name','profile_background','profile_background_position')
VALUES
('srinivas','[email protected]','Srinivas Tamada','142384801.jpg','-18px');
Timeline profile background wire-frame.
HTML Code
Take a look at the live demo for more understanding.
<div id="container">
<div id="timelineContainer">
<!-- timeline background -->
<div id="timelineBackground">
<img src="uploads/backgroundimage.jpg" class="bgImage" style="margin-top: -10px;">
</div>
<!-- timeline background -->
<div id="timelineShade">
<form id="bgimageform" method="post" enctype="multipart/form-data" action="image_upload_ajax_bg.php">
<div class="uploadFile timelineUploadBG">
<input type="file" name="photoimg" id="bgphotoimg" class="custom-file-input">
</div>
</form>
</div>
<!-- timeline profile picture -->
<div id="timelineProfilePic"></div>
<!-- timeline title -->
<div id="timelineTitle">Srinivas Tamada</div>
<!-- timeline nav -->
<div id="timelineNav"></div>
</div>
</div>
<div id="timelineContainer">
<!-- timeline background -->
<div id="timelineBackground">
<img src="uploads/backgroundimage.jpg" class="bgImage" style="margin-top: -10px;">
</div>
<!-- timeline background -->
<div id="timelineShade">
<form id="bgimageform" method="post" enctype="multipart/form-data" action="image_upload_ajax_bg.php">
<div class="uploadFile timelineUploadBG">
<input type="file" name="photoimg" id="bgphotoimg" class="custom-file-input">
</div>
</form>
</div>
<!-- timeline profile picture -->
<div id="timelineProfilePic"></div>
<!-- timeline title -->
<div id="timelineTitle">Srinivas Tamada</div>
<!-- timeline nav -->
<div id="timelineNav"></div>
</div>
</div>
CSS code
Just focus on highlighted CSS properties.
*{margin:0px;padding:0px}
body{font-family: Arial, Helvetica, sans-serif;background-color: #e9eaed;color: #333333;}
#container{margin:0 auto;width:900px}
#timelineContainer{width:100%;position:relative}
#timelineBackground {
height: 315px;
position: relative;
border-left: 1px solid #333333;
border-right: 1px solid #333333;
margin-top: -20px;
overflow: hidden;
background-color:#ffffff;
}
#timelineProfilePic {
width: 170px;
height: 170px;
border: 1px solid #666666;
background-color: #ffffff;
position: absolute;
margin-top: -145px;
margin-left: 20px;
z-index: 1000;
overflow: hidden;
}
#timelineTitle {
color: #ffffff;
font-size: 24px;
margin-top: -45px;
position: absolute;
margin-left: 206px;
font-weight: bold;
text-rendering: optimizelegibility;
text-shadow: 0 0 3px rgba(0,0,0,.8);
z-index: 999;
text-transform: capitalize;
}
#timelineShade {
min-height: 95px;
position: absolute;
margin-top: -95px;
width: 100%;
background:url(images/timeline_shade.png);
}
.timelineUploadBG {
position: absolute;
margin-top: 50px;
margin-left: 813px;
height: 32px;
width: 32px;
}
#timelineNav {
border: 1px solid #d6d7da;
background-color: #ffffff;
min-height: 43px;
margin-bottom: 10px;
position: relative;
}
body{font-family: Arial, Helvetica, sans-serif;background-color: #e9eaed;color: #333333;}
#container{margin:0 auto;width:900px}
#timelineContainer{width:100%;position:relative}
#timelineBackground {
height: 315px;
position: relative;
border-left: 1px solid #333333;
border-right: 1px solid #333333;
margin-top: -20px;
overflow: hidden;
background-color:#ffffff;
}
#timelineProfilePic {
width: 170px;
height: 170px;
border: 1px solid #666666;
background-color: #ffffff;
position: absolute;
margin-top: -145px;
margin-left: 20px;
z-index: 1000;
overflow: hidden;
}
#timelineTitle {
color: #ffffff;
font-size: 24px;
margin-top: -45px;
position: absolute;
margin-left: 206px;
font-weight: bold;
text-rendering: optimizelegibility;
text-shadow: 0 0 3px rgba(0,0,0,.8);
z-index: 999;
text-transform: capitalize;
}
#timelineShade {
min-height: 95px;
position: absolute;
margin-top: -95px;
width: 100%;
background:url(images/timeline_shade.png);
}
.timelineUploadBG {
position: absolute;
margin-top: 50px;
margin-left: 813px;
height: 32px;
width: 32px;
}
#timelineNav {
border: 1px solid #d6d7da;
background-color: #ffffff;
min-height: 43px;
margin-bottom: 10px;
position: relative;
}
Styling an input type="file" browse button
Default input type file works with browse button, replaced choose/browse button with camera icon.
<div class="uploadFile timelineUploadBG">
<input type="file" name="photoimg" id="bgphotoimg" class="custom-file-input">
</div>
<input type="file" name="photoimg" id="bgphotoimg" class="custom-file-input">
</div>
CSS
Here actual input type="file" in hidden more, applied background image for DIV.
.uploadFile {
background: url('images_bg/whitecam.png') no-repeat;
height: 32px;
width: 32px;
overflow: hidden;
cursor: pointer;
}
.uploadFile input {
filter: alpha(opacity=0);
opacity: 0;
margin-left: -110px;
}
.custom-file-input {
height: 25px;
cursor: pointer;
}
background: url('images_bg/whitecam.png') no-repeat;
height: 32px;
width: 32px;
overflow: hidden;
cursor: pointer;
}
.uploadFile input {
filter: alpha(opacity=0);
opacity: 0;
margin-left: -110px;
}
.custom-file-input {
height: 25px;
cursor: pointer;
}
JavaScript
Contains JavaScript code and drag option works with Jquery UI plugin. $('body').on('change','#bgphotoimg', function()- bgphotoimg is the ID name of INPUT FILE tag and $('#bgimageform').ajaxForm() - imageform is the ID name of FORM. While changing INPUT it calls FORM submit without refreshing page using ajaxForm() method.
<script src="js/jquery.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.wallform.js"></script>
<script>
$(document).ready(function()
{
/* Uploading Profile BackGround Image */
$('body').on('change','#bgphotoimg', function()
{
$("#bgimageform").ajaxForm({target: '#timelineBackground',
success:function(){
$("#timelineShade").hide();
$("#bgimageform").hide();
}).submit();
});
/* Banner position drag */
$("body").on('mouseover','.headerimage',function()
{
var y1 = $('#timelineBackground').height();
var y2 = $('.headerimage').height();
$(this).draggable({
scroll: false,
axis: "y",
drag: function(event, ui) {
if(ui.position.top >= 0)
{
ui.position.top = 0;
}
else if(ui.position.top <= y1 - y2)
{
ui.position.top = y1 - y2;
}
},
stop: function(event, ui)
{
}
});
});
/* Bannert Position Save*/
$("body").on('click','.bgSave',function ()
{
var p = $("#timelineBGload").attr("style");
var Y =p.split("top:");
var Z=Y[1].split(";");
var dataString ='position='+Z[0];
$.ajax({
type: "POST",
url: "image_saveBG_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
if(html)
{
$(".bgImage").fadeOut('slow');
$(".bgSave").fadeOut('slow');
$("#timelineShade").fadeIn("slow");
$("#timelineBGload").removeClass("headerimage").css({'margin-top':html});
return false;
}
}
});
return false;
});
});
</script>
<script src="js/jquery-ui.min.js"></script>
<script src="js/jquery.wallform.js"></script>
<script>
$(document).ready(function()
{
/* Uploading Profile BackGround Image */
$('body').on('change','#bgphotoimg', function()
{
$("#bgimageform").ajaxForm({target: '#timelineBackground',
success:function(){
$("#timelineShade").hide();
$("#bgimageform").hide();
}).submit();
});
/* Banner position drag */
$("body").on('mouseover','.headerimage',function()
{
var y1 = $('#timelineBackground').height();
var y2 = $('.headerimage').height();
$(this).draggable({
scroll: false,
axis: "y",
drag: function(event, ui) {
if(ui.position.top >= 0)
{
ui.position.top = 0;
}
else if(ui.position.top <= y1 - y2)
{
ui.position.top = y1 - y2;
}
},
stop: function(event, ui)
{
}
});
});
/* Bannert Position Save*/
$("body").on('click','.bgSave',function ()
{
var p = $("#timelineBGload").attr("style");
var Y =p.split("top:");
var Z=Y[1].split(";");
var dataString ='position='+Z[0];
$.ajax({
type: "POST",
url: "image_saveBG_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
if(html)
{
$(".bgImage").fadeOut('slow');
$(".bgSave").fadeOut('slow');
$("#timelineShade").fadeIn("slow");
$("#timelineBGload").removeClass("headerimage").css({'margin-top':html});
return false;
}
}
});
return false;
});
});
</script>
$('body').on('click','.bgSave', function()- bgSave is the class name of save button, using $("#timelinBGload").attr("style") calling the style value and split with top: string.
userUpdates.php
Simple PHP class contains three functions called userDetails, userBackgroundUpdate and userBackgourndPositionUpdate.
<?php
class userUpdates
{
private $db;
public function __construct($db)
{
$this->db = $db;
}
/* Users Details */
public function userDetails($user_id)
{
$query=mysqli_query($this->db,"SELECT username,email,name,profile_background,profile_background_position FROM users WHERE user_id='$user_id' ") or die(mysqli_error($this->db));
$data=mysqli_fetch_array($query,MYSQLI_ASSOC);
return $data;
}
/* Background Image Update */
public function userBackgroundUpdate($user_id,$actual_image_name)
{
$query=mysqli_query($this->db,"UPDATE users SET profile_background='$actual_image_name' WHERE user_id='$user_id'") or die(mysqli_error($this->db));
return $query;
}
/* Background Image Position Update */
public function userBackgroundPositionUpdate($user_id,$position)
{
$position=mysqli_real_escape_string($this->db,$position);
$query=mysqli_query($this->db,"UPDATE users SET profile_background_position='$position' WHERE user_id='$user_id'")or die(mysqli_error($this->db));
return $query;
}
}
?>
class userUpdates
{
private $db;
public function __construct($db)
{
$this->db = $db;
}
/* Users Details */
public function userDetails($user_id)
{
$query=mysqli_query($this->db,"SELECT username,email,name,profile_background,profile_background_position FROM users WHERE user_id='$user_id' ") or die(mysqli_error($this->db));
$data=mysqli_fetch_array($query,MYSQLI_ASSOC);
return $data;
}
/* Background Image Update */
public function userBackgroundUpdate($user_id,$actual_image_name)
{
$query=mysqli_query($this->db,"UPDATE users SET profile_background='$actual_image_name' WHERE user_id='$user_id'") or die(mysqli_error($this->db));
return $query;
}
/* Background Image Position Update */
public function userBackgroundPositionUpdate($user_id,$position)
{
$position=mysqli_real_escape_string($this->db,$position);
$query=mysqli_query($this->db,"UPDATE users SET profile_background_position='$position' WHERE user_id='$user_id'")or die(mysqli_error($this->db));
return $query;
}
}
?>
image_upload_ajax.php
Uploading image file into uploads folder and inserting background image name into users table. Here upload image size restricted for 1 MB, if you want you can modify image size by changing 1024 value.
<?php
include 'db.php';
session_start();
$session_uid='1'; // $_SESSION['user_id'];
include 'userUpdates.php';
$userUpdates = new userUpdates($db);
include_once 'getExtension.php';
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST" && isset($session_uid))
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().$session_uid.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
$bgSave='<div id="uX'.$session_uid.'" class="bgSave wallbutton blackButton">Save Cover</div>';
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$data=$userUpdates->userBackgroundUpdate($session_uid,$actual_image_name);
if($data)
echo $bgSave.'<img src="'.$path.$actual_image_name.'" id="timelineBGload" class="headerimage ui-corner-all" style="top:0px"/>';
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format.";
}
else
echo "Please select image..!";
exit;
}
?>
include 'db.php';
session_start();
$session_uid='1'; // $_SESSION['user_id'];
include 'userUpdates.php';
$userUpdates = new userUpdates($db);
include_once 'getExtension.php';
$valid_formats = array("jpg", "png", "gif", "bmp","jpeg","PNG","JPG","JPEG","GIF","BMP");
if(isset($_POST) && $_SERVER['REQUEST_METHOD'] == "POST" && isset($session_uid))
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
$ext = getExtension($name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().$session_uid.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
$bgSave='<div id="uX'.$session_uid.'" class="bgSave wallbutton blackButton">Save Cover</div>';
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$data=$userUpdates->userBackgroundUpdate($session_uid,$actual_image_name);
if($data)
echo $bgSave.'<img src="'.$path.$actual_image_name.'" id="timelineBGload" class="headerimage ui-corner-all" style="top:0px"/>';
}
else
echo "Fail upload folder with read access.";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format.";
}
else
echo "Please select image..!";
exit;
}
?>
image_saveBG_ajax.php
Inserting background position value into users table based on user session id.
<?php
include 'db.php';
session_start();
$session_uid='1'; // $_SESSION['user_id'];
include 'userUpdates.php';
$userUpdates = new userUpdates($db);
if(isset($_POST['position']) && isset($session_uid))
{
$position=$_POST['position'];
$data=$userUpdates->userBackgroundPositionUpdate($session_uid,$position);
if($data)
echo $position;
}
?>
include 'db.php';
session_start();
$session_uid='1'; // $_SESSION['user_id'];
include 'userUpdates.php';
$userUpdates = new userUpdates($db);
if(isset($_POST['position']) && isset($session_uid))
{
$position=$_POST['position'];
$data=$userUpdates->userBackgroundPositionUpdate($session_uid,$position);
if($data)
echo $position;
}
?>
index.php
Displaying background image based login user session id, more help PHP Login Page Example.
<?php
include 'db.php';
session_start();
$session_uid='1'; // $_SESSION['user_id'];
include 'userUpdates.php';
$userUpdates = new userUpdates($db);
$userData=$userUpdates->userDetails($session_uid);
$username=$userData['username'];
$name=$userData['name'];
$profile_background=$userData['profile_background'];
$profile_background_position=$userData['profile_background_position'];
?>
//HTML Code
<div id="container">
<!-- timeline background -->
<div id="timelineBackground">
<img src="<?php echo $path.$profile_background; ?>" class="bgImage" style="margin-top: <?php echo $profile_background_position; ?>;">
</div>
<!-- timeline background -->
<div id="timelineShade">
<form id="bgimageform" method="post" enctype="multipart/form-data" action="image_upload_ajax_bg.php">
<div class="uploadFile timelineUploadBG">
<input type="file" name="photoimg" id="bgphotoimg" class="custom-file-input">
</div>
</form>
</div>
<!-- timeline profile picture -->
<div id="timelineProfilePic"></div>
<!-- timeline title -->
<div id="timelineTitle">Srinivas Tamada</div>
<!-- timeline nav -->
<div id="timelineNav"></div>
</div>
</div>
include 'db.php';
session_start();
$session_uid='1'; // $_SESSION['user_id'];
include 'userUpdates.php';
$userUpdates = new userUpdates($db);
$userData=$userUpdates->userDetails($session_uid);
$username=$userData['username'];
$name=$userData['name'];
$profile_background=$userData['profile_background'];
$profile_background_position=$userData['profile_background_position'];
?>
//HTML Code
<div id="container">
<!-- timeline background -->
<div id="timelineBackground">
<img src="<?php echo $path.$profile_background; ?>" class="bgImage" style="margin-top: <?php echo $profile_background_position; ?>;">
</div>
<!-- timeline background -->
<div id="timelineShade">
<form id="bgimageform" method="post" enctype="multipart/form-data" action="image_upload_ajax_bg.php">
<div class="uploadFile timelineUploadBG">
<input type="file" name="photoimg" id="bgphotoimg" class="custom-file-input">
</div>
</form>
</div>
<!-- timeline profile picture -->
<div id="timelineProfilePic"></div>
<!-- timeline title -->
<div id="timelineTitle">Srinivas Tamada</div>
<!-- timeline nav -->
<div id="timelineNav"></div>
</div>
</div>
db.php
Database connection you have to modify username, password and database values.
<?php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE) or die(mysqli_connect_error());
$path = "uploads/"; //Images upload folder
?>
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'username');
define('DB_PASSWORD', 'password');
define('DB_DATABASE', 'database');
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE) or die(mysqli_connect_error());
$path = "uploads/"; //Images upload folder
?>
How if user want to cancel to change the cover?
ReplyDeleteThis is awesome! great tutorial!
ReplyDeleteits very good. i really need this in my next project :)
ReplyDeleteUseful demo , just bookmarked. Though I think in original wallscript you have used another mapping table for image rather than users table. right ?
ReplyDeleteThanks for sharing this, simple and straight foward
ReplyDeleteThis is really awesome, i loved it. helped me in my projects. and if you can please give us tutorial on:
ReplyDelete1. How to change php timestamp to a normal time expression, like "Just now" , "3min ago" , "Yesterday" and something like that.
2. The chatbox(The one which appears when clicking one of the online friends list in Facebook).
3. some other graphics of Facebook/wallscript which you think is worth sharing.
Thank you!!
I have bookmarked your site for any facebook like feature implementation. ( lessons is a complete solution.
ReplyDeletethanx mr.Srinivas..... i like all post
ReplyDeletethis is awesome post.. exactly what i'm looking for...
ReplyDeletethank you!!
thanx.. Nice tutorial!
ReplyDeletesimple tutorial, thank for this amazing work
ReplyDeleteThanks for the nice and unique feature of FB. I also want to use it on my timeline. Really great and nice job you did Dude!
ReplyDeleteThis script is only work when some one change is cover image how we will readjust same image after saving.no readjust help in this script.can you help me please
ReplyDeletereally thank you very much friend.this was very helpful me.i will add this in my project!
ReplyDeletethanx
ReplyDeleteI'm a one of big addicted facebook user. That post really awesome
ReplyDeleteNice background for facebook.
ReplyDeletepessoal esse getExtension.php como fazer
ReplyDeleteadjustment from right to left would be great if image is larger than the div holding it
ReplyDeleteGreat Post. Thanks
ReplyDeleteSuch an cool tricks. Thanks a lot bro I will learn great tricks from your blog. Thanks again for this amazing tips.
ReplyDeleteWhere getExtension.php ? Do I need getExtension.php for completing my script? Please help...
ReplyDeleteI really liked this part of the article. with a nice and interesting topics have helped a lot of people who do not challenge things people should know.. you need more publicize this so many people who know about it are rare for people to know this. success for you.
ReplyDeleteAwesome , I love it !!
ReplyDeleteinclude_once 'getExtension.php'; missing file
ReplyDeleteHi,
ReplyDeleteThans Tamada- Very good HTML coding. And i think you share something genuine. I Really like this coding.
Thankx.
thanx.. Nice tutorial!
ReplyDeletewww.assignmntsolution.net
Its really a great information and helps alot.Thanks alot
ReplyDeletethanx a lot... its awesome !!
ReplyDeleteyou are a great man thanks alot
ReplyDeleteexactly what i was looking for. Thanks man.
ReplyDeleteAwesome, thanks mate
ReplyDeleteThis is a good tutorial thanks
ReplyDeleteLove your style....
ReplyDeletenot working because missing file getExtension.php
ReplyDeleteYou will find this in my previous tutorials.
DeleteImpressive!!
ReplyDeleteWould You please post a tutorial on how to implement your scripts in boonex Dolphin 7.2.1 websites.
ReplyDeletethanks!!
oh good.
ReplyDeleteThe form does not submit, anyone knows what might be wrong? It does accept the image but it doesn't send the form to image_upload_ajax. Is it the jquery?
ReplyDeleteIn depth tutorial and very easy to understand.
ReplyDeletehow to download this script plz tell me?
ReplyDeletethank u very very much
ReplyDeleteCan anyone help me write this in Ruby on Rails? I would really apreciate the help.
ReplyDeleteSir, What if i would like to cancel? How it going back the real one
ReplyDeletecan i sir where can i find the
ReplyDeletejquery.wallform.js
this script
Can you please tell me to add the image validation, so that the specific size of image and size can be upload only as people may bombard my server?
ReplyDeleteThanks
ReplyDeletethank you so much ! that very important for me ! because i already selected my final year project in social networking
ReplyDeleteComo baixar esse tutorial ?
ReplyDeleteHow create it responsive for mobile
ReplyDelete
ReplyDeleteWarning: include_once(getExtension.php): failed to open stream: No such file or directory in C:\xampp\htdocs\facebook-style-cover\image_upload_ajax.php on line 8
Warning: include_once(): Failed opening 'getExtension.php' for inclusion (include_path='C:\xampp\php\PEAR') in C:\xampp\htdocs\facebook-style-cover\image_upload_ajax.php on line 8
Fatal error: Call to undefined function getExtension() in C:\xampp\htdocs\facebook-style-cover\image_upload_ajax.php on line 17
Replace this script bellow in include_once(getExtension.php):
ReplyDeleteReplace this function bellow in include_once(getExtension.php):
ReplyDeletefunction getExtension($str)
{
$i = strrpos($str,".");
if (!$i) {
return "";
}
$l = strlen($str) - $i;
$ext = substr($str,$i+1,$l);
return $ext;
}
hello Srinivas sir, how can i edit profile pic in this demo. and please send me any demo for edit profile form in view page only with edit icon ..
ReplyDeleteHello SRINIVAS Sir, Your code is not working mobile version .Please help me.
ReplyDeleteThanks