Facebook Ajax Connect

Couple of months ago, I was in an interesting problem. I had to find a good solution because it was a LOGIN procedure. I needed to perform a facebook ajax connect. Users would use a Facebook Ajax connect to login into a web application without a page reload.

A logical idea of Facebook Ajax Connect:
  • User will login via Facebook
  • Send Ajax Request to inform the server of the user’s login
  • Record user’s presence on the server

So, now we are in a need to tell the server that we have logged in. How to acheive this?

Facebook Ajax Connect considerations:
  • what will the request to the server contain?
  • How will the server be sure about your identity?
  • How will the server know that this user has a proper facebook account?
  • How to remember a user as an authenticated client on the server?

Remember, simply sending the user Facebook Id is not enough. Opening Google Chrome, seeing the request and learning how the request goes can open holes. The query parameters can learn and false request can be sent.

Google Chrome Network Status

A solution for Facebook Ajax Connect:
  • User will login via Facebook by clicking on “Facebook Connect”
  • Retrieve the access token and facebook user Id using JavaScript SDK
  • Send a XMLHttpRequest to server
  • Use a technique on server-side to make server aware that a particular user has been authenticated

So, now, you know that along with the Facebook Id, you need to an access token. The access token is unique and obtained only by a proper facebook user. The access token is used to verify the Facebook Id on the server

To sum up, this is how Facebook Ajax Connect works:

1. Get the Facebook Id and the access token of the user

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
// the user is logged in and has authenticated your
// app, and response.authResponse supplies
// the user's ID, a valid access token, a signed
// request, and the time the access token
// and signed request each expire
var uid = response.authResponse.userID;
var accessToken = response.authResponse.accessToken;
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook,
// but has not authenticated your app
} else {
// the user isn't logged in to Facebook.
}
});

Code above obtained here

2. Make an XMLHttpRequest and send the details to server (using jQuery)

1
2
3
4
$.post("loginURL", { id: "idGoesHere", accesstoken: "tokenGoesHere" },
function(data) {
/*process the response here */
});

3. Now suppose the loginURL ultimately fall on the function below:

1
2
3
4
5
6
7
8
9
10
11
12
13
public function authenticateFacebookUser($FacebookId,$token)
{
$userDetails=json_decode(file_get_contents("https://graph.facebook.com/me?access_token=".$token));
if ($userDetails->id==$FacebookId) {
/* here, you are sure the client is a proper facebook user
the user can be an existing user or new user
so, use u're ORM or sql to query the database and perform the
procedures needed
*/
return 1;
}
return 0;
}

U got a better idea, please share it, :)

Sort table, PHP or JavaScript ?

When fetching data from the database, several times we need to display the name as a table. Suppose we have a table where we need to display the IDs and Name of students.

Id Name
4 Noor
1 James
3 David
2 Abu

Now suppose, we want to sort the table based on the Id when the user clicks on the column. If we assume that this data comes from a database, such as MySQL, we can simple when writing the SQL (or using an ORM Method) sort the results. Well, if using SQL, it might be something like “ORDER by id ASC”. However, it would require a further request to the server.

One can argue that OK, we’ll write the SQL assuming that the user would always want the results to be sorted by id. But now, what if the user wants to sort the results by Name. This would require a request to the user to get a new resultset from the database sorted by “Name”.

Anyway, the best way to do it is on the client-side. Numerous plugin for doing this exist, check them at here but the one I’ve chose which is very simple and free from crazy configuration.

Ok, to use the plugin, I only need to ensure the following:

1. My Table must be structured using thead and tbody
2. Assign your class the classname “sortable” to your table
3. Attach the javascript file to your doc

See the example now with the plugin

Id Name
4 Noor
1 James
3 David
2 Abu



Just click on the column header and notice the difference. You can more information about the plugin here

Simulating Session in WordPress through Cookies

Sometimes, when developing plugins for wordpress, you would want to do something differently based on the client request. Normally, we might be tempted to use PHP SESSION which I don’t think is a good solution. I fall in a similar situation where i was having to display something based on the client request.

So, lets consider a scenario. A user is displayed a page containing a drop-down list. The user has to select a car from the drop-down list. In the beginning, only the drop-down list should be displayed because the user has not yet select anything. But later, when the user select a car, and if he returns to that page, the picture of the car should be displayed. So, the question is, how does the server know that the user has already selected a car or not??

My solution, which I don’t know if it is the best, is to create a cookie of the id of the selected car on the client and to check this cookie on the server.

So, on the client, I should have the following functions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
<?php
add_action('wp_head', 'my_action_javascript');
function my_action_javascript() {
?>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript" >

                 //function setCookie, getCookie from http://www.w3schools.com/js/js_cookies.asp
        function setCookie(c_name,value,exdays)
        {
            var exdate=new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
            document.cookie=c_name + "=" + c_value;
        }
        function getCookie(c_name)
        {
            var i,x,y,ARRcookies=document.cookie.split(";");
            for (i=0;i<ARRcookies.length;i++)
            {
              x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
              y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
              x=x.replace(/^\s+|\s+$/g,"");
              if (x==c_name)
                {
                return unescape(y);
                }
              }
        }       
        function setSelectedId(){
            var selected_id=$("#selected_id").val();
            setCookie("selected_id",selected_id,1);
            return true;
        }

    </script>
<?php
}
function showCar()
{
?>
        <form action="" method="POST" onSubmit="return setSelectedId();">   
            Choose your Car:
            <select id="selected_id">
              <option value="volvo">Volvo</option>
              <option value="saab">Saab</option>
              <option value="mercedes">Mercedes</option>
              <option value="audi">Audi</option>
            </select>
                        <input type="submit" value="Choose" />
        </form>
        <br/>
        <script type="text/JavaScript">$("#selected_id").val(getCookie("selected_id"));</script>
<?php
        if (!$_COOKIE['selected_id']){
            return "";
        }
        $id=$_COOKIE['selected_id'];
        return getLink($id);
}
?>

Description of functions:

  • setCookie,getCookie only set a value in the cookie.
  • setSelectedId is called when the user submit the form. It uses setCookie to insert the selected_id in the cookie
  • When the request is made, the server check if cookie has been set (!$_COOKIE['selected_id']) and if yes, it returns a the link based on the id. getLink is a custom function which you must define based on the action you want to take if the user has selected something

In case you have a solution, be it better or anything, please share it :-)