I'm having an issue with the javascript below in which the $.ajax call is not being called. The alert('foo') does happen, but then the data call is completely skipped and the callback is never reached (never get alert('success!'). I don't completely understand callbacks, but this seems like it should be working.
Edit
Edited the script to where I currently stand, as I've read this way is better practice. Still, I can step in to authenticate(), it breaks on url:[...], but then never actually makes the ajax call. I've tried removing the return just to see if that's the problem, but it's producing the same result.
define(["jQuery", "kendo", "modernizr", "app/environment"], function ($, kendo, modernizr, environment) {
var authenticate = function (username, password) {
return $.ajax({
url: environment.apiConnection + '/canlogin?userid=' + username + '&password=' + password,
type: 'get',
dataType: 'jsonp'
});
}
var canLogin = function(data) {
alert('good');
}
return {
viewModel: kendo.observable({
username: null,
password: null,
authenticate: function () {
var username = this.get('username'),
password = this.get('password');
authenticate(username, password).done(canLogin);
}
})
}
});
Use a callback instead.
var canLogin = function (username, password, callback) {
$.ajax({
async: false,
url: config.apiConnection + '/canlogin?userid=' + username + '&password=' + password,
type: 'GET',
dataType: 'jsonp',
error: function (x, t, r) {
alert('Error');
},
success: callback
});
}
// use
canLogin("user","passwd",function( data ){
alert("Im called on authentication success!");
});
The solution is a mixture of e.preventDefault() and using a callback in the ajax call. Just using the callback didn't resolve the issue, but adding preventDefault to the authenticate function and fixing the callback issue did.
The final, working version, now looks something like this:
define(["jQuery", "kendo", "modernizr", "app/environment"], function ($, kendo, modernizr, environment) {
function authenticate(username, password, callback) {
$.ajax({
url: environment.apiConnection + '/canlogin?userid=' + username + '&password=' + password,
type: 'get',
dataType: 'jsonp',
success: callback,
error: function (x,t,r) {
console.log('error')
}
});
}
function login(canLogin, username, password) {
if (canLogin == false) {
alert('Incorrect username or password');
return;
}
alert('good');
}
return {
viewModel: kendo.observable({
username: null,
password: null,
authenticate: function (e) {
e.preventDefault();
var username = this.get('username'),
password = this.get('password');
authenticate(username, password, function (canLogin) {
login(canLogin, username, password);
});
}
})
}
});
Related
I am trying to retrieve passwords in the database via the findOne method. Here is my Ajax:
$.ajax(
{
type: 'GET',
url: '/api/passwords/getPassword',
contentType: 'application/json',
dataType: "string",
async: true,
data: JSON.stringify({
"user_name": "fun.test.net",
"target": "Intern",
"system_type": "Test",
})
}).done(function(data)
{
window.ShowPassword(ele, data);
}).fail(function()
{
console.log("Error - Password Not Found.");
});
}
Along with its supporting function, which just swaps a button out for text (the password):
var buttonId = $(ele).attr('id');
var buttonText = $(this).html();
$('#' + buttonId).replaceWith("<span>" + "hello" + "</span>");
And here is my GET function:
router.get('/getPassword', async (req, res) =>
{
let passwords = await Password.findOne(
{
user_name: req.body.user_name,
target: req.body.target,
system_type: req.body.system_type,
});
if (!passwords) return res.status(404).send('Error 404: The password with the given ID was not found.');
res.send(JSON.stringify(passwords.password));
});
Whenever I call this function, it will throw the error:
TypeError: Cannot read property 'password' of null
at C:\Users\e0186030\Desktop\code\password_service2.0\routes\passwords.js:20:39
Please let me know what's going on! I'm not too familiar with Ajax, so I suspect that's what it is. But the idea is that the get function will return its password. It works in postman, so I know the call works by itself.
Try setting the JSON.stringify() to its own variable then sending it in the res:
const password = JSON.stringify(passwords.password);
res.send(password);
Your res.send() could be sending the password before it is actually stringified. Which would result in a null value. Hope this helps.
function gameLogin() {
var usernameToPass;
console.log('Fetching information from facebool.... ');
FB.api('/me', function (response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
//pass user name to Servlet
usernameToPass = response.name;
pass(usernameToPass);
});
}
function pass(name) {
$.ajax({
url: 'GameManagerServlet',
data: {
username: name
},
type: 'GET',
success: function (name) {
console.log(name);
}
});
}
so basically i have this script in my jsp using Facebook login api got username then stored in a variable, and trying to pass to my servlet by another function, because my servlet needs to receive the username when the page is loaded, i've tried some ways like by ajax, but the server side when i use request.getParameter("username"); but always got null. Could you help me to fix this problem? Thanks a lot!
You should use callback function like below.
var usernameToPass;
function gameLogin() {
console.log('Fetching information from facebool.... ');
FB.api('/me', function (response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = 'Thanks for logging in, ' + response.name + '!';
//pass user name to Servlet
usernameToPass = response.name;
pass(callback){
callback(usernameToPass);
};
}
function pass(function(name) {
$.ajax({
url: 'GameManagerServlet',
data: {
username: name
},
type: 'GET',
success: function (successname) {
console.log(successname);
}
});
})
I'm unsure why this jquery ajax call is failing. Basically, I want to authenticate and if the authentication is a success, do something.
I found this but the answer seems to abbreviated to be much use to me (is assumes you already know how to implement the solution). jQuery ajax return value
Here is my ajax call (I have stripped the fluff for getting the username/password):
function authenticate() {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
if(data==='true') {
return "true";
} else {
return "User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data;
}
},
error:function(jqXHR, textStatus, errorThrown){
return "User failed to log into the system. Potential problem with server or connection.";
}
});
And I call it in this function:
function attemptEventSubmit(eKey) {
var authReturn = authenticate();
if(authReturn=="true") {
emailEvent(eKey);
} else {
alert(authReturn);
}
}
When it returns, it always alerts that authReturn is "undefined". I suspect it's defining authReturn as undefined because the authenticate function 'finishes' before the ajax call gets back...
But I'm not sure how to fix this problem.
I suspect I could call separate instead of returning values... (say, in this example, calling the emailEvent function directly in the ajax success function) but that would make the authenticate function specific... and it'd no longer be able to be used for authenticating for other purposes.
You can use your code but will need a callback. A better way would be look into promises.
function authenticate(onsuccess, onfail) {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
onsuccess(data); // you should check if this is a function
},
error:function(jqXHR, textStatus, errorThrown){
onfail(errorThrown);
}
});
function attemptEventSubmit(eKey) {
authenticate(
function(ajaxData){
emailEvent('whatever you want to send');
},
function(errThrown){
alert(errThrown);
});
}
How about pass in a callback function as another argument of the function authenticate().
So the code changes will be
function authenticate(callback) {
$.ajax({ //TODO: Securely send this (ssl?)
type: 'POST',
url: 'includes/clientAuthenticate.php',
data: { username: username, password: password},
success:function(data){
if(data==='true') {
//return "true";
callback("true");
} else {
//return "User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data;
callback("User failed to log into the system.\nEmail request ignored.\n\nError message: \n" + data);
}
},
error:function(jqXHR, textStatus, errorThrown){
//return "User failed to log into the system. Potential problem with server or connection.";
callback("User failed to log into the system. Potential problem with server or connection.");
}
});
Calling the function authenticate will become:
function attemptEventSubmit(eKey) {
authenticate(function(authReturn){
if(authReturn=="true") {
emailEvent(eKey);
} else {
alert(authReturn);
}
});
}
I am making a simple ajax call to the web api service that serves an authentication routine.
My problem is the ajax call can make a request to the service but errors out once the service returns a boolean value.
WHAT I WANT:
All i want to do is check if the returned boolean is true or false. If true i want to redirect the user to another page.
Could somebody please help me out on this?
JQUERY CODE:
<script type="text/javascript">
$(document).ready(function () {
$('#submitButton').click(function () {
var name = $(userNameTextBox).val);
var pass = $(passwordTextBox).val();
if (name.length == 0 || pass.length == 0) {
alert("Please enter your credentials");
}
else {
$.ajax({
url: "http://localhost:50503/api/Authentication/Authenticate",
data: { userName: name, passWord: pass },
cache: false,
type: 'GET',
dataType: 'json',
success: function (msg) {
alert(msg);
},
error: function (msg) {
alert("Error Message: "+msg);
}
});
}//end of else
});
});
</script>
Here is my webapi service
public class AuthenticationController : ApiController
{
[HttpGet]
[Route("api/Authentication/Authenticate")]
public bool Authenticate(string userName,string passWord)
{
if (userName.ToLower().Equals("username") && passWord.ToLower().Equals("password"))
{
return true;
}
else
{
return false;
}
}
}
You can try replace your ajax call by this maybe, remove the dataType:
var request = $.ajax({
url: "http://localhost:50503/api/Authentication/Authenticate",
cache: false,
type: 'POST',
data: { userName: userName, passWord: passWord }
});
request.done(function (msg) {
//check the boolean and redirect user to another page.
if(msg) window.location.href = "http://nextpage.com";
});
i also change the method to POST. More appropriate in your case.
If all else fails, put a debugger breakpoint (e.g., via the debugger directive in your error callback to $.ajax and run your code in the browser's debugger (i.e. Chrome dev tools). Then, after the breakpoint is hit, you should be able to determine (by walking the stack) why the error callback is invoked.
My Test
I've tried to reproduce your case, and for me it doesn't fail. I've defined a test controller in the following way:
using System.Web.Http;
namespace Test
{
public class TestController : ApiController
{
[HttpGet]
public bool Authenticate(string username, string password)
{
return username == "user" && password == "pass";
}
}
}
And I make an AJAX call to it from JavaScript like so:
$.ajax({url: 'http://localhost:59900/api/test', type: 'get', dataType: 'json', cache: false, data: { userName: 'user', passWord: 'pass' }}).done(function () {console.log("Success", arguments);}).fail(function () { console.log("Error", arguments); });
The AJAX call invokes the success callback (done) with true as its result, so no issues at all.
Parser Error
It appears that jQuery can't parse the JSON sent from Web API (true). To return valid JSON, return an object of the following type from your controller:
public class Result
{
public bool Result { get;set; }
}
This should result in the following JSON being sent to your client:
{ "Result": true }
Updated controller:
namespace Test
{
public class TestController : ApiController
{
[HttpGet]
public Result Authenticate(string username, string password)
{
return new Result { Result = username == "user" && password == "pass" };
}
}
}
Try to use (worked for me, check responseJSON.Message of first parameter object):
$.post(url, jsonData).
done(function (data) {}).
fail(function (xhr, status, err) {
alert("Error " + err + ". " + xhr.responseJSON.Message);
});
In my website, I have provided a facility to login via linkedin. I have used javascript API for that.
I have written below code for login.
function onLinkedInAuth() {
var isLoggedIn = document.getElementById('<%=hdnIsLoggedin.ClientID %>').value;
// Check for the session on the site
if (isLoggedIn == false || isLoggedIn == 'false') {
IN.API.Profile("me")
.fields("id", "firstName", "lastName", "industry", "emailAddress")
.result(function (me) {
//debugger;
var id = me.values[0].id;
var fname = me.values[0].firstName;
var lname = me.values[0].lastName;
var industry = me.values[0].industry;
var email = me.values[0].emailAddress;
// AJAX call to register/login this user
jQuery.ajax({
type: "POST",
url: "UserRegisterAsSeeker.aspx/LinkedinLoginOrRegister",
data: "{id:'" + id + "',fname:'" + fname + "',lname:'" + lname + "',email:'" + email + "'}",
contentType: "application/json; Characterset=utf-8",
dataType: "json",
async: true,
success: function (data) {
closeLoginWindow();
__doPostBack('<%=lnkRefreshPage.UniqueID%>', '');
},
error: function (request, status, error) {
alert('Unable to process the request at this moment! Please try again later.');
},
complete: function () {
}
});
});
}
}
Above code works fine.
And for logout i have used below function provided by linkedin
function logout() {
IN.User.logout(function () {
window.location.href = '/logout.aspx';
});
}
Problem is in logout. When we login to the site and immediately logout, it works fine but when we leave the site ideal for some time it does not logout from linkedin. We have to click 3-4 times then it works.
I don't know why it's happening. Please help if you can.