I'd like to track when people click the Facebook "Like" button on my website.
I have a small script set-up, but it doesn't seem to work and I'm out of ideas of what it could be. Any suggestions? The AppID is correct and this script is just for testing so don't mind the lack of validation:
index.html
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<title>FB Like Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="fb-root"></div>
<script type="text/javascript">
$(document).ready(function() {
window.fbAsyncInit = function() {
FB.init({appId: 'x', status: true, cookie: true, xfbml: true});
FB.Event.subscribe('edge.create', function(href, widget) {
$.ajax({
type: 'POST',
url: 'like-sql.php',
data: ({liked : 1})
});
});
FB.Event.subscribe('edge.remove', function(response) {
$.ajax({
type: 'POST',
url: 'like-sql.php',
data: ({liked : 0})
});
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = 'http://connect.facebook.net/nl_NL/all.js#appId=x&xfbml=1';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
});
</script>
<fb:like href="http://x.x.x" layout="button_count" show_faces="true" width="500"></fb:like>
</body>
</html>
like-sql.php
<?php
$status = $_POST['liked'];
mysql_query("UPDATE `fb_like` SET umk_like = $status WHERE user_id = '3432'");
?>
I'm new to this whole jQuery ajax thingy, so I don't really know how I should debug this. Any suggestions are welcome :)
EDIT: Nevermind guys I got it.
I'm testing this in an external file, where I don't have jQuery included by default ;) I can't believe it took me this long to figure it out, lol. Thanks anyway for all the help!
Try to alert() something in the event listener itself, to see if it is subscribed correctly
FB.Event.subscribe('edge.create', function(href, widget) {
alert('Like caught !');
$.ajax({
type: 'POST',
url: 'like-sql.php',
data: ({liked : 1})
});
});
and add notify=true to fb:like
<fb:like notify="true" href="http://x.x.x" layout="button_count" show_faces="true" width="500"></fb:like>
I had the same problem with "comment.create", and I solved it by notify="true", and subscribing to "comments.add" ! but I still can't subscribe to "comment.remove"!
Nevermind guys I got it.
I'm testing this in an external file, where I don't have jQuery included by default ;) I can't believe it took me this long to figure it out, lol. Thanks for all the help though!
Related
I've been struggling with this for two hours now and I've narrowed down the issue to a simple test case. I've done plenty of research and finally settled on trying to reproduce the first answer from this question: Set session var with ajax.
When I push this button (lazy html, but that's not where the issue lies):
<html>
<head>
...
<script src="jquery.js"></script>
...
<head>
<body>
....
<?php
var_dump($_SESSION);
?>
<input type="button" class="update">
....
</body>
</html>
This ajax request in jquery.js gets called:
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function() {
console.log("Successful request sent");
}
});
And finally the setSession.php file:
<?php
session_start();
$_SESSION["foo"] = $_POST["bar"];
?>
The success message is printed to the console so I know I'm hitting the right file. Why isn't the session variable getting set? I have php 5.5.2 if that matters at all. Thanks for you help!
Like I suggested on the comments, do this to fix your code:
Reload the page on your success:
success: function() {
console.log("Successful request sent");
location.reload();
}
Make sure you have session_start() in all the pages that uses sessions:
session_start(); //this must be at the top, before you print anything
Might this can help you.
In setSession.php write echo $_SESSION["foo"] = $_POST["bar"];
In your ajax script do
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function(e) {
console.log(e);
}
});
now open browser console (F12). click on your button.update. Check if is there written bar in console.
I am trying to use jQuery's ajax to call a php script onload. This script will return xml from a url web service, parse through it, and then display bits and pieces of it into a div tag when the page loads (onload). I'm okay with php when it comes to using forms, but getting php scripts to run onload is not working for me. Could someone please look through my code and give me your advice? Thanks in advance.
HTML:
<!doctype html>
<html>
<head>
<title>Word of the Day</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="code.js"></script>
</head>
<body>
<h3>Word of the Day: </h3>
<div id="word_day"></div>
</body>
</html>
JavaScript:
$(document).ready(function() {
$(window).load(function() {
$.ajax({
post: "GET",
url: "word_day.php"
}).done(function() {
alert(this.responseText);
}).fail(function() {
alert(this.responseText);
});
});
});
I did not add my PHP code since I was pretty sure that it wasn't the cause of my frustration.
You don't need those two handlers, just one:
$(document).ready(function()
{
$.ajax(
{
post: "GET",
url: "word_day.php"
}).done(function()
{
alert(this.responseText);
}).fail(function()
{
alert(this.responseText);
});
});
As you had it you were trying to create one handler when the handler fired which was never going to work.
Edit:
Your done/fail part should look like:
}).done(function(data)
{
alert(data);
}).fail(function(jqXHR, textStatus, errorThrown)
{
alert(textStatus);
});
I seem to be having a problem with long polling and IE. This is my first foray into long polling, so I set up a simple test to see if I could make it work. It seems to behave just fine with FF and Chrome, but I'm getting different results with IE.
First, here's some code:
HTML/Javascript:
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.3.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.9.2.min.js"></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready(function()
{
(function poll()
{
$.ajax({
url: 'events/alert-data.php',
success: function (e)
{
$('#results').append($('<div>Success: ' + e.text + '</div>').fadeIn(1000));
},
error: function (e)
{
console.log(e);
},
dataType: 'json',
complete: poll,
timeout: 10000
});
})();
});
//]]>
</script>
</head>
<body>
<div id="results">hello</div>
</body>
</html>
PHP:
<?php
$time = time();
while (time() - $time < 5) { }
echo json_encode(array('text' => time()));
?>
In FF/Chrome, I'm seeing expected data:
hello
Success: 1356104196
Success: 1356104201
Success: 1356104217
Success: 1356104222
Success: 1356104227
But in IE it repeats the first Success line infinitely. At least I presume it's infinite as it locks up the browser and won't allow me to scroll.
I'm not sure what I'm doing wrong. Any help would be much appreciated.
Thanks in advance.
The problem with IE would appear to be the consequence of caching, probably by IE itself. This could potentially happen in any browser.
Try adding :
cache: false
to the ajax options.
i want to pass a variable from jquery to php but my code doesnt work .I tried very hard but no luck . When i click the button nothing happens.plz help thank you
one more thing i tried this without passing variable and i use only echo command then it works but when i pass variable nothing happens
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("button").click(function(){
var var_data = 5;
$.ajax({
url: "myscript.php",
data: { var_php_data: var_data },
success: function(data) {
// do something;
alert(data);
}
});
});
</script>
</head>
<body>
<button>Change Content</button>
</body>
</html>
myscript.php contains the following code
<?php
echo $_GET['var_php_data'];
?>
Try wrapping your script in a document ready handler. Also you have a trailing comma (,) after the success callback that you should remove. Also you should use a , instead of ; after the data parameter. Specifying the HTTP verb for your AJAX request might also be useful:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function() {
var var_data = 5;
$.ajax({
url: 'myscript.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
alert(data);
}
});
});
});
</script>
</head>
<body>
<button>Change Content</button>
</body>
</html>
The reason you need to wrap your click registration in a document ready handler is because you put your script inside the <head> section of your markup and the button hasn't yet been loaded by the browser when you attempt to subscribe to its click handler.
You can install Firebug (Firexox plugin), or user something similar for your browser to see real HTTP request and response. If you will post them here it will be more simple to find the problem.
Track request in FireBug. You can find by FB did request success (200) as well as date send by request.
Also, try http://{your_host}>/myscript.php?var_PHP_data=echoText
Addition:
Darin Dimitrov described the problem right way
I need to get all statistics from a Youtube channel so that I can create a document using PHP containing all of the data.
I want information such as the dates the video was viewed, if it has been liked, if it has been blogged and so on.
Is it possible to do this?
Thanks
Please see the sample code below for how you can do some of this. You can find a basic demo here. As seen, you do not necessarily need to write any PHP code to do this. More details are available in developer documents.
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("body").append("<div id = 'data'><ul>jffnfjnkj</ul></div>");
var dataContainer = $("#data ul");
$.ajax({
url:'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?alt=jsonc&v=2&callback=?',
dataType: "jsonp",
timeout: 5000,
success: function(data){
$.each(data.data.items,
function(i, val) {
if (typeof(val.player) !== 'undefined' && typeof(val.title) !== 'undefined') {
dataContainer.append('<li>'+val.title+'</li>');
}
});
}
});
});
});
</script>
</head>
<body>
<h2>Header</h2>
<p>Paragraph</p>
<p>Paragraph.</p>
<button>Click me</button>
</body>
</html>