Post image for Create a facebook post to wall system using PHP and jQuery Part 2

Create a facebook post to wall system using PHP and jQuery Part 2

by Hyder on July 7, 2011

in Jquery, PHP

If you have not read my previous post on creating a Facebook post to wall system then you should read it first. In this article, I will explain how I added code behind the “Share button” so that when clicked, it will post the content of the text area as wall post.

How it works ?

When you click on “share” button :

  1. The file insert.php is called via ajax to save message in database
  2. if message is saved successfully , then add message to the unordered list like below
  3. <ul id="posts">
    <li>My wall post message </li>
    </ul>
    

    Jquery code below is used to add the message as list :

    $('ul#posts').prepend('My wall post message');
  4. The textarea message is then cleared
  5.   $('textarea#wall').val('');
  6. If another message is shared on the wall , it is added on the dom like this :
  7. <ul id="posts">
    <li>This is my second post </li>
    <li>My wall post message </li>
    </ul>
    


Basically , this is how the post to wall system works .Below is the complete code when user clicks on share button . I have added the comments inline .

 $('#shareButton').livequery("click", function () { //if user clicks on share button
        var textarea_content = $('textarea#wall').val(); // get the content of what user typed ( in textarea )
        if (textarea_content != '') { // if textarea is not empty
            var sitetitle = $('label.title').html(); // then get external site title (if there's any )
            if (sitetitle == null) {
                sitetitle = ' ';
            }

            var siteurl = $('label.url').html(); // get site url ( if there's any )
            if (siteurl == null) { // if no value retrieved
                siteurl = ' '; //set to blank to prevent 'null' or 'undefined' displayed on page
            }
            var sitedesc = $('label.desc').html(); // get external site description ( if there's any)
            if (sitedesc == null) { // if no value retrieved
                sitedesc = ' '; //set to blank to prevent 'null' or 'undefined' displayed on page
            }
            var current_image_id = $('input#current_img').val(); // get the current image thumbnail id (if there's any)
            // we need that id to post the correct image chosen by user in  wall post
            if (current_image_id != '') { //make sure id is retrieved successfully
                var current_image_url = $("img#" + current_image_id).attr("src"); // get the current image displayed in thumbnail url in "src" tag
                if (current_image_url != '') { //if there's an image url
                    var image_html = '<div class="img_attachment"> <img class="external_pic" width="90" height="67"  src="' + current_image_url + '">'; // prepare image url 'embeded with appropriate html
                } else {
                    var image_html = ''; //No image to display ( it means that no image url was retrieved from external website , ( ignoring <div class = 'img_attachement> .. </div>
                }
            } else {
                var image_html = ''; // set to nothing
            }

            var wall_post = '<li> <img src="image/avatar.jpg" class="avatar">    <div class="status">     <h2><a href="#" target="_blank">Hyder Abbass</a></h2>  <p class="message">' + textarea_content + '</p> ' + image_html + '<div class="data"><p class="name"><a href="' + siteurl + '" target="_blank">' + sitetitle + '</a></p><p class="caption">' + siteurl + '</p><p class="description">' + sitedesc + '</p></div></div> </div><p class="likes">5 hours ago ·            100 Likes </p></li>';
      var message_wall = $('#message_wall').attr('value');

            $.ajax({
                type: "GET",
                url: "insert.php",
                data: "message_wall=" + wall_post,
                success: function () {
                    $('ul#posts').prepend(wall_post);

                }
            });

            //Add the prepared html to add in div with id = wallz
            //After adding the post wall ,
            $('textarea#wall').val(''); // remove text in the textarea
            $('#ajax_content').empty(); // empty the div with id = ajax_content ( contains previous content fetched via ajax )
            $('#fetched_data').hide(); // hide the div
            $('#ajax_flag').val(0); //reset  this to zero
        } else {
            alert('Enter some text ! '); // just in case some morons try to click on share witout writing anything :)
        }

    });

Wrap up

In this article ( Part 1 and part 2 ) we learnt how to create a Facebook post-to-wall system that allows a user to post whatever he or she type in the text area. If the text area contains a link to an external website, the page title, description and thumbnails contained on this external page is automatically fetched and displayed. User can choose which thumbnail to post as wall post. When user clicks on the share button, the application triggers an Ajax call to insert.php (in which you should write code to save it to your database). if you have any question/problem , I had love to answer you in the comments below.

Related Posts

  1. Create a facebook post to wall system using PHP and jQuery Part 1
  2. Facebook and Google Plus style of introducing new features using jQuery
  3. Create fancy contact form with CSS 3 and jQuery
  4. An Alternative to Pagination : Facebook and Twitter Style
After Post

{ 67 comments… read them below or add one }

KennyF. July 12, 2011 at 3:24 pm

Hei

Some questions.

1. When you type in a UR, it will not recognise all URL you type inn. I did a test, and tried as an exampel

http://www.facebook.com and Microsoft homepage.

Why?

2. I can’t play any YouTube videos here

3. If I want to insert a image like Facebook to – either upload from computer or share from a separate site on my site – this is not pssible.

Any solution to this?

Reply

booosterd March 4, 2012 at 11:50 pm

yesssssssssssss

Reply

Hyder July 13, 2011 at 9:26 am

1 .When you type a url , you should press the spacebar in order to trigger the ajax call .However i have noticed it displays “Incompatible Browser” For the page title . This is because facebook didn’t detect any Browser User Agent since we are using the function file_get_content() to fetch the page content . A workaround for this would be to use curl to fetch the website content since curl allows you to pass a browser agent .

2. No the application does not support video streaming embedding like youtube .I Might create another tutorial how to embed video in another article if there’s enough request :)
3. No , the app only support website url .
Let me know if you need more clarification .

Reply

manish July 24, 2011 at 8:36 am

hello sir it’s nice .but i need more clarification about using this. as i run this in chrome but it don’t recognize url plz. help me.

Reply

Hyder July 24, 2011 at 8:44 am

@Manish : to trigger the event to fetch data of a url you need to press spacebar after . It works perfectly in chrome . let me know if you need more clarification .

Reply

manish July 25, 2011 at 3:38 am

hi sir,it’s working…thanks..could i use it in my website…

Reply

manish July 25, 2011 at 4:41 am

hello sir i write following code in my insert.php
include “dbset.php”;
$r=$_GET['message_wall'];
$sql=”INSERT INTO event(posted_user_id,msg,date)VALUES (2, ‘$r’, Now())”;
mysql_query($sql) or die(“sorry”);

when data is inserted into mysql then it only insert this much data
<a href="

rest are not displayed in database ..please help me..

Reply

manish July 25, 2011 at 4:43 am

hello sir i write following code in my insert.php
include “dbset.php”;
$r=$_GET['message_wall'];
$sql=”INSERT INTO event(posted_user_id,msg,date)VALUES (2, ‘$r’, Now())”;
mysql_query($sql) or die(“sorry”);

when data is inserted into mysql then it only insert this much data
<a href="

rest are not displayed in database ..please help me…….

Reply

Sam Brown August 4, 2011 at 7:20 pm

Escape the “#” or put a page.php in there.

Reply

Dayo August 15, 2011 at 4:37 pm

how do i make get name and picture from my database?

Reply

Decca August 21, 2011 at 10:05 am

I am having problems creating the insert.php file. How shall I accept the data via ajax and how can I save it in my MySQL database?

Reply

Hyder August 21, 2011 at 10:19 am

What’s the issue actually ? can you post your code ?

Reply

jmk September 1, 2011 at 8:07 pm

Hi,
Can you provide a basic mysql database setup here so that we can try this program out on a website, also please please provide the completed software.
thanks,
jmk

Reply

videoman September 1, 2011 at 8:44 pm

Hello,
How does one add a database to this? I am quite new to this!
Is it possible for you to add the completed code and database tables?
Thanks much,
want to add this to a site our camera club is building.
videoman

Reply

wiqdgr8 September 5, 2011 at 12:49 pm

Wooowww….. Thanx Alot.. :)

Reply

justis September 12, 2011 at 10:56 am

dude check your time stamp function, now is stated as 5 hours ago and gives an initial of 100 likes. i am bored can you help me with the notification system? Oh this is a great script though, i give it a 10 if you remove the bugs

Reply

Hyder September 12, 2011 at 1:15 pm

Dude there’s not time stamp function .the time is hardcoded just for demo :)check out this code it will help you : http://www.9lessons.info/2010/01/php-time-stamp-function.html

Reply

liverpool September 29, 2011 at 9:16 am

Has anyone got this to work in IE 8?

Reply

Hyder September 30, 2011 at 7:08 am

i’m sorry i don’t have IE8 on my pc . i’ll test it on IE9 tonight and see if there’s any issue .

Reply

Giordano September 29, 2011 at 5:37 pm

Hello, thanks for the tutorials. Unfortunately I’m stuck trying to pass the variables from ajax to php when I call the php script to write in the database:

var wall_post = ‘ Hyder Abbass ‘ + textarea_content + ‘ ‘ + image_html + ‘‘ + sitetitle + ‘‘ + siteurl + ” + sitedesc + ‘ 5 hours ago · 100 Likes ‘;

var message_wall = $(‘#message_wall’).attr(‘value’);
$.ajax({
type: “GET”,
data: “message_wall=” + wall_post,
url: “add.php”,
success: function () {
$(‘ul#posts’).prepend(wall_post);
}
});

I use the method GET in the add.php file to write the variable message_wall in the database but the variables results empty. Could you please help me? Thanks a lot. This is the add.php file:

Reply

Hyder September 30, 2011 at 7:15 am
var message_wall = $(‘#message_wall’).attr(‘value’);
$.ajax({
type: “GET”,
data: “wall_post=” + message_wall, /*This is where you went wrong */
url: “add.php”,
success: function (data) {/*data contain the add.php response value [see explanation below ]*/
if(data == 1){/*Means that message was inserted successfully in db*/
$(‘ul#posts’).prepend(wall_post);/ * then we can display it on page */
}
}
});

Explanation :
You did not assign the variable ‘message_wall’ correctly .If you use firebug , you should see the url something like :
http://localhost/add.php?wall_post=facebook_content_goes_here
I’m assuming that in add.php you have used $_GET['wall_post'] to capture the data via ajax.Also please add a condition in your add.php if the data has been saved in database successfully , echo the value 1 on the page.Let me know if you need any clarification :) code is untested but it should work fine .

Reply

Giordano September 30, 2011 at 9:52 am

Uff Finally! I changed the syntax of the url this way, as you stated above:

$.ajax({
type: “GET”,
data: “message_wall=” + wall_post,
url: “add.php?wall_post="+textarea_content”,
success: function () {
$(‘ul#posts’).prepend(wall_post);
}
});

wall_post is the argument of $_GET in add.php, now works perfectly,

Thanks a lot!

Reply

Hyder September 30, 2011 at 2:21 pm

Great ! but what if for some reason the insert query in add.php fails ? It will still display the message post ! This is why you should take the response from add.php into consideration before displaying the post on the wall .(see line code 6-9 above )

Reply

Giordano September 30, 2011 at 3:05 pm

You’re right, I will include it also, thanks!

abilesh November 8, 2012 at 11:57 am

hi sir ,i need to share pictures and videos if u plz send the required code to my mail

Kiran October 6, 2011 at 11:58 am

Dear Hyder ,

Thanks for this wonderful URL extract program . I just downloaded and setup in my local environment and testing it . Will let you know if I come across any issues .

But sure extracting video URL’s will also be helpful . I checked Youtube JSON data and going to work on it . But not sure how to work with all the video up loader sites . May be choosing top 10 websites will ease my job

Here is the first issue I encountered

If I type http://www.lynda.com/ and enter space , Not getting the images .. But getting description and the link ..

Thank You

Regards
Kiran

Reply

Kiran October 6, 2011 at 12:18 pm

Dear Hyder ,

I found one more link , similar to this (http://www.achari.in/demo/fb-URL/) and it has http://lynda.com working .. but there are some other sites not working there too ..

Just for your information

Regards
Kiran

Reply

Kiran October 6, 2011 at 3:04 pm

Dear Hyder ,

One more comment , I see you are using simple html dom parser . But this is really pretty slow. You can check stats here . php built in DOM library is pretty faster ..

http://whitlock.ath.cx/FastCrawl/benchmark.php

This is just my opinion :)

Regards
Kiran

Reply

Kiran October 6, 2011 at 3:43 pm

Dear Hyder,

For http://lynda.com , it was a image resolution problem and I changed $ImgSize[1] >= 110 and it started working .

Thank You
Regards
Kiran

Reply

Parth November 4, 2011 at 5:21 pm

Have u done mysql query as i am doing it and i get this output
<a href="
can u help me

Reply

Kiran October 6, 2011 at 4:06 pm

Dear Hyder ,

Its me again with one more comment . Some links are breaking .. for example if you try the below URL

http://www.leadership-with-you.com/steve-jobs-leadership.html

It is breaking …and not getting any information .

Note :- This works perfect on facebook and I am debugging it

Regards
Kiran

Reply

Kiran October 6, 2011 at 5:16 pm

Dear Hyder,

Here we go and I found the problem in index.html , replaces var url =content.match with the below string and it is working fine now

var url = content.match(/(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/);

But I still see bit slow … testing more

Regards
Kiran

Reply

Andy October 11, 2011 at 2:21 pm

Hi, could you possibly supply a script for the ‘insert.php’ file so that I can save the info to a mysql database??? I am currently new to this php thing, and at present am still trying to learn this parse/get array and send it to the database side :-( Thanks!! :-)

Reply

charisma October 22, 2011 at 8:33 am

get html from another website can make our website cookies stolen by that website if our user go to not trusted website..and to avoid it we must display html result in iframe..this technique already implemented by oembed, oembed used to fetch video..; to insert data it’s easy andry..just need to $dataToSave= $_GET['message_wall']; to get data and after that do some filter like anti injection filter..and you can go with insert query ..;

Reply

Asim December 6, 2011 at 6:58 pm

plz write a tutorial about how to display all images from mysql database on the same page

Reply

Parth December 16, 2011 at 10:05 am

https://facebook.com is working in demo but not in the download one. Kindly check that

Reply

Louie January 5, 2012 at 5:25 am

Hi,

I found a bug. Whenever you post URL, the follow second post will display empty image, which is undefined.

Edit :
I found a solution to resolve the undefinded image URL,
replace:

if (current_image_url != '') { //if there's an image url
with:
if (typeof current_image_url != 'undefined') { //if there's an image url

It works fine now.

Reply

mihaise September 2, 2012 at 12:36 am

the problem is $(‘input#current_img’).val() is not reset. the solution is:
after

$(‘#ajax_flag’).val(0); //reset this to zero

insert this:

$(‘input#current_img’).val(”);

Another problem is that there is no clear button but it easy to implement.

Reply

Louie January 11, 2012 at 10:49 am

Dear Hyder,

Could you please develop something like Facebook “Older Posts”?

Reply

Hyder January 11, 2012 at 6:50 pm
Louie January 12, 2012 at 4:02 am

Thanks Hyder :)

Reply

Louie January 12, 2012 at 4:08 am

by the way, just for sharing,
for those who have experienced difficulty in saving UTF-8 Chinese characters into DB, you may alter the line below by adding encodeURIComponent, for example:

data: “wall_post=” + encodeURIComponent(message_wall),

it works :)

Reply

Louie January 14, 2012 at 2:48 am

Hi Hyder,

Unfortunately, this script does not work in Internet Explorer 8.

Reply

wuying February 1, 2012 at 3:15 am

Hi Hyder,
Could u please tell me how ’s facebook extract data from music or video link?
i read in facebook developer and see we use OPEN GRAPH Api
view source of a video youtube ,i see attributes property=”og:image” and og:video ,other some video’s site not have but why’s facebook extract data from all video link is right ?
Thanks u for any suggest .
sorry for my bad english .

Reply

Hyder February 1, 2012 at 3:25 am

Hello , facebook extract data from the webpage title,and meta tags . For video site such as youtube , i’m pretty damn sure it uses youtube api . Check out this post about how to extract youtube video image as facebook does .I hope i answered your question .

Reply

Thomas February 8, 2012 at 12:04 am

Can you please explain the insert.php. Please reply.

Reply

Thomas February 8, 2012 at 10:46 pm

or can someone end me the code…it would be a huge help. Thanks.

Reply

Thomas February 11, 2012 at 2:20 am

send not end

Reply

Louie February 14, 2012 at 12:20 am

Can anyone figure out how to make this script works in Internet Explorer 8?

Reply

Federico February 22, 2012 at 4:42 am

Hello, First of all thank you because I saw lots of posts of this kind of code and noone was even close. You made this and I apprecciate it.
It has all I need for my website but If I have a database with all the people in the social network and I am a user who logs in… How can I make to save all that information to a database?
I saw that the file is empty for me to learn more, but can you give me any help please?
once again thanks

Reply

reetpal February 24, 2012 at 2:58 am

i have downloaded the given file and i am having cpanel for my website now where can i put the extracted files….. help me please ……..

Reply

faggio February 25, 2012 at 12:36 am

Hi all Pease help me.What need to write in insert.php?This script very awesome only I dont know how to complete this wall.

Reply

fede March 3, 2012 at 11:26 pm

Hello man how are u
The file that you did not fill
insert.php !
I have done this from below:

I have my database with an ID and a text, and where it says ‘hola’ I have to put what the user has written

please help

thank you !

Reply

phaelix March 20, 2012 at 12:09 am

Quick question, I’m not really seeing it here but has anyone figured out how to auto update the end user screen when another user adds something? like the way facebook does it now? I am working on a simple “ledger” project that 2 of us are adding information to and I would like to make it so that when 1 of us adds information it shows up to the other so we dont put in duplicate information. Any help would be appreciated.

Reply

Hyder March 20, 2012 at 5:57 am

You should make an ajax call every ‘X’ seconds to fetch for new data .My previous article should definitely help you to do this task .
http://youhack.me/2010/04/13/auto-load-page-content-every-x-second-using-jquery/

Reply

sw00ch April 24, 2012 at 11:48 am

Hey there, this is nice script, but i have a little question…
How can i send multiple data to insert.php…am i doing right?

var multiple = {“message_wall” : wall_post, “usrtext” : textarea_content, “siteimg” : image_html, “siteurl” : siteurl, “sitetitle” : sitetitle, “sitedesc” : sitedesc};

var message_wall = $(‘#message_wall’).attr(‘value’);
$.ajax({
type: “GET”,
data: multiple,
url: “insert.php”,
success: function () {
$(‘ul#posts’).prepend(wall_post);
}
});

if i do that way, it seems to be work only for textarea content and it shows image tag (there is no image typed in text area) shown in database ( ), but if i post address link, it dosn’t show me data and nothing appear in database…

Reply

sw00ch April 24, 2012 at 12:22 pm

ok, its dont show image tag anymore in database if i type text in textarea, i added some lines:
if (current_image_url = ‘undefined’) {
var image_html = ”;
}

but its still dont send data to database if i’m try to fetch link…

Reply

sw00ch April 24, 2012 at 12:47 pm

anyway, i finally got it work, its sends all other data now, but only image link is src=’undefined’

Reply

sw00ch April 25, 2012 at 10:52 am

current_image_id turns to NULL, i dont know why

Reply

sw00ch April 24, 2012 at 6:02 pm

weird, fetch preview shows image, if i post that, it shows undefined… hmm

Reply

MhdAlwan July 4, 2012 at 6:25 pm

Hey Guys,
thnx for this beautiful tutorial
i’ve done it like this

$.ajax({
type: “GET”,
url: “add.php”,
data: “message_wall=” + wall_post,
success: function () {
$(‘ul#posts’).prepend(wall_post);

This is the add.php :

$urls = $_GET['message_wall'];
mysql_query(“insert into tb_site(urls) values (‘$urls’)”);

but the database store it like :

<a href="

can anybody tell me where is the problem?
thnx alot.

Reply

mattia July 19, 2012 at 12:41 pm

Hi, great tutorial. Thanks
I have just a big problem. It works only with a .html extension and I need to use a .php
I’m developing locally using mamp pro.
any reason ? maybe a server configuration problem?

Reply

nad August 2, 2012 at 2:28 am

can you please give the code to insert the data im MYSQL Table because now its useless to me

Reply

Travis August 4, 2012 at 11:25 am

dear Hyder,

When I refresh the page everything that has been posted gets removed.
How to make the post permanent

Reply

cali October 31, 2012 at 7:53 am

save the caonent in a database or a file and make a call to load the content during the page (re)load

Reply

Ehsan Nawaz September 28, 2012 at 12:06 pm

Can you develop a script like facebook fan pages

Reply

cali October 31, 2012 at 7:51 am

Very nice, but i think it’s for exemple purpose only and not to use in production as that is not secure and not protected against fox.
very simple exemple type alert(hummm, where is my duff beer ??); in the comment you’ll let the script be ececuted.

After to answer on some comment in insert.php it’s simple to get the var content with a get but fell free to use HtmlPurifier before to inject this content in database, the simpliest way to clean the content.

Instead it’s a very nice idea to propose this kind of tutorial freely :) thank you very much for that, for someone like me who is not so good in js, it’s a very very helpfull tutorial thanks again :)

Reply

Leave a Comment

Previous post:

Next post: