AJAX call in Scala Play: Data not transfered - javascript

I'm about to implement a Login using Google OAuth. I followed the official Google docs
The client does get a token from the Google server. But whenever I try to send it back to my server to store it, I do not seem to get data from the AJAX call. Here is my code:
function signInCallback(authResult) { //called when client has confirmed the Login dialog
if (authResult['code']) {
// Hide the sign-in button now that the user is authorized, for example:
$('#signinButton').attr('style', 'display: none');
console.log("signinCallback. Send code to server:")
console.log("Code = "+ authResult['code']);
console.log("performing AJAX call now...\n\n")
// Send the code to the server
$.ajax({
type: 'POST',
url: 'http://localhost:9000/storeauthcode',
contentType: 'application/octet-stream; charset=utf-8',
success: function(result) {
// Handle or verify the server response.
console.log("AJAX call --> success");
console.log(result)
},
processData: false,
data: authResult['code']
});
} else {
//There was an error.
console.log("AJAX call failed.")
}
I created a line in my routes file:
POST /storeauthcode controllers.Application.storeAuthCode
The method on the server:
def storeAuthCode = Action { request =>
Ok("storeauthcode called with queryString = "+request.rawQueryString)
}
The following is a console output of my Chrome browser:
hello.js:2 Welcome to your Play application's JavaScript!
(index):67 signinCallback. Send code to server:
(index):68 Code = <token deleted for privacy reasons>
(index):69 performing AJAX call now...
(index):77 AJAX call --> success
(index):78 storeauthcode called with queryString =
So although my browser gets a token back, I cannot store it on the server, because I don't get any data back.
Ok("storeauthcode called with queryString = "+request.body.asJson)
is also empty.
This one here also delivers an empty result:
def storeAuthCode = Action { request =>
Ok("storeauthcode called with queryString = "+request.getQueryString("data"))
}

Related

How to get response back from the REST API and perform actions from jquery ajax call?

I am learning JS, jquery, and trying to build a login page and after giving the credentials to my application URL I should get a response back and I should be able to perform actions accordingly.
Something like: if the response is "success" then I should get an alert for success and redirect to another page (not sure how to do that) and if the response is "fail" I should throw an alert.
Below is the relevant snippet from my js file:
$.ajax({
url: "http://localhost:8588/api/userLogin",
type: "POST",
data: credentials,
dataType: "json",
contentType: 'application/json',
success: function(response) {
alert(response);
}
});
And my java controller method snipped annotated with #RestController:
#PostMapping(value = "/userLogin", consumes = "application/json")
public String userLogin(#RequestBody UserRequest userRequest) {
System.out.println(userRequest.getUserId()+ " "+ userRequest.getPassword());
User user = userService.getUser(userRequest);
return (user != null) ? "succeess" : "fail";
}
I am not getting any error
I am able to call the API but not getting the response back on UI. What am I missing?
I've taken your code and simulated simple case like yours. Most of the code looks right but as you've said there are no errors in the console and no response to client so there's problem got to be somewhere. There are certain things you've not specified here, so for more context for other people I am assuming UserRequest as
public class UserRequest {
public String username;
public String password;
}
and for the ajax request data I'm using
JSON.stringify({username: "developer", password:"pass"})
Now, I'm getting 200 response code with success message in alert at client side. Let me know if any error pops up after trying this.

Render Django template with POST data on AJAX call

OBJECTIVE:
When user is inactive for 5 minutes, my base.js file will send an ajax request to the server, server will flush all session data. I got everything right till here. Further after logging the user out, I want to display a page saying you have been logged out, with some custom data ( eg: user name) which I will be sending to that page via POST method.
I cannot use window.location(url) because in doing so I can only send data with GET method.
AJAX code in VUE Axios :
axios({
method: 'post',
url: 'ajax/logout/',
data: { },
responseType: 'json',
})
.then ( function (response){
console.log('AJAX success');
})
.catch ( function (error){
console.log('ajaxLogout error');
});
Django view looks like :
def ajaxLogout(request):
return JsonResponse ({"success":1} )

AWS API Call with Authorization Header ( session.getIdToken().getJwtToken() )

I Have a WebPage That USE AWS API Gateway using AWS-Cognito Authentication. Most of the Buttons in Web Page Call Api and send or Retrieve data. This is the Code I Use Under Every Button Click
getAuthenticateUser().getSession(function(err,session){
if (err) {
console.log("Error"+err);
return;
}
if(session.isValid())
{
$.ajax({
url: URL,
headers:
{
'Authorization':session.getIdToken().getJwtToken(),
'Content-Type':'application/json'
},
method: 'GET',
dataType: 'json',
success: function(data){
// Execute Function Need to Execute on Success
}
,
error: function (xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
if(!session.isValid())
{
console.log("Session is not valid..!");
//Please Login to Continue
}
});
This is Working Fine without Issue.But the Problem is It take Some Time to Execute it Everytime and Feeles like every time it Gives a New Session for Each call even Previous Session is not Expired. How can I Use get new Session Only when it Expired and if Previous Session is not Expired just check the validity of it globally and get a new Authorization Header Only I need..?
Because In My Code Once User Press One Button and Send Data id same User press another button after 30 sec i'm getting new session again right ..? it really gives me really bad on web site Performance.
Any Idea How to Solve this ..?
this my getAuthenticationUser() Code
function getAuthenticateUser()
{
return userPool.getCurrentUser();
}
and this my Global Variable in that Javascript page
var poolData = {
UserPoolId : 'usXXXXXXXXXXOv3jSL',
ClientId : 'XXXXXXXXXXka8g'
};
var userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData);
getSession() does not create a new session if the current session is valid.
If the current session is either null or invalid, it tries to refresh the session (using the refresh token) to get the ID token that is necessary to successfully complete the HTTP request using the Authorization header. Otherwise, it throws an error requesting to authenticate.
You can see what getSession() exactly does by taking a look at the CognitoUser class definition. (currently on line 1016.)

how to get json string from angular $http post request

I am sending this POST, I want to see the string that get's sent in the request before I send it.
Here's Plunker
$http.post('/someUrl', {msg:'hello word!'}).
then(function(response) {
// this callback will be called asynchronously
// when the response is available
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
I guess what I am trying to do is see the JSON string being sent to the server.
if you are hitting the url with config option like this
var config = {
headers: { 'Content-type': 'application/json' },
'dataType': 'json'
};
var data = {
name: 'intekhab',
age:26,
};
$http.post('/admin/header', data, config).then(function(response){
console.log(response);
});
Then you can see the data what are send. Open your browser console and click network then under network click your url what you have hit
And now see the look at Request Payload under header tab
There your data will be revealing what you have send to server.
And if you are not using config option like this
var data = {
name: 'intekhab',
age:26,
};
$http.post('/admin/header', data).then(function(response){
console.log(response);
});
Then do the same as above only difference is where you have seen the data under Request Payload, now you will see the same data under Form Data
From what I understand, I think you want different handlers if the request succeeds or fails. You can do it in this way:
$http.post('/someUrl', {msg:'hello word!'}).
success(function(response) {
// this callback will be called asynchronously
// when it succeeds
}).error(function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});

Javascript Detect During Postback

I implemented a system on my ASP.NET Web Forms site for passing notifications to the client. The notifications can be validation messages, success messages, warnings, errors etc. These messages are generated by code on the server side and then retrieved from the server via script on the client side and displayed.
On each page of my site I have embedded a JavaScript function that calls a web service (on the server side) via jQuery AJAX and requests the latest notifications. If there are notifications, they are displayed using Noty. On the server side, messages that have been sent to the client are removed from the queue.
This works pretty well. However, let's say I'm on a page called NewEmployee.aspx and they create a new employee by filling out a new form, and this generates some kind of notification such as "New Employee Created With ID 58478" and also takes them to the ViewEmployee.aspx page. If the postback happens slowly enough, the message will start to display while the user is still on NewEmployee.aspx but before the user arrives at ViewEmployee.aspx. The end result is that the notification is only displayed for a split second and the user never sees it.
I need a way in JavaScript on the client side to detect if the page is performing a postback. If I have that, I can prevent it from calling the webservice during a postback and have it wait until it completes. I want it to look something like this.
setInterval(oneSecondFunction, 1000); //check for messages every 1 second
function oneSecondFunction()
{
var IsPostingBackRightNow=GetIsPostingBackStatus(); //I need your help writing this function
if(!IsPostingBackRightNow)
{
$.ajax({
type: 'POST',
url: 'myurl/MessageService.asmx/GetCurrentMessage',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ sessionid: sessionid, locale: 'en-US' }),
dataType: 'xml',
success: function (msg)
{
//show message via noty if there's a message
}
});
}
}
The post back is passing from the form, so you capture the onsubmit event on the form, and there you open your flag.
Here is how... add that on code behind
Page.Form.Attributes["onsubmit"] = "return GoForPostBack();";
to have this attribute also rendered on your form...
<form ... onsubmit="return GoForPostBack();">
and the javascript
var IsPostingBackRightNow = false;
function GoForPostBack()
{
IsPostingBackRightNow = true;
return true;
}
setInterval(oneSecondFunction, 1000); //check for messages every 1 second
function oneSecondFunction()
{
if(!IsPostingBackRightNow)
{
$.ajax({
type: 'POST',
url: 'myurl/MessageService.asmx/GetCurrentMessage',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ sessionid: sessionid, locale: 'en-US' }),
dataType: 'xml',
success: function (msg)
{
//show message via noty if there's a message
}
});
}
}

Categories

Resources