title: Login with Facebook while writing to a MySQL database in AJAX and PHP
body: <p>For the past week I have been trying to use the login with Facebook API as well as learn a bit more about MySQL. With the help of a few sources I have successfully done that. However I am having to now combine those two projects into one project using AJAX (as I don't want to launch separate pages, but rather to stay in the same page.</p>
  
  <p>Here is my code for the MySQL, as it stand right now it is perfect with the exception that it goes to script.php to run (I need to convert this to AJAX, I believe):</p>
  
  <pre><code>    &lt;!doctype html&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;meta charset="UTF-8"&gt;
  &lt;/head&gt;
  &lt;body&gt;
    &lt;form action="script.php" method="post"&gt;
  &lt;p&gt;first name:
    &lt;input name="namefirst" type="text" id="namefirst" maxlength="35"&gt;
  &lt;/p&gt;
  &lt;p&gt;last name:
    &lt;input name="namelast" type="text" id="namelast" maxlength="50"&gt;
  &lt;/p&gt;
  &lt;p&gt;
    &lt;label for="textarea"&gt;review:&lt;/label&gt;
    &lt;textarea name="text" maxlength="65535" id="text"&gt;&lt;/textarea&gt;
  &lt;/p&gt;
  &lt;p&gt;&lt;input type="submit"&gt;
  &lt;/form&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>
  
  <p>Here is the code for the script.php:</p>
  
  <pre><code>&lt;?php
  
  $servername = "localhost";
  $username = "name";
  $password = "password";
  $dbname = "db";
  // Create connection
  $conn = new mysqli($servername, $username, $password, $dbname);
  // Check connection
  if ($conn-&gt;connect_error) {
      die("Connection failed: " . $conn-&gt;connect_error);
  } 
  
  
  $firstname = filter_var(mysqli_real_escape_string($conn, $_POST["namefirst"]), FILTER_SANITIZE_STRING);
  $lastname = filter_var(mysqli_real_escape_string($conn, $_POST["namelast"]), FILTER_SANITIZE_STRING);
  $text = filter_var(mysqli_real_escape_string($conn, $_POST["text"]), FILTER_SANITIZE_STRING);
  
  
  $sql = "INSERT INTO tabel (firstname, lastname, text)
  VALUES('$firstname', '$lastname', '$text')";
  
  
  if ($conn-&gt;query($sql) === TRUE) {
      echo "New record created successfully";
      echo "&lt;br&gt;&lt;br&gt;&lt;br&gt;" . $namefirst . "&lt;br&gt;&lt;br&gt;" . $namelast . "&lt;br&gt;&lt;br&gt;" . $review;
  } else {
      echo "Error: " . $sql . "&lt;br&gt;" . $conn-&gt;error;
  }
  
  ?&gt;
  </code></pre>
  
  <p>Now I am trying to combine this project with this project, which uses Facebook's API to get log in and make a MySQL entry.</p>
  
  <p>Here is the code for that (fbindex.php):</p>
  
  <pre><code>&lt;?php
  // Include FB config file &amp;&amp; User class
  require_once 'fbConfig.php';
  require_once 'User.class.php';
  
  if(isset($accessToken)){
      if(isset($_SESSION['facebook_access_token'])){
          $fb-&gt;setDefaultAccessToken($_SESSION['facebook_access_token']);
      }else{
          // Put short-lived access token in session
          $_SESSION['facebook_access_token'] = (string) $accessToken;
  
            // OAuth 2.0 client handler helps to manage access tokens
          $oAuth2Client = $fb-&gt;getOAuth2Client();
  
          // Exchanges a short-lived access token for a long-lived one
          $longLivedAccessToken = $oAuth2Client-&gt;getLongLivedAccessToken($_SESSION['facebook_access_token']);
          $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;
  
          // Set default access token to be used in script
          $fb-&gt;setDefaultAccessToken($_SESSION['facebook_access_token']);
      }
  
      // Redirect the user back to the same page if url has "code" parameter in query string
      if(isset($_GET['code'])){
          header('Location: ./');
      }
  
      // Getting user facebook profile info
      try {
          $profileRequest = $fb-&gt;get('/me?fields=name,first_name,last_name,email,picture');
          $fbUserProfile = $profileRequest-&gt;getGraphNode()-&gt;asArray();
      } catch(FacebookResponseException $e) {
          echo 'Graph returned an error: ' . $e-&gt;getMessage();
          session_destroy();
          // Redirect user back to app login page
          header("Location: ./");
          exit;
      } catch(FacebookSDKException $e) {
          echo 'Facebook SDK returned an error: ' . $e-&gt;getMessage();
          exit;
      }
  
      // Initialize User class
      $user = new User();
  
      // Insert or update user data to the database
      $fbUserData = array(
          'oauth_provider'=&gt; 'facebook',
          'oauth_uid'     =&gt; $fbUserProfile['id'],
          'first_name'    =&gt; $fbUserProfile['first_name'],
          'last_name'     =&gt; $fbUserProfile['last_name'],
          'email'         =&gt; $fbUserProfile['email'],
          'picture'       =&gt; $fbUserProfile['picture']['url'],
      );
      $userData = $user-&gt;checkUser($fbUserData);
  
      // Put user data into session
      $_SESSION['userData'] = $userData;
  
      // Get logout url
      $logoutURL = $helper-&gt;getLogoutUrl($accessToken, $redirectURL.'logout.php');
  
      // Render facebook profile data
      if(!empty($userData)){
          $output  = '&lt;h2 style="color:#999999;"&gt;Facebook Profile Details&lt;/h2&gt;';
          $output .= '&lt;div style="position: relative;"&gt;';
          $output .= '&lt;img src="'.$userData['cover'].'" /&gt;';
          $output .= '&lt;img style="position: absolute; top: 90%; left: 25%;" src="'.$userData['picture'].'"/&gt;';
          $output .= '&lt;/div&gt;';
          $output .= '&lt;br/&gt;Facebook ID : '.$userData['oauth_uid'];
          $output .= '&lt;br/&gt;Name : '.$userData['first_name'].' '.$userData['last_name'];
          $output .= '&lt;br/&gt;Email : '.$userData['email'];
      }else{
          $output = '&lt;h3 style="color:red"&gt;Some problem occurred, please try again.&lt;/h3&gt;';
      }
  
  }else{
      // Get login url
      $loginURL = $helper-&gt;getLoginUrl($redirectURL, $fbPermissions);
  
      // Render facebook login button
      $output = '&lt;a href="'.htmlspecialchars($loginURL).'"&gt;click here to login with facebook&lt;/a&gt;';
  }
  ?&gt;
  &lt;html&gt;
  &lt;head&gt;
  &lt;/head&gt;
  &lt;body&gt;
      &lt;!-- Display login button / Facebook profile information --&gt;
      &lt;div&gt;&lt;?php echo $output; ?&gt;&lt;/div&gt;
  &lt;/body&gt;
  </code></pre>
  
  <p>The attached two documents just handle the facebook login API info and the SQL databasing. My question is how do I combine these two, so after successful Facebook login process $post from index.php while not leaving the page?</p>