简体   繁体   中英

POSTing an Array from a Facebook Graph API response by AJAX to a PHP script

Hello_I'm making a Facebook Canvas App and I'm trying to get the Invite Friends process working. I have my multi-friend selector made, and it's sending invites correctly, but I now want to reward the inviter whenever an invited person adds the app.

I think the correct way to do this is to run a check whenever a new user begins using the app. I'm trying to do this by querying Facebook's Graph API to see if the new user has an apprequest for my app, if they do, then I want to find out the ID (or IDs) of the person/people who have sent this new user an invite request.

To try to work out how to do this, I had 3 invites (from 3 different accounts) sent to one account, and now if I log in as the invite receiver and then query Facebook's Graph API console with this code: /v2.3/me/apprequests?fields=from,id it returns this:

{"data": [
    {
      "from": {
        "id": "1234526161534",
        "name": "John Doe"
      },
      "id": "14677152342565_827362417384",
      "created_time": "2015-05-19T21:35:11+0000"
    },
    {
      "from": {
        "id": "4777221325314",
        "name": "Jane Doe"
      },
      "id": "1683273626362_827362417384",
      "created_time": "2015-05-19T20:50:14+0000"
    },
    {
      "from": {
        "id": "1015521200905293",
        "name": "Di Do"
      },
      "id": "1251333932735_827362417384",
      "created_time": "2015-05-19T20:50:08+0000"
    }
  ]}

So it's showing me that 3 different people have sent me apprequests for the app. It's giving me their IDs, their names, and a unique request ID concatenated with the Invited person's ID.

Currently, I'm able to grab the sender IDs individually, but I want to send them as an array to a PHP script by AJAX, and then I want to insert them into my database using a PDO prepared statement if that's possible.

This is my current code:

/* making the API call */
FB.api(
    'me/apprequests?fields=from,id',
    function (response) {
     if (response && !response.error) {

   var requestid = response.data[0].from.id;
   var requestid1 = response.data[1].from.id;
   var requestid2 = response.data[2].from.id;

   console.log(response.data[0].from.id);
   console.log(response.data[1].from.id);
   console.log(response.data[2].from.id); 

    $.ajax({
         url: 'reward.php',
         data: {'requestid' : requestid,
               'requestid1' : requestid1,
               'requestid2' : requestid2},
        type: "POST",
        success: function(response){
          if(response==1){
             alert("Reward Applied!");
                 }
          else{
             alert("Reward Failed!");
                 }
            }
       });
      }
    }
);

While I am able to send the IDs to the PHP file as separate variables var requestid, var requestid1, var requestid2 and then Insert them individually, this isn't a good method to use, as the number of request IDs will vary, so instead of sending each of them as individual variables, I think I need to send them as an array, but I'm unsure of how to do this.

My current PDO Insert Transaction is this:

reward.php

<?php
$servername = "myservername";
$username = "myusername";
$password = "mypassword";
$dbname = "mydbname";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    // set the PDO error mode to exception
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $conn->beginTransaction();

    // Defining the three request IDs
    $requestid = $_POST['requestid'];
    $requestid1 = $_POST['requestid1'];
    $requestid2 = $_POST['requestid2'];

    // Insert first request ID
    $stmt = $conn->prepare("INSERT INTO requestids (requestid) VALUES (:requestid)");
    $stmt->bindParam(':requestid', $requestid);
    $requestid = $_POST['requestid'];
    $stmt->execute();

    // Insert second request ID
    $stmt = $conn->prepare("INSERT INTO requestids (requestid) VALUES (:requestid1)");
    $stmt->bindParam(':requestid1', $requestid1);
    $requestid = $_POST['requestid1'];
    $stmt->execute();

    // Insert third request ID
    $stmt = $conn->prepare("INSERT INTO requestids (requestid) VALUES (:requestid2)");
    $stmt->bindParam(':requestid2', $requestid2);
    $requestid = $_POST['requestid2'];
    $stmt->execute();

    $conn->commit();
    echo "1";
    }
catch(PDOException $e)
    {
    echo "Error: " . $e->getMessage();
    }
$conn = null;
?>

This won't work if a person has requests from more than 3 people, it really needs to be an Array instead. I'm pretty new to PDO and Transactions, and don't have any experience working with Arrays. I'd really appreciate any help at all with this, thanks so much in advance!

@Emily With respect to your updated questions, its easy to achieve. Pass the array itself to ajax post like this

$.ajax({
     url: 'reward.php',
     data: {'requestids' : response.data},
    type: "POST",
    success: function(response){
      if(response==1){
         alert("Reward Applied!");
             }
      else{
         alert("Reward Failed!");
             }
        }
   });
  }
}

Then in your PHP loop through requestids array and generate mysql query to insert all records at once like this

$sql= "INSERT INTO requestids (requestid) VALUES "; 
foreach($_POST['requestids'] as $requestId){
       $sql.="($requestId)";
}

I am sure you can easily convert this simple query into a PDO statement

Yes you are not sending data correctly.

Try this

data: {'senderid' : response.data.from.id}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM