Ajax Code to run PHP query After Facebook Like Button is Clicked
I have the PHP below on a file called fblike.php. On another file, I have the Facebook Like button. The Like button functions. I would like to run the code below when the Facebook Like button is clicked.
I know that FB.Event.subscribe('edge.create', function(response) {}
is supposed to run whenever the Like button is clicked. I know that I am probably supposed to use Javascript and maybe Ajax to cause the PHP on fblike.php to run.
But after multiple tries, I can't get it to work. What is the specific Ajax开发者_如何学编程 code that I could include within the Facebook Event? Do I need to do anything to the Like button code to allow the Facebook Event to work?
$submissionid = $_POST['submissionid'];
$uid = $_POST['uid'];
mysql_connect("server", "username", "password") or die(mysql_error());
mysql_select_db("database") or die(mysql_error());
$q = "INSERT INTO fblikes VALUES (NULL, '$submissionid', '$uid', NULL)";
$r = mysql_query($q);
if($r)
{
echo "Success!";
}
elseif(!$r)
{
echo "Failed!";
}
Try something like this:
FB.Event.subscribe('edge.create', function(response) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST", "path/to/yourscript.php", true);
xmlhttp.send("submissionid="+response.submissionid+"&uid="+response.uid);
});
Essentially, you'd have to pull the variables out of the response and send them via a POST-method AJAX request to your PHP script.
You can optionally expand the function() to check for success:
if(xmlhttp.responseText == "Success!")
精彩评论