I have the below Login JavaScript for my MVC4 Application. I am attempting to add a value with my POST data to update the [LastVisitDate] each time a user logs in. However, whenever I login with my credentials, the value is still shown as 4/18/2014 10:04:47 AM. I have verified my cache has been cleared and am at a loss as to what I may be doing wrong.
Anyone have some thoughts on the matter?
function login()
{
var userName = $("#username").val();
var password = $("#password").val();
var rememberme = $("#rememberMe").is(':checked');
// NEWLY ADDED
var datestamp = Date.now();
var data =
{
Email: userName,
Password: password,
RememberMe: rememberme,
// NEWLY ADDED
LastVisitDate: datestamp
};
$.ajax(
{
url: "/Account/Login",
type: "POST",
data: data,
cache: false,
async: true,
success: function (data) {
$("#loginAlert").remove();
if (data.returnUrl != undefined) {
window.location.href(data.returnUrl);
}
else {
window.location.reload();
}
},
error: function (result) {
if ($("loginAlert").length() == 0) {
var errorMsg = 'There was an error.';
$("#navBar").after(errorMsg);
}
}
});
}
function EnterKeyPressed () {
if (event.keyCode == 13) {
login();
}
}
function closeAlert() {
$("#loginAlert").alert("close");
}
You have just posted the Ajax code and there is no clear information on what is going on in the background.
But based on your question I am assuming you are not returning the last logged in date. If its a SQL query then you need to perform a Order by date DESC. See if it helps :)
Related
Let's say I have a login form, with 2 fields, email and password, first I want to check if the user email is actually registered or not, so I made a separate file named user_check.php with the PHP code to check if a user exists or not,
include_once('../../classes/user.class.php');
$User = new User();
if ($User -> UserExists($_POST['login_email']) === true) {
echo true;
} else {
echo false;
}
now from login page, I want to call in an AJAX request to actually check if the UserExists() method returns false or true, if it returns false I will just give an error message to the user, else the code will continue
$.ajax({
url: 'ajax/login-handler/user_check.php',
type: 'POST',
data: {login_email: email.val()},
cache: false,
success: function(data) {
if (data == 1) {
alert('Exists');
} else alert('Doesn\'t Exist');
}
});
Should I do nested Ajax calls for other database checks inside success block if statements? Or if I need to do separate Ajax calls how can I pass one Ajax calls response to the other call?
If you have to make multiple asynchronous calls, I think the cleanest way would be to have an async function that awaits every asynchronous call you have to make. For example, using fetch, which supports well-formed Promises:
$(form).on('submit', (e) => {
e.preventDefault();
tryLogin()
.catch((e) => {
// handle errors
});
});
const tryLogin = async () => {
const userExists = await fetch('ajax/login-handler/user_check.php', {
method: 'POST',
body: JSON.stringify({ login_email: email.val() })
});
if (!userExists) {
// doesn't exist, tell user and return
return;
}
// user exists
const someOtherResult = await fetch('ajax/login-handler/somethingElse.php', {
method: 'POST',
body: JSON.stringify({ foo: 'bar' })
});
// do stuff with someOtherResult
};
First create your login page, then create your username and password field. And put this code after the JQuery library.
$(document).ready(function(){
$('#login').click(function(){
var usernameAdmin = document.getElementById("username").value;
var password = document.getElementById("password").value;
var dataString = 'usernameAdmin='+usernameAdmin+'&password='+password;
$.ajax({
type: "POST",
url: "controler/login.php",
data: dataString,
cache: false,
success: function(data)
{
document.getElementById("login").disabled = false;
window.location="admin/";
}
});
});
});
Now create your Ajax file according to the code below and enjoy it
if(isset($_POST['usernameAdmin']))
{
$username = $_POST['usernameAdmin'];
$password = $_POST['password'];
$c = $check->check_login_admin($username,$password);
if($c == true)
{
echo 1;
}
else
{
echo 0;
}
}
protected function check_login_admin($username,$password)
{
parent::__construct();
$sql = $this->_SELECT." `users` WHERE username=:u AND password=:p";
$r = $this->_DB->prepare($sql);
$r->bindValue(':u', $u);
$r->bindValue(':p', $p);
$r->execute();
$c = $r->rowCount();
if($c == 1)
{
foreach($r->fetchAll() as $row);
$_SESSION['log_true_admin']= true;
$_SESSION['name']= $row['name']." ".$row['family'];
$_SESSION['id']= $row['id'];
return true;
}
else return false;
}
good luck my friend
I have a simple chat application using Ajax and HTML.
Whenever I load new messages, I want to scroll the div to show the most recent message, so I'm doing the following:
jQuery:
function SendMessage()
{
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '')
{
$.ajax(
{
type: 'POST',
url: url,
data:
{
email: email,
message: clientmsg
},
success: function (data)
{
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
$("#conversation").scrollTop($("#conversation").outerHeight() * 1000);
}
});
}
}
I use this line to scroll the div down to the maximum:
$("#conversation").scrollTop($("#conversation").outerHeight()*1000);
My problem is, it scrolls down to the maximum WITHOUT showing the new messages. It scrolls down till the last message before the new one. Which is weird, because I'm calling it after updating the chat. Here's the function that updates the chat:
function UpdateChat(){
$.ajax({
// URL that gives a JSON of all new messages:
url: "url",
success: function(result)
{
var objects = JSON.parse(result);
$("#conversation").html("");
objects.forEach(function(key, index){
//append the messages to the div
$("#conversation").append("html here");
});
}
});
};
As mentioned in comments, you can use a setTimeout() to let the dom update add give some time before scrolling. See code below:
function SendMessage()
{
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '')
{
$.ajax(
{
type: 'POST',
url: url,
data:
{
email: email,
message: clientmsg
},
success: function (data)
{
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
setTimeout(function() {
$("#conversation").scrollTop($("#conversation").outerHeight() * 1000);
}, 500);
}
});
}
}
Assuming you insert a new element at the bottom, you could use scrollIntoView to make sure the new element is visible:
$.ajax({
// ...
success: function(data) {
var lastElement = $('#conversation :last-child');
lastElement[0].scrollIntoView();
}
});
Try putting the scroll line inside a setTimeout() method to allow about 500ms for things to update before scrolling down.
jQuery:
function SendMessage(){
var clientmsg = $("#comment").val();
var email = $("#email").val();
event.preventDefault();
if (clientmsg != '') {
$.ajax({
type: 'POST',
url: url,
data: {
email: email,
message: clientmsg
},
success: function (data) {
// Success means the message was saved
// Call the function that updates the div with the new messages
UpdateChat();
setTimeout(performScroll, 500);
}
});
}
}
and the scroll function
function performScroll() {
$("#conversation").scrollTop($("#conversation").outerHeight()*1000);
}
This question already has answers here:
Facebook JS SDK's FB.api('/me') method doesn't return the fields I expect in Graph API v2.4+
(4 answers)
Closed 6 years ago.
I was debugging an older script and came to the part where it should query a some Data of a Facebook user and store it into a Database.
Some of the scopes like publish_stream have been deprecated and so i replace it with "publish_actions". At least there is something i couldn't figure out. I would like to query the first and last name of the user but this reponse stays empty, the only that works is the thumbnail and the user ID.
So here are the scopes (i know public_profile is not necessary but facebook recommends it).
//function handleFacebookAuth(callback) {
function handleFacebookAuth(callback) {
var permissions = '';
//noinspection JSUnresolvedVariable
if (window.extendedPerms) {
permissions = 'public_profile,email,publish_actions,user_likes,' + window.extendedPerms;
} else {
permissions = 'public_profile,email,publish_actions';
}
if (accessToken != null && userId != null) {
callback(accessToken, userId);
} else {
FB.login(function (response) {
if (response.authResponse) {
userId = response.authResponse.userID;
accessToken = response.authResponse.accessToken;
callback(accessToken, userId);
} else {
$("#white-wall").hide();
}
}, {scope: permissions});
}
return false;
}
And here the query to the Data
function sendData(moves, seconds) {
FB.api('/me', function (response) {
var data = {
access_token: accessToken,
flag: 'data',
fbuid: response.id,
moves: moves,
seconds: seconds,
fname: response.first_name,
lname: response.last_name,
email: response.email,
gender: response.gender
};
userId = response.id;
$.ajax({
url: "ajax.php",
data: data, dataType: 'html', method: "post",
error: function (data) {
alert(data.responseText);
},
success: function (data) {
console.log(data);
//$( "#gameresults" ).html( data);
$('#gameresults').html(data);
$("#triggerbtn").fancybox({
'width': 480,
'height': 550,
'autoSize': false,
'overlayShow': false,
'scrolling': 'no'
});
$("#triggerbtn").trigger('click');
//window.top.location.href = data;
}
});
});
}
I hope that maybe someone see a mistake in it, i really can't figure out what is wrong with it, maybe the issue might be somewhere else and it would be great to hear that my code above is okay.
Okay thanks WizKid's hint the solution was pretty simple
I added to /me
FB.api('/me?fields=id,first_name,last_name,email,gender', function (response) {
That was all..
Hi;
when i'm using from jQuery ajax, the page getting to freeze until request end.
this is my JavaScript code:
function GetAboutContent(ID, from) {
var About = null;
if (from != true)
from = false;
$.ajax({
type: "POST",
url: "./ContentLoader.asmx/GetAboutContent",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ 'ID': ID, 'from': from }),
async: true,
success: function (msg) {
var Result = msg.d.Result;
if (Result == 'session') {
warning('Your session has expired, please login again!');
setTimeout(function () {
window.location.href = "Login.aspx";
}, 4000);
return;
}
if (Result == 'failed' || Result == false) {
About = false;
return;
}
About = JSON.parse(msg.d.About)[0];
}
});
return About;
}
and this is my WebService
[WebMethod(EnableSession = true)]
public object GetAboutContent(int ID, bool from = false)
{
try
{
if (HttpContext.Current.Session["MahdParent"] != null ||
HttpContext.Current.Session["MahdTeacher"] != null ||
from)
{
functions = new GlobalFunctions();
DataTable queryResult = new DataTable();
queryResult = functions.DoReaderTextCommand("SELECT Field FROM TT WHERE ID = " + ID);
if (queryResult.Rows.Count != 0)
return new { Result = true, About = JsonConvert.SerializeObject(queryResult.Rows[0].Table) };
else
return new { Result = false };
}
else
return new { Result = "session" };
}
catch (Exception ex)
{
return new { Result = "failed", Message = ex.Message };
}
}
How can i solve that problem?
please help me
In the last line you try to return About. That cannot work due to the asynchronous nature of an AJAX request. The point at which you state return About doesn't exist any more when the success function of your AJAX request runs.
I assume you try do do somehting like this:
$('div#content').html(GetAboutContent());
In a procedural lantuage like PHP or Perl this works fine, yet JavaScript functions in a very different way. To make something like this work you'd do something like this:
$.ajax({
type: "post",
url: "./ContentLoader.asmx/GetAboutContent",
dataType: "json",
data: {
'ID': ID,
'from': from
},
success: function(result) {
$('div#content').html(result)
}
});
The difference between the two bits of code is that the first would expect JavaScript to know the value at the time you request it. However, your function GetAboutContent() doesn't have instant access to these data. Instead it fires up an AJAX request and ends right after that with the request still in progress for an unknown amount of time.
Once the request finishes successfully the data is available to JavaScript. and you can work with it in the callback function defined for success. By then the request has absolutely no connection to the function that started it. That's why it's asynchronous.
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.