Insert to database after user has shared content o

2019-09-16 16:52发布

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条回答
看我几分像从前
2楼-- · 2019-09-16 17:32

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);
    });
查看更多
登录 后发表回答