Storing an API Call email in a variable - facebook-graph-api

I'm having trouble storing the user's email address in a variable in javascript. What I want to do is call the API, get the email address, and store it in the "email" variable, for use in other functions on the screen.
My code looks like this:
function emailCheck(){
var email;
FB.api('/me',email = function(response){
return response.email;
})
}
alert(email);
I did check to make sure that I have the proper permissions. I would put alert(response.email) in my response section, and it would alert with the proper email. The problem is that I cant get the email variable accessible outside of the function.

You need to use a continuation as all API methods are asynchronous
function emailCheck(continuation){
FB.api('/me', function(response){
continuation(response && response.email);
});
}
emailCheck(function(email) {
alert(email);
}
A different way is to use Promises, Futures or deferreds (same thing really) to abstract pieces of this.

Related

How to create a collection variable from response in postman

Selecting a value and right-clicking enables me to save it as a Global variable.
But there is no option to save it as a collection variable.
In the environments section as well. I can see Globals but my collection is not available.
But as I go through blogs/ articles online I can see some variables that are scoped to a collection.
Can I know a way to achieve this?
Tests tab is all you need
Considering the Stackoverflow GetUser API for Reference.
NOTE: The below-shown response is a part of the original response.
Response:
{
"items": [
{
"user_type": "registered",
"user_id": 12345678,
}
]
}
In the above response let's say we need user_type, and user_id in another API's URL / body / headers.
Before accessing we need to store these variables after receiving the response. This can be done in the Tests tab in postman request.
const jsonData = JSON.parse(responseBody);
const userType = jsonData?.items?.[0]?.user_type;
const userId = jsonData?.items?.[0]?.user_id;
if(userType){
pm.collectionVariables.set("userType",userType)
}
if(userId){
pm.collectionVariables.set("userId", userId)
}
Points to Note:
Postman tests are written in Javascript.
Optional chaining in line 2,3 is to avoid console errors. Possible Scenario: When API fails and returns an error response.
The IF Statements are to avoid null values in case of an Error Response. If statements are not mandatory. In fact without using if statements you will get to know clearly that something went wrong.
How to use collection variables
Once you make a request with the above tests. Postman IntelliSense suggests available collection variables. ( Refer to the image attached )
We are sending the body as a raw JSON in this Test Endpoint. Note that userType is surrounded by double quotes "" whereas userId is not. ( JSON syntax )

Reading cookies or sending info to Google Tag Manager

What is the correct way to send data to my Google Tag Manager?
I got a cookie notice that gives the user the opportunity to accept certain cookies (performance, marketing and analytics). So far I got this script to read the user' choice:
...
if (e.detail.performance) {
setCookie('cookie_performance', e.detail.performance, 365);
}
if (e.detail.analytics) {
setCookie('cookie_analytics', e.detail.analytics, 365);
}
if (e.detail.marketing) {
setCookie('cookie_marketing', e.detail.marketing, 365);
}
...
However, this only sets a cookie in the user' browser. I like to know inside my Google Tag Manager container if the user accepted the cookie.
I have read stuff about using the dataLayer, but I am stuck on configuring the triggers or tags inside my container.
Is it possible to send an event to my container whenever the user accepts a certain cookie?
Sure. If you go to the variables section and click "new" one choice for the variable type you have is "First Part Cookie".
As an aside, if the "365" in your code refers to the lifetime of your cookie in days (I assume it does, since 365 days is a year), be aware that on Safari and iOs Cookie lifetime will be limited to seven days due to the new version of their "Intelligent Tracking Prevention".
While using cookies works fine for GTM, the datalayer usually is best practice (cookies come with a few caveats - the browser may not allow them, their size is limited, their number per domain is limited etc).
As mentioned before there are inbuilt cookie variables for use within GTM, this way you can reference these in an if statement by using {{cookieVar_Name}} within GTM code.
However to answer your question about clueing in GTM about those cookies one way is to probably send along a dataLayer.push event with the necessary data.
For example you could adapt your current code to push an event when those cookies are set:
...
if (e.detail.performance) {
setCookie('cookie_performance', e.detail.performance, 365);
window.dataLayer.push({
event: 'performanceEvent',
cookie_performance: true
});
}
if (e.detail.analytics) {
setCookie('cookie_analytics', e.detail.analytics, 365);
window.dataLayer.push({
event: 'analyticsEvent',
cookie_analytics: true
});
}
if (e.detail.marketing) {
setCookie('cookie_marketing', e.detail.marketing, 365);
window.dataLayer.push({
event: 'marketingEvent',
cookie_marketing: true
});
}
...
At this point you could create a custom event trigger named to say, marketingEvent, you could then use this trigger to fire a tag when that dataLayer.push is actioned/is consented to.
In regards to reading the cookies of returning customers, you could either use a customHTML tag with a cookie reading function:
//This function can be used to retrieve a cookie and its value by its key(name)
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
getCookie(cookie_marketing);
Or store the cookie value in an inbuilt GTM cookie variable and write an if statement:
if({{cookie_marketing}} == true){
// fire code here
}
Hope this helps get you on the right track.

Meteor share sessions data between client and server

I'm building a restricted signup. I want user with a specific code passed in a url to be able to signup and not others. I'm using the accounts package.
I can prevent account creation in the Accounts.onCreateUser method. I'm looking for a way to tell the server if the client had an authorised signup code. With a classic form (email+password) I can just add an extra hidden field. How can I achieve the same result if the user signs up with let's say Facebook?
Since Meteor doesn't use cookies, I can't store this info in a cookie that the server would access. Session variable are not accessible server side. And since I'm not controlling what got send with the account-facebook creation, I can't use a Session variable on the client side that I'd pass along when the user presses sign up.
Any idea"?
Just add the special token to the user object being passed to Accounts.createUser():
var user = {
email: email,
password: password,
profile: {
token: token
}
};
Accounts.createUser(user, function (error, result) {
if (error) {
console.log(error)
}
});
On the server side you can access this in the Accounts.onCreateUser():
Accounts.onCreateUser(function(options, user) {
console.log(options);
console.log(user);
});
I think it's in the options variable that you will find your token, so it would be options.profile.token.
for me, the best option here was passing in custom parameters to loginbuttons.
see the package docs:
https://github.com/ianmartorell/meteor-accounts-ui-bootstrap-3
Where it outlines the below:
accountsUIBootstrap3.setCustomSignupOptions = function() {
return {
mxpDistinctId: Session.get('mxpdid'),
leadSource: Session.get('leadSource')
}
};

Grails: Expose LoginController for programmatic login

So I am working on a Grails/Flex toy project. I have a controller(LoginController) that I am using to perform backend authentication on my Flex app. However, I have been unable to "find" my controller. What I mean by that is I get a HTTP Status 404 error when trying to access
http://localhost:8080/OrlandoGrails/LoginController/login.json
Here is my sad, sad little controller as it is in its proof-of-concept state.
package orlandograils
class LoginController {
static allowedMethods = [login: "POST", login: "GET"]
def login(String username, String password )
{
return "Hello"
}
}
I've seen the documentation concerning RESTful services, but they always seem to concern a domain object which I don't have. In any case, I have also added this to my UrlMappings.groovy file
"/LoginController/login.json"(resource:"LoginController")
Any help on what I'm doing horribly wrong would be greatly appreciated. Also, is there a way to list Grails routes like one can with RoR or Symfony2?
Also, while the bulk of my services will be over the amf channels, my authentication is occurring over http.
It isn't entirely clear what you are trying to accomplish but one problem with your sample is that in your URL mapping you are specifying the name of a controller as your resource, which doesn't make sense. That could be a domain class, but not a controller.
If all you want to do is map a url to particular action in the controller you can do something like this in UrlMappings.groovy...
"/LoginController/login.json"(controller: 'login', action: 'login')
Normally you wouldn't have "Controller" in the url so something like this would be more common...
"/login/login.json"(controller: 'login', action: 'login')
From the little code snippet it also isn't clear what role you want JSON to play. Maybe you just want something like this...
"/login"(controller: 'login', action: 'login')
If you can further describe what you are trying to accomplish I can clarify.
In regards to getting a listing of routes (e.g. URL Mappings) you can run grails url-mappings-report
Also note to modify url-mapping to look like:
"/LoginController/login.json"(controller: "login", action: "login")
If resource is used then default action methods has to be show, create, update and delete
//Using resource: would look for a show() action method for a GET
//request which you don't have in your case. And, note name of controller used
//is login instead of LoginController
"/LoginController/login.json"(resource: "login")
As far as the 404 is concerned it's looking for a corresponding view called "hello.gsp" If you want to render text then use:
render text: 'hello'
The original post includes this:
package orlandograils
class LoginController {
static allowedMethods = [login: "POST", login: "GET"]
def login(String username, String password )
{
return "Hello"
}
}
The allowedMethods property there is bogus. Keys in a Map have to be unique. That code attempts to put the key login in the Map twice. If the intent is to say that the login method may be accessed via POST or GET then this makes sense...
static allowedMethods = [login: ['POST', 'GET']]
The code as written is valid, but it doesn't do what it was probably intended to do. That Map will evaluate to only have 1 value associated with the login key. That doesn't have anything to do with Grails, that is just standard Map behavior.
$ groovysh
Groovy Shell (2.1.9, JVM: 1.7.0_45)
Type 'help' or '\h' for help.
-------------------------------------------------------------------------------
groovy:000> [login: 'GET', login: 'POST']
===> {login=POST}
groovy:000>
Notice that the expression evaluates to a Map with the value "POST" associated with the login key.

In Ember.js, how do you make requests to an API that are outside of the REST convention?

I would like to request a 'reset password' endpoint e.g GET -> user/password/reset on an API. What is the best way to map this request in ember.js? It doesn't seem appropriate to setup a full ember.js model for this kind of request, as it doesn't have a proper ID and is not really a request for a record, but a triggered event with a success/fail response. Am I incorrectly implementing the REST convention or is there another way to do this?
You can use a simple ember-object to represent password reset and then basic ajax. Something like this:
App.User.reopenClass({
resetPassword: function(subreddit) {
return $.getJSON("user/password/reset").then(
function(response) {
console.log('it worked');
return true;
},
function(response) {
console.log('fail');
return false;
}
);
}
});
See http://eviltrout.com/2013/03/23/ember-without-data.html
That said, this could be a sign that the API endpoint should change. Ideally GET requests should not have side effects, so a GET that resets a password is not recommended. If you think of reset as a password reset request, the reset password endpoint that makes the most sense is POST -> user/password/reset to create a new request.