i'm using this method directly from Facebook Developer to get users information after login, i need to get username, userid and email
public void onSuccess(LoginResult loginResult) {
GraphRequest request = GraphRequest.newMeRequest(
loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(
JSONObject object,
GraphResponse response) {
// Application code
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,email");
request.setParameters(parameters);
request.executeAsync();
how should i do to get the JSON information and store it in Public variable in my document, to use it in other function ?
Related
I am developing a REST API using Node.JS and AWS Lambda, which will be accessed by 3 apps.
Android app developed with Flutter
iOS app developed with Flutter
Web app developed with Java
I have always been a Java guy and never a Javascript guy. This is my first time on serious job with Javascript stuff.
Normally when we create REST APIs in Java, it will get the data from the database, convert it to a Java class and send it back as the response.
For an example, lets assume below is the structure of my database table. Have a close look at the names, AND the associated foreign keys.
In my Java based REST API, this will be the class.
public class SellerSettings implements java.io.Serializable {
private Integer idsellerSettings;
private User user;
private double responseRate;
private double responseTime;
private boolean isavailable;
public SellerSettings() {
}
public Integer getIdsellerSettings() {
return this.idsellerSettings;
}
public void setIdsellerSettings(Integer idsellerSettings) {
this.idsellerSettings = idsellerSettings;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public double getResponseRate() {
return this.responseRate;
}
public void setResponseRate(double responseRate) {
this.responseRate = responseRate;
}
public double getResponseTime() {
return this.responseTime;
}
public void setResponseTime(double responseTime) {
this.responseTime = responseTime;
}
public boolean getIsavailable() {
return this.isavailable;
}
public void setIsavailable(boolean isavailable) {
this.isavailable = isavailable;
}
}
When the data is requested from an API built with Java, it will send the response back with the same set of names you see in the java class I presented. Since the user is another class, it will actually add that's fields as well..
Anyway, this is my node.js code now.
const mysql = require('mysql');
const con = mysql.createConnection({
host : "*******.rds.amazonaws.com",
user : "****",
password : "*****",
port : 3306,
database : "*****"
});
exports.lambdahandler = (event, context, callback) => {
// allows for using callbacks as finish/error-handlers
context.callbackWaitsForEmptyEventLoop = false;
const sql = "select * from seller_settings";
con.query(sql, function (err, result) {
if (err) throw err;
var response = {
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": JSON.stringify(result),
"isBase64Encoded": false
};
callback(null, response)
});
};
And it return the below
[
{
"idseller_settings": 1,
"iduser": 1,
"response_rate": 90,
"response_time": 200,
"isavailable": 0
},
{
"idseller_settings": 2,
"iduser": 1,
"response_rate": null,
"response_time": 210,
"isavailable": 0
}
]
It is nothing but the pure table names.
As a Java guy, I looked at how we can convert these to the Java like names. Then I found Javascript classes. However I do understand that Javascript is not OOP as Java or anything similar. It is not perfect on OOP. Also adding these class, converting the values from JSON to classes, and the sending it back seems to be an over kill for my simple, nice Node.JS code.
As a Java guy, I would ask,
When requested via the REST API, Is it normal to grab the data from the database tables as per column names as it is and send it back in Javascript world? Or should I create classes?
My mobile and web apps are using classes in their languages, when sending POST requests they will most probably send a JSON that contains Java classe's variables I shared. From the node.js side, this can be converted to table names?
I am trying to use Braintree's payment DropinUI, and configuring it requires sending a generated token
to a javascript function in my page. I have the following markup in my Razor Page:
<div id="dropin-container"></div>
<button id="submit-button">Request payment method</button>
<script>
function configureBraintreeClient(clientToken) {
var button = document.querySelector('#submit-button');
braintree.dropin.create({
authorization: clientToken,
container: '#dropin-container'
}, function (createErr, instance) {
button.addEventListener('click', function () {
instance.requestPaymentMethod(function (requestPaymentMethodErr, payload) {
// Submit payload.nonce to your server
});
});
});
}
</script>
The div #dropin-container is populated by the result of the function configureBraintreeClient. So, I need to pass in a clientToken when the page loads.
My page model to generate a client token:
public class IndexModel : PageModel
{
private readonly IJSRuntime _jsRuntime;
public IndexModel(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
public IActionResult OnGet()
{
// Create gateway
var gateway = new BraintreeGateway
{
Environment = Environment.SANDBOX,
MerchantId = "xxxxxxx",
PublicKey = "xxxxxxx",
PrivateKey = "xxxxxxx"
};
var clientToken = gateway.ClientToken.Generate();
JSRuntimeExtensions.InvokeVoidAsync(_jsRuntime, "configureBraintreeClient", clientToken);
// Not sure if this is needed, doesn't work with return type of
// void and this line removed either.
Page();
}
}
This does not work. The div is never populated.
I can insert a client token directly into the markup and it runs perfectly, so it has something to do with passing the client token
to the page from the page model. Should I not be using the JSRuntime extension?
I've tried setting the client token as a model property and inserting it in the function with razor syntax like authorization: #Model.ClientToken
but it doesn't work.
I've tried to dig around to understand the page life cycle better but nothing I have found has helped me figure out this issue.
I see no errors in the developer console of my browser or in Visual Studio, but I don't know a lot about debugging javascript in ASP .NET Core.
What's the proper way to pass a parameter into a javascript function that updates a div like this?
For we do not have merchant ID,Public key andPrivate key,be sure that you have generated the correct token,then you could try this:
1.IndexModel():
private readonly IJSRuntime _jsRuntime;
public IndexModel(IJSRuntime jsRuntime)
{
_jsRuntime = jsRuntime;
}
[BindProperty]
public string clientToken { get; set; }
public void OnGet()
{
// Create gateway
var gateway = new BraintreeGateway
{
Environment = Braintree.Environment.SANDBOX,
MerchantId = "xxxxxxx",
PublicKey = "xxxxxxx",
PrivateKey = "xxxxxxx"
};
clientToken = gateway.ClientToken.Generate();
JSRuntimeExtensions.InvokeVoidAsync(_jsRuntime, "configureBraintreeClient", clientToken);
}
2.Razor Page(no need to use function):
<div id="dropin-container"></div>
<button id="submit-button">Request payment method</button>
<script src="https://js.braintreegateway.com/web/dropin/1.20.4/js/dropin.min.js">
</script>
<script>
var button = document.querySelector('#submit-button');
braintree.dropin.create({
authorization: '#Model.clientToken',
container: '#dropin-container'
}, function (createErr, instance) {
button.addEventListener('click', function () {
instance.requestPaymentMethod(function (requestPaymentMethodErr, payload) {
// Submit payload.nonce to your server
});
});
});
</script>
3.Test(You could see that the token has filled into the js):
Reference:
https://developers.braintreepayments.com/start/hello-client/javascript/v3
I can insert a client token directly into the markup and it runs perfectly, so it has something to do with passing the client token to the page from the page model. Should I not be using the JSRuntime extension?
For this,if you want to use client token,I suggest that you could refer to:
https://developers.braintreepayments.com/start/tutorial-drop-in-node
For authorization,you could also use tokenization key.
In my main.js file I want to have data from spring boot controller in some specific json format.
eg.
var contactsJSON = [{"userId": "firstuser", "displayName": "firstuser"},
{"userId": "seconduser", "displayName": "seconduser"}];
Now in my controller "/users" i'm returning list of all users.
I want that at the time of application loading the value of contactsJSON gets populated dynamically in required json format (I only need username to create JSON).
main.js
var contactsJSON = [{"userId": "firstuser", "displayName": "firstuser"
},
{"userId": "seconduser", "displayName": "seconduser"
},
{"userId": "thirduser", "displayName": "thirduser"
}
];
UserController.java
#RequestMapping(value = "/users", method = RequestMethod.GET)
public String viewUsers(Model model) {
List<User> list = userService.getAllUsers();
model.addAttribute("userList", list);
return "welcome";
}
List contains private Long id;
private String username;
private String password;
private String passwordConfirm;
I want to dynamically provide value of contactsJSON in my javascript file. How can I do this ?
You can either return a response as String or you can use ResponseEntity Object provided by Spring as below. By this way, you can also return Http status code which is more helpful in the web service call.
#RestController
#RequestMapping("/api")
public class MyRestController
{
#RequestMapping(value = "/users", method = RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> viewUsers(Model model) {
{
//Get data from service layer into entityList.
List<User> list = userService.getAllUsers();
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : list) { // You can iterate over the list and add in json format below is the example for same
//JSONObject entity = new JSONObject();
//entity.put("aa", "bb");
//entities.add(entity);
}
return new ResponseEntity<Object>(entities, HttpStatus.OK);
}
}
First, a Thymeleaf recommendation
I highly recommend Thymeleaf over JSP templates. For one thing, it makes inline object-to-JSON expressions very easy. For example...
<script th:inline="javascript">
const contactsJSON = [[${userList}]];
</script>
See https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#advanced-inlined-evaluation-and-javascript-serialization
If you don't want to switch, I would recommend adding an AJAX call to fetch your user data. On the Java side, it might look like this
#GetRequest(path = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
#ResponseBody
public List<User> getAllUsers() {
return userService.getAllUsers();
}
Spring will automatically serialize the response as JSON.
Then in your welcome.jsp
<script>
// load the current URL (ie /users) but requesting JSON
fetch('', {
headers: {
Accept: 'application/json'
}
}).then(res => res.json()).then(contactsJSON => {
// you can now use contactsJSON here
})
</script>
I'm trying to post strings from an AngularJS application (using $http) to a server built on ASP.NET WebApi, but I get 404 as soon as I add a parameter.
The client code is this
$scope.add = function () {
// ...cut...
$http({ method: "POST", url: url, data: { fileString: "test string" }}).then(
function successCallback(response) {
$log.info(response.data);
}
);
}
The server code is
[HttpPost]
public IHttpActionResult UploadExcel(string fileString) {
// cut
}
I get a 404, but if I remove the parameter on server side it works, so i can use a server side code like this
[HttpPost]
public IHttpActionResult UploadExcel() {
// cut
}
What is wrong? Should I pass the data in a different way? I tried different combination but I can't get it work.
What you want to do is send a string, not a JSON object as you are doing right now with { fileString: "test string" }. When I want to send a string, what I normally do is that I send data from Angular like this:
$http.post("/Search/QuickSearch?searchQuery="+ searchString);
And my controller I make ready to receive a string like this:
[HttpPost]
public IHttpActionResult QuickSearch(string searchQuery)
{
// cut
}
If I want to send a JSON object, I tell my controller what it should expect, like this:
[HttpPost]
public IHttpActionResult SaveActivity(ActivityEditForm form);
{
// cut
}
public class ActivityEditForm
{
public int? Id { get; set; }
[Required]
public string Title { get; set; }
public string Description { get; set; }
}
And then send my JSON from Angular like this:
$http.post("/Activity/SaveActivity", { form: activity });
I suggest you should capture the request send by Angular. By default, Angular send parameters in a json string in request body.
I'm not sure wether Asp.net can parse them from json string in body.
So, you can try to add the below codes (also need jQuery)
angular.module('yourApp').config(function ($httpProvider) {
$httpProvider.defaults.transformRequest = function(data){
if (data === undefined) {
return data;
}
return $.param(data);
}
});
The first error is in the controller, [FromBody] should be used with the input parameter.
public IHttpActionResult UploadExcel([FromBody]string fileString)
Then the data variable on the client should be a single string, so
$http({ method: "POST", url: url, data: "test string" }).then(
Anyway I found some issue with this solution later, it seems the simplest but I suggest to avoid it.
Best solution
Thank to #Squazz answer and this SO answer I strongly suggest a change in the webapi controller, client was correct. Just introduce a class to handle a single string and adapt the input parameter
// new class with a single string
public class InputData {
public string fileString { get; set; }
}
// new controller
[HttpPost]
public IHttpActionResult UploadExcel([FromBody] InputData myInput) {
string fileString = myInput.fileString;
// cut
}
This way JSON code from the client is automatically parsed and it's easy to change the data input.
Extra tip
$scope.add angular function was correct as in the question, but here is a more complete example
$scope.testDelete = function () {
var url = "http://localhost/yourAppLink/yourControllerName/UploadExcel";
var data = ({ fileString: "yourStringHere" });
$http({ method: "POST", url: url, data: data }).then(
function successCallback(response) {
console.log("done, here is the answer: ", response.data);
}, function errorCallback(response) {
console.log("an error occurred");
}
);
}
So I'm trying to send the following data from jQuery on the server side like so:
var fd = new FormData();
fd.append('name', 'tyler');
fd.append('hello', 'world');
$.post('/NMISProduct/Index', { submitData: fd}, function(returnedData) {
console.log(returnedData);
}, 'json');
How do I handle this on the server side? Here is what I have, which I'm sure is very wrong:
[HttpPost]
public string Index(string submitData)
{
return submitData;
}
I just want to return what I send to C# back to jQuery so I know it got there. What am I doing wrong?
Your current approach ties you to FormData() and it doesn't take advantage of JSON.Net which is happy and eager to deserialize your object so that you can consume it.
If you truly want to test "full-loop", deserialize to a strongly typed object and return it back to the client as serialized json, building out the matching object on the client instead of using FormData().
$.post('/NMISProduct/Index', { name: 'tyler',hello: 'world' }, function(data) {
console.log(data);
});
[HttpPost]
public ActionResult Index(FormData submitData)
{
return Json(submitData);
}
public class FormData
{
public string Name { get; set; }
public string Hello { get; set; }
}