I have a simple login, once user is logged in I have added a call back to run another post so that I have access to the post json to use in my system.
I think the way I have done it is correct however I am getting error
GetData is not defined
Is this the correct way to do this
JavaScript
$scope.LogIn = function () {
$http({
url: "http://www.somesite.co.uk/ccuploader/users/login",
method: "POST",
data: $.param({'username': $scope.UserName, 'password': $scope.PassWord}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
GetData();
// location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
$scope.UserData = function ($scope) {
$scope.UserName = "";
$scope.PassWord = "";
};
$scope.GetData = function () {
$http({
url: " http://www.somesite.co.uk/ccuploader/campaigns/getCampaign",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log("then : " + JSON.stringify(response));
location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
You need to update your code to be $scope.GetData();.
Currently you are using GetData() which doesn't reference the same method. In fact it is undefined as per the error message.
Related
I am able to do login but I don't know how to set and get data into my localstorage, data is showing in alert.I know how to get and get result data from ajax response but did'nt understand how to do same with this below code.
function getDataProfile() {
var term = null;
// alert("getting user data="+accessToken);
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function (jqXHR, text_status, strError) {},
success: function (data) {
var item;
alert(JSON.stringify(data));
// Save the userprofile data in your localStorage.
localStorage.gmailLogin = "true";
localStorage.gmailID = data.id;
localStorage.gmailEmail = data.email;
localStorage.gmailFirstName = data.given_name;
localStorage.gmailLastName = data.family_name;
localStorage.gmailProfilePicture = data.picture;
localStorage.gmailGender = data.gender;
$('#loginStatus').html(data.given_name);
}
});
}
var googleapi = {
authorize: function (options) {
var deferred = $.Deferred();
//Build the OAuth consent page URL
var authUrl = 'https://accounts.google.com/o/oauth2/auth?' + $.param({
client_id: options.client_id,
redirect_uri: options.redirect_uri,
response_type: 'code',
scope: options.scope
});
//Open the OAuth consent page in the InAppBrowser
var authWindow = window.open(authUrl, '_blank', 'location=no,toolbar=no');
//The recommendation is to use the redirect_uri "urn:ietf:wg:oauth:2.0:oob"
//which sets the authorization code in the browser's title. However, we can't
//access the title of the InAppBrowser.
//
//Instead, we pass a bogus redirect_uri of "http://localhost", which means the
//authorization code will get set in the url. We can access the url in the
//loadstart and loadstop events. So if we bind the loadstart event, we can
//find the authorization code and close the InAppBrowser after the user
//has granted us access to their data.
$(authWindow).on('loadstart', function (e) {
var url = e.originalEvent.url;
var code = /\?code=(.+)$/.exec(url);
var error = /\?error=(.+)$/.exec(url);
if (code || error) {
//Always close the browser when match is found
authWindow.close();
}
if (code) {
//Exchange the authorization code for an access token
$.post('https://accounts.google.com/o/oauth2/token', {
code: code[1],
client_id: options.client_id,
client_secret: options.client_secret,
redirect_uri: options.redirect_uri,
grant_type: 'authorization_code'
}).done(function (data) {
deferred.resolve(data);
changepage('#adminhome');
}).fail(function (response) {
deferred.reject(response.responseJSON);
$("#errorStatus").html('error');
});
} else if (error) {
//The user denied access to the app
// $("#mainerrorStatus").html(error);
// alert(error);
deferred.reject({
error: error[1]
});
}
});
return deferred.promise();
}
};
var accessToken;
var UserData = null;
function callGoogle() {
// alert('starting');
googleapi.authorize({
client_id: 'myid',
client_secret: 'myid',
redirect_uri: 'http://localhost',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email'
}).done(function (data) {
accessToken = data.access_token;
// alert(accessToken);
// $loginStatus.html('Access Token: ' + data.access_token);
console.log(data.access_token);
console.log(JSON.stringify(data));
getDataProfile();
$("#accesstokenget").html('access token get');
});
}
// This function gets data of user.
function getDataProfile() {
var term = null;
// alert("getting user data="+accessToken);
$.ajax({
url: 'https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + accessToken,
type: 'GET',
data: term,
dataType: 'json',
error: function (jqXHR, text_status, strError) {},
success: function (data) {
var item;
alert(JSON.stringify(data));
// Save the userprofile data in your localStorage.
localStorage.gmailLogin = "true";
localStorage.gmailID = data.id;
localStorage.gmailEmail = data.email;
localStorage.gmailFirstName = data.given_name;
localStorage.gmailLastName = data.family_name;
localStorage.gmailProfilePicture = data.picture;
localStorage.gmailGender = data.gender;
$('#loginStatus').html(data.given_name);
}
});
disconnectUser();
}
function disconnectUser() {
var revokeUrl = 'https://accounts.google.com/o/oauth2/revoke?token=' + accessToken;
// Perform an asynchronous GET request.
$.ajax({
type: 'GET',
url: revokeUrl,
async: false,
contentType: "application/json",
dataType: 'jsonp',
success: function (nullResponse) {
// Do something now that user is disconnected
// The response is always undefined.
accessToken = null;
// alert(JSON.stringify(nullResponse));
console.log("-----signed out..!!----" + accessToken);
},
error: function (e) {
// Handle the error
// console.log(e);
// You could point users to manually disconnect if unsuccessful
// https://plus.google.com/apps
// alert('user diconnected<br>could not be connected');
}
});
}
This is the way to use localStorage:
// Store
localStorage.setItem("gmailLogin", "true");
// Retrieve
var isGmailLogin = localStorage.getItem("gmailLogin");
my question is: How can i pass variable(java script) to a rest apllication
This one of my functions in my controller.js:
This code sampel work, but i cant use my var email and password.
at the moment i use the url path log me in(url : 'rest/ab/einloggen/t#rt.de/22'). But how can i use var email(t#rt.de) and passwort(22).
app.controller('loginCtrl', function($scope, $location,$http){
$scope.submit = function(){
var email = $scope.username;
var password = $scope.password;
$http({
method : 'GET',
url : 'rest/ab/einloggen/t#rt.de/22'
}).success(function(data, status, headers, config) {
console.log(data);
if(data=="true"){
$location.path('/eingeloggt');
console.log("lalala");
}
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
});
Here is the login rest function:
#Path("/einloggen/{username}/{passwort}")
#GET
public String einloggen(#PathParam("username") String Username,#PathParam("passwort") String Passwort)
{
// Bekomme die strings
Business b = new Business();
boolean test =b.einloggen(Username, Passwort);
//Return einer JSON
String ersatzBool ="false";
if(test==true){
ersatzBool="true";
}
return ersatzBool;
}
if you want to pass data to webapi you can use
'POST' instead of 'GET', In the below example I have passed json data {id: 2 }
and getting response as a list of products, In the api post method id 2 is available.
$http.post('http://localhost:1011/productDetails', { Id: 12 }, {
headers: {
'Content-MD5': '917200022538',
'Accept': 'application/Json',
'Content-Type': 'application/Json'
}
}).then(onUserComplete, onError);
var onUserComplete = function (response) {
$scope.Products = response.data;
};
var onError = function (reason) {
$scope.error = "Error while fetching records.";
};
This is something I had to do while communicating with a server(CMS application - Contentstack) using Restful api's, one striking difference would be I had to use authtoken.
$http({
url: siteUrl,
method: methode,
headers: {
access_token: auth_token,
api_key: site_api_key,
Accept: data_type, // --> 'application/json, text/plain, */*'
},
data: dataBody
}).then(function (resp) {
console.log('success ', resp);
callback(resp);
}, function(err){
console.log(err, "error");
});
I've built an API using Slim Framework.
One of my routes in Slim accept optional parameters.
Is there any way I can do this using angularjs $http.get. How can I set optional parameters in my request.
Below is my code;
$scope.getRestaurant = function () {
return $http({
method: 'get',
url: "http://api.example.co.uk/web/restaurant/details/" + $scope.id + "/" + $scope.u,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return [];
});
}
As you can see I have $scope.id and $scope.u. I will like $scope.u to be optional. At the moment it is always passed even when it is null.
Just add it to the url if it's truthy.
var baseUrl = 'http://api.example.co.uk/web/restaurant/details/' + $scope.id;
if($scope.u) baseUrl += '/' + $scope.u;
//edited
You can use a ternary test like bellow:
$scope.getRestaurant = function () {
return $http({
method: 'get',
url: "http://api.example.co.uk/web/restaurant/details/" + $scope.id +
( $scope.u != null ) ? "/"+$scope.u : "" ,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return [];
});
}
or create your url before you make your return
$scope.getRestaurant = function () {
var url = "http://api.example.co.uk/web/restaurant/details/" + $scope.id +
( $scope.u != null ) ? "/" +$scope.u : "" ;
return $http({
method: 'get',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
return response.data;
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
return [];
});
}
I want to write a function in AngularJS that returns a value (actually it is a string). That value is returned by a http request, but async is driving me crazy.
My first attempt was:
this.readParameter = function(key) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
return response.data;
}, function errorCallback(response) {
throw new Error("Error");
})
};
But of course it does not work because of Angular async features (response.data is undefined)
What is the way to do it? I just want to return the value (string), so I can use this function like
var a = readParameter("key1")
What you can do is define some variable with initial value outside function and on response set value inside success function instead of returning it.
Delegator pattern works great here to assign $http task to some service and use callback method for response.
Controller (Call Service for specific request) -> Service (Manage request params and other things and return factory response to Controller) -> Factory (Send request and return it to Service)
Basic example of Callback
var myVariable = '';
function myFunction (key, callback) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
callback(response);
}, function errorCallback(response) {
throw new Error("Error");
})
};
function myCallbackFunction(response) {
myVariable = response.data; // assign value to variable
// Do some work after getting response
}
myFunction('MY_KEY', myCallbackFunction);
This is basic example to set value but instead use callback pattern from above example.
var myvariable = '';
function myFunction (key) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
myvariable = response.data; // set data to myvariable
// Do something else on success response
}, function errorCallback(response) {
throw new Error("Error");
})
};
myFunction('MY_KEY');
Don't try to mix async and sync programming. Instead use a callback to use like
readParameter("key1", callback)
for example:
this.readParameter = function(key, callback) {
$http({
method: "GET",
url: "XXXXXXX",
headers: { 'Content-Type': 'application/json' }
}).then(function successCallback(response) {
callback(response)
}, function errorCallback(response) {
throw new Error("Error");
})
};
I resolve this by using promise:
Example :
in Service (invoicesAPIservice => invoicesapiservice.js) you use:
angular.module('app')
.service('invoicesAPIservice', function ($http) {
this.connectToAPI= function () {
return new Promise(function(resolve,reject){
var options = {
method:'GET',
url :'',
headers:{
'X-User-Agent': '....',
'Authorization': '....',
}
};
$http(options).then(function successCallback(response) {
resolve(response);
//console.log(response);
},function errorCallback(response) {
reject(response);
})
});
});
});
and in your Controller (mainCtrl=> mainCtrl.js):
angular.module('app').controller('mainCtrl', function($scope,invoicesAPIservice) {
$scope.connectToAPI=function () {
invoicesAPIservice.connectToAPI().then(function (content) {
console.log(content.statusText);
}.catch(function (err) {
//console.log(err);
alert("Server is Out");
});
}
});
And in your page : index.html:
<button ng-click="connectToAPI()"></button>
:)
without the parameters of the method Get, the code works, but if the method asks for a parameter an error 404 is returned. How do I properly send parameters with Angular JS?
factory.test = function () {
var q = $q.defer();
$http({
method: "GET",
url: url + "/dataEntry/test",
data: {
sampletext : "sample"
}
})
.success(function (data, status, headers, config) {
q.resolve(data);
})
.error(function (data, status, headers, config) {
q.reject(data);
});
return q.promise;
};
[Route("test")]
public String Get(string sampletext)
{
return "Reply coming from data entry controller" + sampletext;
}
Since it's a GET request you shouldn't be sending data. You need to be sending a query string.
Change your data to params.
$http({
method: "GET",
url: url + "/dataEntry/test",
params: {
sampletext : "sample"
}
})
Source: http://docs.angularjs.org/api/ng/service/$http
$http({
url: "/saveInfo",
method: 'Post'
}).then(function(response) {
console.log("saved successfully");
}, function(response) {
console.log("Error message");
});