Insert to database after user has shared content on facebook

与世无争的帅哥 提交于 2020-01-07 06:24:09

问题


I am working on a Facebook tap app. In the app the user selects an item page and in there he can write a comment about the item. After he has written his comment he clicks a button that opens up a facebook share dialog and the user comment is in the dialog box.

What I want to accomplish is inserting the comment to a database when the user clicks share and if he clicks cancel nothing happens.

Here is the function that I use to open up the dialog:

function FacebookPostToWall()
    {
    var comment = document.getElementById('comment').value;;
    FB.ui({
        method: 'feed',  
        link: 'http://linkfortheitem.com',
        name: "Name of the item",
        caption: "Caption for the item",
        description: '' + comment,
        picture: '',
        message: ''
        },
        function(response){
            if(response && response.post_id) {
                alert('user has shared');
            }else {
                alert('user has not shared');
            }       
    });
    }

So my question is, is there a way to call my php function that inserts the comment to database inside the callback function?


回答1:


You can use ajax to send the comment to a php script that can retrieve the parameter via $_POST['comment'] (or whatever you decide to call the parameter). If you're using plain old javascript, first example shows you something that would use to send an ajax request with your comment variable. The second example which is ridiculously easier uses jQuery, which is most definitely worth learning. Both of these would go immediately after (or replace) alert('user has shared'); in your script, so that the call is sent only if the facebook comment was successfully posted.

Let me know if this was what you were looking for and if you have any questions :)

Javascript example

var xmlhttp;
if (window.XMLHttpRequest)
{
    // code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
}
else
{
    // code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert('Comment sent to PHP, and the response is: '+xmlhttp.responseText);
        }
    });
xmlhttp.open("POST","yourphpscript.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("comment="+comment);

jQuery Example

$.post('yourphpscript.php', { 'comment': comment }, function(response) {
        alert('Comment sent to PHP, and the response is: '+response);
    });


来源:https://stackoverflow.com/questions/16821320/insert-to-database-after-user-has-shared-content-on-facebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!