I have an array of users. Each user can be skipped on .click button. However I want it to skip the user that logs in. The session is started with PHP, but I'm showing the user through ajax and javascript. However
if(sSession = sKey){
aPeople.slice(this.jPerson);
}
is not correctly skipping the user. Could you help?
Here's the code:
$("#btnSkip").click(function() {
$.getJSON('include/users.txt', function(aPeople){
var getPerson = function(id) {
var jPerson = aPeople[id]
var sID = jPerson.id
var sName = jPerson.name
var sImage = jPerson.picture
var sSession = $('#mySession').text()
var sKey = jPerson.key
//this if statement doesn't work
if(sSession == sKey){
console.log(sSession)
console.log(sKey)
console.log(personIndex)
console.log(jPerson)
aPeople.splice(jPerson);
}
$('#sName').text(sName)
$('#sImg').attr('src', sImage)
//TO START COUNT AGAIN
if(aPeople.length -1 == personIndex){
personIndex = 0
}else{
personIndex = personIndex + 1
}
}
getPerson(personIndex);
$( '#sName' ).fadeIn( 'slow' )
$( '#sImg' ).fadeIn( 'slow' )
})
})
So, it looks to me like to you want to:
Here's a suggested solution:
function setupUserNavigator(users, loggedInUserKey) {
var idx = 0;
// filter out the logged in user
var filtered = $.grep(users, function(user) {
return !(user.key === loggedInUserKey);
});
function current() {
return filtered[idx];
}
function next() {
idx += 1;
}
function more() {
return idx < filtered.length - 1;
}
return { current, next, more };
}
function displayUser(user) {
$('#sName').text(user.name);
$('#sImg').attr('src', user.picture);
}
function usersResponseHandler(users) {
var loggedInUserKey = $('#mySession').text();
var userNavigator = setupUserNavigator(users, loggedInUserKey);
// display the first user immediately
displayUser(userNavigator.current());
// display each subsequent user on a 'next' button click
$('#next').click(function() {
userNavigator.next();
displayUser(userNavigator.current());
if(!userNavigator.more()) {
$(this).prop('disabled', true);
}
});
}
// $.getJSON('include/users.txt', usersResponseHandler);
// use test data for the snippet and mock response handler call
var data = [
{ id: '1', key: '1234', name: 'Joe', picture: 'img/joe.png' },
{ id: '2', key: '5678', name: 'John', picture: 'img/john.png' },
{ id: '3', key: '9012', name: 'Sarah', picture: 'img/sarah.png' },
{ id: '4', key: '0987', name: 'Tim', picture: 'img/tim.png' },
{ id: '5', key: '6543', name: 'Lily', picture: 'img/lily.png' }
];
usersResponseHandler(data);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Logged In User Key:
<div id="mySession">9012</div><br />
Name:
<div id="sName"></div>
Picture:
<div><img id="sImg" src="" /></div><br />
<button id="next">Next</button>
</div>