Facebook Style Background Image Upload and Position Adjustment.
Wall Script
Wall Script
Monday, February 16, 2015

Facebook Style Background Image Upload and Position Adjustment.

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.

Facebook Style Background Image Upload and Position Adjustment.


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 database store like this.
INSERT INTO users
('username','email','name','profile_background','profile_background_position')
VALUES
('srinivas','[email protected]','Srinivas Tamada','142384801.jpg','-18px');

Timeline profile background wire-frame.
Facebook Style Background Image Upload and Position Adjustment.

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>

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;
}

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>

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;
}

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>

$('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;
}
}
?>

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;
}
?>

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;
}
?>

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>

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 
?>
web notification

56 comments:

  1. How if user want to cancel to change the cover?

    ReplyDelete
  2. its very good. i really need this in my next project :)

    ReplyDelete
  3. Useful demo , just bookmarked. Though I think in original wallscript you have used another mapping table for image rather than users table. right ?

    ReplyDelete
  4. Thanks for sharing this, simple and straight foward

    ReplyDelete
  5. This is really awesome, i loved it. helped me in my projects. and if you can please give us tutorial on:
    1. 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!!

    ReplyDelete
  6. I have bookmarked your site for any facebook like feature implementation. ( lessons is a complete solution.

    ReplyDelete
  7. thanx mr.Srinivas..... i like all post

    ReplyDelete
  8. this is awesome post.. exactly what i'm looking for...

    thank you!!

    ReplyDelete
  9. simple tutorial, thank for this amazing work

    ReplyDelete
  10. Thanks 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!

    ReplyDelete
  11. This 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

    ReplyDelete
  12. really thank you very much friend.this was very helpful me.i will add this in my project!

    ReplyDelete
  13. I'm a one of big addicted facebook user. That post really awesome

    ReplyDelete
  14. pessoal esse getExtension.php como fazer

    ReplyDelete
  15. adjustment from right to left would be great if image is larger than the div holding it

    ReplyDelete
  16. Such an cool tricks. Thanks a lot bro I will learn great tricks from your blog. Thanks again for this amazing tips.

    ReplyDelete
  17. Where getExtension.php ? Do I need getExtension.php for completing my script? Please help...

    ReplyDelete
  18. I 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.

    ReplyDelete
  19. include_once 'getExtension.php'; missing file

    ReplyDelete
  20. Hi,

    Thans Tamada- Very good HTML coding. And i think you share something genuine. I Really like this coding.
    Thankx.

    ReplyDelete
  21. thanx.. Nice tutorial!
    www.assignmntsolution.net

    ReplyDelete
  22. Its really a great information and helps alot.Thanks alot

    ReplyDelete
  23. exactly what i was looking for. Thanks man.

    ReplyDelete
  24. This is a good tutorial thanks

    ReplyDelete
  25. not working because missing file getExtension.php

    ReplyDelete
  26. Would You please post a tutorial on how to implement your scripts in boonex Dolphin 7.2.1 websites.
    thanks!!

    ReplyDelete
  27. The 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?

    ReplyDelete
  28. In depth tutorial and very easy to understand.

    ReplyDelete
  29. how to download this script plz tell me?

    ReplyDelete
  30. Can anyone help me write this in Ruby on Rails? I would really apreciate the help.

    ReplyDelete
  31. Sir, What if i would like to cancel? How it going back the real one

    ReplyDelete
  32. can i sir where can i find the
    jquery.wallform.js

    this script

    ReplyDelete
  33. 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?

    ReplyDelete
  34. thank you so much ! that very important for me ! because i already selected my final year project in social networking

    ReplyDelete
  35. How create it responsive for mobile

    ReplyDelete


  36. Warning: 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

    ReplyDelete
  37. Replace this script bellow in include_once(getExtension.php):

    ReplyDelete
  38. Replace this function bellow in include_once(getExtension.php):
    function getExtension($str)
    {
    $i = strrpos($str,".");
    if (!$i) {
    return "";
    }
    $l = strlen($str) - $i;
    $ext = substr($str,$i+1,$l);

    return $ext;
    }

    ReplyDelete
  39. 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 ..

    ReplyDelete
  40. Hello SRINIVAS Sir, Your code is not working mobile version .Please help me.
    Thanks

    ReplyDelete

mailxengine Youtueb channel
Make in India
X