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, :)

Dynamically create Html using JavaScript

Don’t wrap HTML in JavaScript code, Keep them seperate else they’ll fight and you’ll get beaten

Today, the trend is “Mashups”, we take data from this web service and that web service and make something beautiful. We normally do this in javaScript, making xmlHTTPRequest. On obtaining a response. we then dynamically use JavaScript to create HTML. However, I’ve notice that many developers tend to mix JavaScript and HTML. By doing so, I think they complicate the codes. Representing HTML codes as JavaScript Strings make them prone to JavaScript errors. Also, they might end in making their HTML not as per W3C recommendation due to single and double quotes.

Suppose I’m getting the details of laptops from an xmlHTTPRequest. Then, in JavaScript, I’m having to generate a layout to display the laptop’s details.

I get the laptop brand name, screen size, processor capacity, RAM , Hard Disk details then a picture URL for the laptop and i need to write JavaScript to build an HTML layout and display the content in it.

Codes to dynamically use JavaScript to create HTML

1. The bad practice, Mixing the codes(this is what i think)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
$.get("URL_to_get_details",function(laptops)
{
      /*here i need to write the code to display the laptop
      suppose the laptop is json encoded */
      laptops=$.parseJSON(laptops); 
      /*parse the json encoded data with jQuery*/
      var i=0,html="";
      while (i<laptops.length){
           currentLaptop=laptops[i];
           /*build the HTML for the laptops*/
           html+="<div><span>Brand Name:"+currentLaptop.brandName+"</span><span>"+.....+
                 "<img src= "\"+currentlaptop.URL+"\" alt=\"create HTML using JavaScript\">";
      }
      /* create the newly built layout */
      ("#laptopContainer").html(html);
});

What I’m doing in the above code is to wrap HTML in JavaScript. I’m representing HTML as a JavaScript String. I’m having to be cautious due to JavaScript String quotes and HTML quotes. I really don’t think its good. When you start to have lots of HTML, you’ll become crazy mingling with HTML syntax and keeping JavaScript free from errors at the same time.

So this is what i propose. Completly isolate HTML and JavaScript codes. Instead of wrapping HTML into JavaScript, declare a prototype of the layout in HTML and hide it in your DOM.

2. The good practice, Seperating the codes

Normally, I do it like this because i think it’s better. If you have a better solution please share it :)

To Use JavaScript to create HTML:

  • Declare an HTML Layout prototype in the DOM with dummy variables
  • Use raw JavaScript or jQuery to retrieve the HTML codes from DOM as string
  • Obtain variable from their sources
  • use JavaScript to replace dummy variable with apporiate values(e.g use .replace)
1
2
3
4
5
6
7
8
9
10
<div id="prototype" style="display:none">
    <div>
       <span>Brand Name: varBrandName</span>
       <span>Screen Size: varScreenSize</span>
       <span>Processor Capacity: varProcessorCapacity</span>
       <span>RAM:varRAM</span>
       <span>Hard Disk Details: varHardDisk</span>
       <span><img src="varPictureSrc" alt="img" /></span> 
   <div>
</div>

now, in the HTML code above, you’ll see var. These will be actually be replaced by the actual values in JavaScript.

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
$.get("URL_to_get_details",function(laptops)
{
      /*here i need to write the code to display the laptop
      suppose the laptop is json encoded */
      laptops=$.parseJSON(laptops); /*parse the json encoded data with jQuery*/
      var i=0,html="";
      while (i<laptops.length){
           currentLaptop=laptops[i];
         
           /* get the content of the prototype */
           currentHTML=("#prototype").html();
   
           /* replace the dummy values in the HTML */
           currentHTML=currentHTML.replace("varBrandName",laptops[i].brandName);
           currentHTML=currentHTML.replace("varScreenSize",laptops[i].screenSize)
           currentHTML=currentHTML.replace("varProcessorCapacity",laptops[i].processor);
           currentHTML=currentHTML.replace("varRAM",laptops[i].RAM);
           currentHTML=currentHTML.replace("varHardDisk",laptops[i].hardDisk);
           currentHTML=currentHTML.replace("varPictureSrc",laptops[i].pictureSrc);
     
           /* build the HTML for the laptops */
           html+=currentHTML;
      }
      /* create the newly built layout */
      ("#laptopContainer").html(html);
});

SO, as you see, I’ve retrive the HTML from the declared prototype and then generated the layout replacing the dummy variables with the value I’ve obtained from xmlHTTPResponse. At any time, I did not wrap the HTML in JavaScript. The prototype I declared is pure HTML as per W3C recommendation.