I am trying to retrieve user fields using the LinkedIn API, in JavaScript.
I wish to pass this information as variables to another page using AJAX.
The code works fine, but a problem occurs when a user has an empty field.
For example, if I go to my LinkedIn Profile and delete my current job, the code stops working and no variables are passed because this field - positions.values[0].title
is empty.
Removing this entire line document.getElementById("imgTitle").src = member.positions.values[0].title;
will get it working again.
My question is how do I deal with the empty fields, and pass these variables as either ""
or null
using AJAX?
<!DOCTYPE html>
<html>
<head>
<script src="assets/js/scripts.js"></script>
<script src="js/jquery.js"></script>
<script type="text/javascript" src="//platform.linkedin.com/in.js">
api_key: [apikey]
onLoad: onLinkedInLoad
authorize: true
lang: [LANG_LOCALE]
</script>
<script type="text/javascript">
function onLinkedInLoad() {
IN.Event.on(IN, "auth", onLinkedInAuth);
}
function onLinkedInAuth() {
IN.API.Profile("me")
.fields(
"firstName",
"lastName",
"industry",
"location:(name)",
"picture-url",
"headline",
"summary",
"num-connections",
"public-profile-url",
"distance",
"positions",
"email-address",
"educations",
"date-of-birth"
)
.result(displayProfiles)
.error(displayProfilesErrors);
}
function displayProfiles(profiles) {
member = profiles.values[0];
alert(JSON.stringify(member));
document.getElementById("lblName").innerHTML = member.firstName + " " + member.lastName + "<br/> Location is " + member.location.name;
document.getElementById("imgProfile").src = member.pictureUrl;
document.getElementById("imgTitle").src = member.positions.values[0].title;
document.getElementById("lblProfile").innerHTML = member.publicProfileUrl;
document.getElementById("lblEmail").innerHTML = member.emailAddress;
var firstName = member.firstName;
var emailAddress = member.emailAddress;
$.ajax({
type: "POST",
url: "heya.php",
data: {firstname: firstName, email: emailAddress},
dataType: 'text',
success: function (data) {
alert(data);
}
});
}
function displayProfilesErrors(error) {
profilesDiv = document.getElementById("profiles");
profilesDiv.innerHTML = error.message;
console.log(error);
}
</script>
</head>
<body>
<script type="in/Login">
</script>
<br/>
<b>Get Linkedin LoggedIn User Details</b>
<table>
<tr>
<td>Name:</td>
<td><label id="lblName"/></td>
</tr>
<tr>
<td>Email:</td>
<td><label id="lblEmail"/></td>
</tr>
<tr>
<td>Profile Url:</td>
<td><label id="lblProfile"/></td>
<td>Title:</td>
<td><label id="lblTitle"/></td>
</tr>
<tr>
<td>Profile Image:</td>
<td><img id="imgProfile"/></td>
</tr>
</table>
<div id="profiles">
</div>
</body>
</html>