facebook registration plug-in Async Validation - facebook

I am trying to impliment facebook registration pluging from last three weeks, to check the username avaiablity I am using jquery and JSON, accourding to this http://developers.facebook.com/docs/plugins/registration/advanced/ guide, with the following code I am able to send username to my server that is a a c# page to check either it is available or not, but how to tell back?
Problem is this I don’t know how to send message from c# page to the calling scritp, and how to use read it here.
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#appId=134552926621797&xfbml=1"></script>
<fb:registration redirect-uri="http://dev2.urecommendme.com/test3.aspx"
fields='[{"name":"name"},
{"name":"username","description":"Username","type":"text"}]'
onvalidate="validate_async"></fb:registration>
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
function validate_async(form, cb) {
$.getJSON('http://dev2.urecommendme.com/test01.aspx?username=' + form.username + '&callback=?',
function (response) {
if (response.error) {
// Username isn't taken, let the form submit
cb();
}
alert(cb.toString());
});
}
</script>
</body>
Returning message should be something like this
<script src="http://graph.facebook.com/shahidgfdgd?callback=jsonp1307613510850">
jsonp1307613510850({
"error": {
"type": "OAuthException",
"message": "(#803) Some of the aliases you requested do not exist: shahid"
}
});
</script>
This is my third week to implimenting it please guide me so I can complete this task, thanks.

FB registration page should look like as follows
<body>
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js#appId=134552926621785&xfbml=1"></script>
<fb:registration redirect-uri="http://dev2.urecommendme.com/test3.aspx"
fields='[{"name":"name"},
{"name":"username","description":"Username","type":"text"}]'
onvalidate="validate_async"></fb:registration>
<script src="http://code.jquery.com/jquery-1.4.4.min.js"></script>
<script>
function validate_async(form, cb) {
$.getJSON('test02.aspx?username=' + form.username,
function (response) {
if (response.error) {
// Username isn't taken, let the form submit
cb();
}
cb({ username: 'That username is taken' });
});
}
</script>
</body>
Note how I mentioned server file name (it is without full URL, as both files were on same root dir) in validate_async(form, cb) function
$.getJSON('test02.aspx?username=' + form.username,
Test02.aspx page should look like as follows
Note no html, body or head tags in test02.aspx
(Test02.aspx.cs) should look like
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Newtonsoft.Json;
using System.Text;
public partial class test02 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e1)
{
StringBuilder JSON = new StringBuilder();
//validate from your database and execute one of the following two lines.
JSON.Append("{\"error\":\"Exist\"}"); // username is taken
// JSON.Append("{\"anything\":\"Not Exist\"}");
Response.Write(JSON.ToString());
Response.End();
}
}

Related

JSON object parsing error using jQuery Form Plugin

Environment: JQuery Form Plugin, jQuery 1.7.1, Zend Framework 1.11.11.
Cannot figure out why jQuery won't parse my json object if I specify an url other than a php file.
The form is as follows:
<form id="imageform" enctype="multipart/form-data">
Upload your image <input type="file" name="photoimg" id="photoimg" />
<input type="submit" id ="button" value="Send" />
</form>
The javascript triggering the ajax request is:
<script type="text/javascript" >
$(document).ready(function() {
var options = {
type: "POST",
url: "<?php $this->baseURL();?>/contact/upload",
dataType: 'json',
success: function(result) {
console.log(result);
},
error: function(ob,errStr) {
console.log(ob);
alert('There was an error processing your request. Please try again. '+errStr);
}
};
$("#imageform").ajaxForm(options);
});
</script>
The code in my zend controller is:
class ContactController extends BaseController {
public function init() {
/* Initialize action controller here */
}
public function indexAction() {
}
public function uploadAction() {
if (isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST") {
$image = $_FILES['photoimg']['tmp_name'];
$im = new imagick($image);
$im->pingImage($image);
$im->readImage($image);
$im->thumbnailImage(75, null);
$im->writeImage('userImages/test/test_thumb.jpg');
$im->destroy();
echo json_encode(array("status" => "success", "message" => "posted successfully"));
}
else
echo json_encode(array("status" => "fail", "message" => "not posted successfully"));
}
}
When I create an upload.php file with the above code, and modify the url from the ajax request to
url: "upload.php",
i don't run into that parsing error, and the json object is properly returned. Any help to figure out what I'm doing wrong would be greatly appreciated! Thanks.
You need either to disable layouts, or using an action helper such as ContextSwitch or AjaxContext (even better).
First option:
$this->_helper->viewRenderer->setNoRender(true);
$this->_helper->layout->disableLayout();
And for the second option, using AjaxContext, you should add in your _init() method:
$ajaxContext = $this->_helper->getHelper('AjaxContext');
$ajaxContext->addActionContext('upload', 'json')
->initContext();
This will disable automatically disable layouts and send a json header response.
So, instead of your two json_encode lines, you should write:
$this->status = "success";
$this->message = "posted successfully";
and
$this->status = "fail";
$this->message = "not posted successfully";
In order to set what to send back to the client, you simply have to assign whatever content you want into view variables, and these variables will be automatically convert to json (through Zend_Json).
Also, in order to tell your controller which action should be triggered, you need to add /format/json at the end of your URL in your jQuery script as follow:
url: "<?php $this->baseURL();?>/contact/upload/format/json",
More information about AjaxContext in the manual.
Is the Content-type header being properly set as "application/json" when returning your JSON?

Customize google cloud print button function

Currently i am using the google cloudprint button for my site
<script src="//www.google.com/cloudprint/client/cpgadget.js"></script>
<script defer="defer">
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(document.getElementById("custom_print_button"));
gadget.setPrintDocument("url", "Cloud Print test page",
"http://www.google.com/cloudprint/learn/");
</script>
I want to send an email when I hit the print button, is this possible?
No problem at all... just attach an onclick handler to the print button, or bind the click with jQuery and call a function to do your email. I used it to create a document with Ajax before it was printed:
<script>
function printIT() {
jQuery.ajax({
url: "print_this.php",
context: document.body,
success: function(responseText) {
alert("Document sent!");
return false;
}
});
}
</script>
<button id="print_button_container" class="ui-link" onclick="printIT();"></button>
<script src="//www.google.com/cloudprint/client/cpgadget.js">
</script>
<script defer="defer">
var gadget = new cloudprint.Gadget();
gadget.setPrintButton(document.getElementById("print_button_container"));
gadget.setPrintDocument("url", "My Document", "http://www.yourpath.com/yourdoc.html");
</script>
Simplified version... not tested but should work :)

FBJS streemPublish not working

In my application I want post a text message in facebook wall streemPublish but it is not working, can anyone tell me what i did wrong else guide me a good working tutorial,
also the below code does not showing any error....
Here is my code ...
<body>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php" type="text/javascript"></script>
<script type="text/javascript">
function publish() {
FB_RequireFeatures(["Connect"], function() {
FB.Facebook.init('113700398662301', 'xd_receiver.htm');
FB.ensureInit(function() {
var message = 'this is message';
var action_links = [{ 'text': 'Vote for Bill The Aircraft Carrier!', 'href': 'http://spayday.factor360.com/contest.html?page=viewInd&id=48082&contestId=2'}];
FB.Connect.streamPublish(message, action_links, null, "Share your support for Bill The Aircraft Carrier!", callback, false, null);
});
function callback(post_id, exception) {
alert('Wall Post Complete');
}
});
}
</script>
</body>
<p>Stream Publish Test</p>
Post a story
</html>
The code looks a little dated. Check this for updated info on stream publishing
https://developers.facebook.com/docs/reference/javascript/FB.ui/
and this for setting up your FB init.
https://developers.facebook.com/blog/post/525/

how to get user facebook logged in status

i am working on a small application in asp.net, c# in my website, which shows user is logged into facebook in the same browser. Which means in the browser if user open my website(in same browser if user is not logged into facebook) a popup should show that user is not loggedin. if the user logged into facebook then a popup should come in my website showing that loggedin after refresh of my page.
in a page refresh i just want to alert the login status of user...
i had the xd_receiver.htm file in my root directory and
this script in header and
Untitled Page
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php"
type="text/javascript"></script>
<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js#appId=142899075774321&xfbml=1"></script>
<script type='text/javascript' language='javascript'>
window.onload = function() {
FB.init('142899075774321', 'xd_receiver.htm');
alert("Before ensureInit");
FB.ensureInit(function() {
alert("After ensureInit");
FB.Connect.ifUserConnected(onUserConnected, onUserNotConnected);
});
};
function onUserConnected() {
alert('connected!');
window.location.reload();
}
function onUserNotConnected() {
alert('not connected');
}
</script>
this script in body....
But this code is not working.....
how should i solve this......
thanks in advance
Try this for the html head part:
<title>Facebook Status</title>
<script src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US"
type="text/javascript">
</script>
<script type="text/javascript">
var api_key = 'Your app id';
var channel_path = 'xd_receiver.htm';
//alert(document.referrer);
FB_RequireFeatures(["XFBML"], function() {
// Create an ApiClient object, passing app's API key and
// a site relative URL to xd_receiver.htm
FB.Facebook.init(api_key, channel_path);
FB.Connect.get_status().waitUntilReady(function(status) {
switch(status) {
case FB.ConnectState.connected:
document.getElementById("divstatus").innerHTML ="LOGGED IN AUTHORIZED";
break;
case FB.ConnectState.appNotAuthorized:
document.getElementById("divstatus").innerHTML ="LOGGED IN NOT AUTHORIZED";
break;
case FB.ConnectState.userNotLoggedIn:
document.getElementById("divstatus").innerHTML ="NOT LOGGED IN";
break;
}
});
});
</script>
Then use this for the html > body part:
<div id="divstatus">
</div>

How do I check if a user is a fan of my facebook page on my website?

I want to check if my users are fans of my facebook page. I think something like this should do it:
<script type="text/javascript" src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php/en_US"></script>
<script type="text/javascript">FB.init("my api key","xd_receiver.htm");</script>
<script type="text/javascript">
//<![CDATA[
FB_RequireFeatures(["Api"], function(){
var api = FB.Facebook.apiClient;
api.pages_isFan(PAGE_ID,gigyaUser.FACEBOOK_USER_ID,function(response){
alert(response);
});
});
//]]>
</script>
However, for some reason I keep getting null even though the user is in fact a fan of the page. Am I missing something?
I think you almost had that correct.
This snippet works great for me.
assumes:
1. fanPageUID = the fan page's uid
2. and user UID is the UID of the user
3. (and you have an active session)... this may be the hard part, but not part of this question.
function checkifFan() {
FB_RequireFeatures(["Api"], function(){
var api = FB.Facebook.apiClient.pages_isFan(fanPageUID,userUID,function(response){
if (response==false) {
setTimeout('checkifFan()', 300); //every 300ms check if they have pressed fan
}
else {
location.reload();
}
});
});
}
You can also check that a user is a fan of your website by the following script:
<fb:login-button scope="user_likes">
Grant Permissions to Allow access to Likes
</fb:login-button>
<button onclick="checkDoesLike()">Check if user Likes the Page</button>
<h1>Like this Application's Page</h1>
<fb:like-box profile-id="your_page_id"></fb:like-box>
<script>
window.checkDoesLike = function() {
FB.api({ method: 'pages.isFan', page_id: 'your_page_id' }, function(resp) {
if (resp) {
Log.info('You like the Application.');
} else {
Log.error("You don't like the Application.");
}
});
};
</script>