"Unlocking the Power of Facebook with Javascript and Ajax

My Cordova app successfully authenticates with Facebook, but when trying to retrieve data, I encounter errors. I suspect there may be an issue with my URL. Can anyone identify a mistake in this?

Errors:

app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration.{"readyState":0,"status":0,"statusText":"Error: SyntaxError: DOM Exception 12"}    

function makeAPICallsFB(token) {
$.ajax(
    {
        //url: 'https://api.linkedin.com/v1/people/~?format=json',
        url: 'https://graph.facebook.com/v2.6/me?fields=id,first_name,last_name,bio,email,work,friends,picture{url}',
        //url: 'https://graph.facebook.com/v2.6/oauth/access_token',
        beforeSend: function (xhr) {
            try {
                console.log("Authorization...");
                xhr.setRequestHeader('authorization', 'Bearer ' + token);
                console.log("Finished Auth...");
            } catch(err) {
                alert(err);
            }
        },
        success: function (linkedInData) {
            console.log("TEST....");
            if (linkedInData != null) {
                console.log("Success");
                try {
                    console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
                    console.log('name: ' + linkedInData.id);
                    vsetaService.saveLinkedInData(linkedInData, token);
                    checkUserStatus();
                } catch(err) {
                    alert(err);
                }
            } else {
                alert("Data is NULL!");
            }
        },
        error: function (error) {
            console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));
            //navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
            //Take user to Home if an error with LinkedIn + Temp assign access
            authenticatedUser = 1;
            homeScreen();
        }
    });
console.log("Finished!");
}

This is my FB Login

function oauth2_loginFaceBook() {
    $.oauth2({
        type: 'post',
        auth_url: 'https://www.facebook.com/v2.6/dialog/oauth',           // required
        response_type: 'code',      // required - "code"/"token"
        token_url: 'https://www.facebook.com/v2.6/oauth/access_token',          // required if response_type = 'code'
        logout_url: '',         // recommended if available
        client_id: 'confidential',          // required
        client_secret: 'confidential',      // required if response_type = 'code'
        redirect_uri: 'http://localhost/callback',       // required - some dummy url
        other_params: { scope: 'public_profile', state: 'somethingrandom1234' }        // optional params object for scope, state, display...
    }, function (token, response) {
        console.log('app: oauth2_login Success: ' + response.text);
        // do something with token or response
        makeAPICallsFB(token);

    }, function (error, response) {
        console.log('app: oauth2_login ERROR: ' + response.text + " AuthenticateUser anyways to allow access to App as of right now.");
        //Take user to Home if an error with LinkedIn + Temp assign access
        authenticatedUser = 1;
        homeScreen();
    });
}

Any assistance would be greatly appreciated!

EDIT: LinkedIn was handled correctly and the code is almost identical!

function makeAPICalls(token) {
$.ajax(
    {
        //url: 'https://api.linkedin.com/v1/people/~?format=json',
        url: 'https://api.linkedin.com/v1/people/~:(id,first-name,last-name,picture-urls::(original),headline,industry,num-connections,location,summary,specialties,site-standard-profile-request,api-standard-profile-request,public-profile-url,picture-url,positions:(id,title,summary,start-date,end-date,is-current,company:(id,name,type,size,industry,ticker)),educations:(id,school-name,field-of-study,start-date,end-date,degree,activities,notes))?format=json',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('authorization', 'Bearer ' + token);
        },
        success: function (linkedInData) {
            if (linkedInData != null) {

                console.log('app: makeAPICalls LinkedInData: ' + JSON.stringify(linkedInData) + " token: " + token);
                vsetaService.saveLinkedInData(linkedInData, token);

                checkUserStatus();
            }
        },
        error: function (error) {
            console.log("app: makeAPICalls: error:setting authenticatedUser to Yes and skip registration." + JSON.stringify(error));

            //navigator.notification.confirm('Unable to connect to LinkedIn at this time.', confirmCallback, "VSETA - Think Material", ["Ok"]);
            //Take user to Home if an error with LinkedIn + Temp assign access
            authenticatedUser = 1;
            homeScreen();
        }
    });
}

I suspect that the issue might lie in the URL. Any suggestions?

Answer №1

It seems like the issue may lie with the image{url}

If you need the URL for their profile picture,

photoURL = "http://graph.facebook.com/" + response.id + "/picture";

UPDATE

If that doesn't solve it, I can explain how I approach the task you're attempting.

I suggest using Facebook's SDK instead of Ajax for a smoother process.

//1
//Initialize the SDK
FB.init({
  appId      : 'your app id here',
  cookie     : true,
  xfbml      : true,
  version    : 'v2.6'
});

//2
//Load the SDK
(function(d, s, id) {
   var js, fjs = d.getElementsByTagName(s)[0];
   if (d.getElementById(id)) return;
   js = d.createElement(s); js.id = id;
   js.src = "//connect.facebook.net/en_US/sdk.js";
   fjs.parentNode.insertBefore(js, fjs);
 }(document, 'script', 'facebook-jssdk'));

//3
//Login button
<fb:login-button scope="public_profile,email" onlogin="facebookDoAThing();" data-max-rows="1" data-size="large" data-show-faces="true" data-auto-logout-link="true"></fb:login-button>

//4
//Call this function after button click
function facebookDoAThing() {
  FB.getLoginStatus(function(response) {
    statusChangeCallback(response);
  });
}

//5
//Check authorization
function statusChangeCallback(response) {
  if (response.status === 'connected') {
    getInfoAndSuch(response);   
  }
}

//6
//Retrieve user info
function getInfoAndSuch(response){
  authType = "facebook";
  authId = response.authResponse.userID; 
  FB.api('/' + authId + '?fields=id,first_name,last_name,email,permissions',
    function(response) {
            firstName = response.first_name; 
            lastName = response.last_name; 
            email = response.email;        
            photoURL = "http://graph.facebook.com/" + response.id + "/picture";     
    });
    //Optionally remove your app from their account
    FB.api("/me/permissions", "delete", function(response){});

This setup should help you achieve your goal.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unable to choose anything within a draggable modal window

Can someone please assist me? I am struggling to figure this out. I can't select text inside the modal or click on the input to type text into it. I suspect it may be due to z-index issues, but I'm having trouble locating them. var currentZ = n ...

Load a partial view in MVC using Ajax with a complex data structure

Within my main view, I have a section that loads a partial view containing data. Here is the code snippet that is executed upon initial loading: <div id="customerdetailsDIV" class="well main-well clearfix"> @Html.Partial("_customer_details", Mod ...

Preventing exit in Ionic application for PhoneGap/Cordova development

I'm developing an application and I want to restrict access to users who are unfamiliar with it. Is there a way to accomplish this? The only solution I found so far is blocking the back button functionality... Appreciate your help! ...

Understanding the significance of an exclamation point preceding a period

Recently, I came across this code snippet: fixture.componentInstance.dataSource!.data = []; I am intrigued by the syntax dataSource!.data and would like to understand its significance. While familiar with using a question mark (?) before a dot (.) as in ...

Activate Sparkline mini graph following successful Ajax response

With the code snippet below, I am able to fetch data from a MySQL database using Ajax and receive the result successfully during testing. However, my challenge lies in getting sparkline to render the graphs after the Ajax call is successful. Interestingl ...

What is the best way to pass an array to PHP and then display it in HTML?

After setting up a form with 3 select tags in my HTML, I attempted to create an array using jQuery and send it to PHP. The goal is to retrieve data from PHP and display it on my HTML page. Below is the code snippet: HTML code <form name="myform"> ...

Utilizing Piwik Analytics in jQuery Mobile Framework

Having an issue with tracking users on my mobile Web App using Piwik. Due to AJAX, only views on the first page are being tracked. I attempted to use the pageinit function to load the Piwik tracking script on every page, but it still only tracks the firs ...

Ajax/ASP.Net-powered PDF Viewer/Editor

Currently, I am working on a project that aims to enable document reading directly within the browser, eliminating the need for any additional software installations. This feature is intended to be a crucial part of a management application tailored for bu ...

The checkbox is not being triggered when an <a> tag is placed within a <label>

I have a unique case where I need to incorporate <a> within a <label> tag. This is due to the fact that various CSS styles in our current system are specifically designed for <a> elements. The <a> tag serves a purpose of styling and ...

Navigating intricate data structures within React

As a newcomer to React, I could use some assistance with a project I am working on. The application is similar to Slack, where users can create new teams and channels. However, I am encountering difficulties in managing the state of the data input throug ...

Creating an Interactive and Engaging 3D Experience on Facebook with the Power of Javascript API

Looking for suggestions on a 3D API in JavaScript that can be used to create immersive applications on Facebook. Is there something similar to this one: ? Appreciate any insights. ...

A: Looking to implement form validation with Ajax in CodeIgniter?

Hey there, I am currently trying to implement form validation in CodeIgniter using Ajax on the server side, but I am facing some issues. My goal is to display an error message with 'required' under the form input fields when necessary. Could some ...

Querying GraphQL: Retrieving partial string matches

I have set up a connection to a mongoDB collection using graphQL. Here is the data from the DB: { "_id" : ObjectId("59ee1be762494b1df1dfe30c"), "itemId" : 1, "item" : "texture", "__v" : 0 } { "_id" : ObjectId("59ee1bee62494b1df1dfe30d" ...

Guide on activating javascript code for form validation using php

How can I activate JavaScript code for form validation? I am currently implementing form validation on a combined login/register form where the login form is initially displayed and the register form becomes visible when a user clicks a button, triggering ...

The AngularJS array data is not displaying correctly

I am having trouble displaying comments array data in HTML properly. The data appears the same as it is in the comments array. What could be causing this issue? How should I proceed? <ul class="media-list" ng-controller="dishDetailController as menuCt ...

Update: "Mui V5 - Eliminate collapse/expand icons in TreeView and reduce TreeItem indentation"

My current project involves Mui V5 and I am looking to customize the TreeView component. Specifically, I need to remove the collapse/expand icons as I want them to be integrated into the TreeItem label component on the left side instead of the right. Add ...

Tips for refreshing Trackball controls in three.js

In my three.js project, I am faced with the challenge of updating the trackball controls upon window resize. I have found that updating the entire controls by calling the function with new input variables is necessary. Unfortunately, recreating the contr ...

Every time I click the login button, my HTML page opens again in a new tab. How can I resolve this problem?

Every time I click the login button, my HTML page opens again in a new tab. How can I resolve this issue? I've created an HTML form where clicking on login opens the HTML page in a new tab. What is the solution to fix this problem? My HTML Code <!D ...

Synk: the presence of a self-signed certificate within the certificate chain

Recently, I've been encountering the error message Synk Protect is showing "self-signed certificate in certificate chain" when I try to run npm install on a project of mine. Would appreciate any help or tips on how to identify which out of the 984 pac ...

Utilizing PHP to fetch data from a separate webpage

This is a question that has sparked my curiosity. I am not facing any particular issue that requires an immediate solution nor do I possess the knowledge on how to achieve it. I have been contemplating whether it is feasible to utilize PHP for fetching co ...