I am using the functions below for showing project info in popup which is working fine.The 2nd function is used to delete only the Document files for that particular project.I want to disable this function for Users with role "Manager".
function openShowProjectModal(id) {
$.post("/get-project-info", {ID: id}, function (res) {
var project = JSON.parse(res);
$("#job-name-show").text(project.JobName);
$("#job-number-show").text(project.JobNumber);
$("#location-show").text(project.Location);
var files = "";
for (var i = 0; i < project.Docs.length; i++) {
var filename = project.Docs[i].Document;
var id = project.Docs[i].ID;
// I want to disable the Delete function or to hide this Trash icon.
files += i+1 + ". " +(''+filename+'' ) +" " + '</i> <br/>';
$("#project-files").html(files);
}
});
}
function deleteDoc(id) {
if(confirm("Are you sure to delete?")){
$.post("/remove-doc",
{
ID :id
}, function (res) {
if (res == "removed") {
window.location.href = '/projects';
} else {
console.log("not removed");
}
});
}
}
I do not know where do you store roles. Maybe something like this will work:
function deleteDoc(id) {
if(user.role === "Manager") return;
if(confirm("Are you sure to delete?")){
$.post("/remove-doc",
{
ID :id
}, function (res) {
if (res == "removed") {
window.location.href = '/projects';
} else {
console.log("not removed");
}
});
}
Related
I perform an edit to ensure against duplicate emails by making an ajax call and supplying a callback. If a duplicate exists, I want to return false from submit event. Is there an elegant way to achieve this without setting async=false? What I tried (see emailCallback) is not working.
submit event
EDIT (included the rest of the submit handler).
$("#form-accounts").on("submit", function (e) {
e.preventDefault();
if (!$(this).get(0).checkValidity()) return false;
if (!customValidation(true, false)) return;
checkDupEmail(emailCallback);
function emailCallback(result) {
if (result) return (function () { return false } ());
}
if ($("#submit").text() == "Create Account") {
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/accounts.php', formData + "&action=create-account", createSuccess);
function createSuccess(result) {
if (isNaN(result)) {
showMessage(0, result);
return;
}
localStorage.setItem("account-id", result);
debugger
setUsertype($("input[name=user-type]:checked").val());
showMessage(1, "Account Created");
};
return
}
var rString = randomString(32, '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ');
function randomString(length, chars) {
var result = '';
for (var i = length; i > 0; --i) result += chars[Math.floor(Math.random() * chars.length)];
return result;
};
var anRandom = randomString(14, rString);
$("#code").val(anRandom);
console.log("v-code=" + anRandom);
$("#submit").css({ 'display': 'none' });
$("#verify").css({ 'display': 'block' });
var subject = "Writer's Tryst Verification Code"
$("#subject").val(subject);
var msg = "This mail is intended for the person who requested verification of email ownership at Writers-Tryst (" + getWriterTrystURL() + ").\n\n" + "Double click on the code below and then copy it. Return to our website and and paste the code.\n\nYour verification code: \n\n" + anRandom;
$("#msg").val(msg);
var formData = $("#form-accounts").serialize().replace("''", "'");
ajax('post', 'php/sendmail.php', formData, successMail, "create-account error: ");
function successMail(result) {
$("#ver-email-msg").val("An email has been sent to you. Double-click the verification code then copy and paste it below.").css({ 'display': 'block' });
}
});
function checkDupEmail(callback) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, emailSuccess);
function emailSuccess(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
callback(true);
} else callback(false);
}
}
Instead of passing a callback, why don't you just submit the form when your Ajax call completes successfully?
$("#form-accounts").on("submit", function (e) {
// Always cancel the submit initially so the form is not submitted until after the Ajax call is complete
e.preventDefault();
...
checkDupEmail(this);
...
});
function checkDupEmail(form) {
var data = {};
data.action = "validate-email";
data.email = $("#email").val();
ajax('post', 'php/accounts.php', data, function(result) {
if (parseInt(result) > 0) {
showMessage(0, "The email address is in use. Please supply another or login instead of creating a new account.")
} else {
form.submit();
}
}
}
A better approach than that would be to submit your form using Ajax. That would eliminate the need for two calls to the server.
I have chat on Socket.IO, MySQL, PHP. Everything is working good, but i need download and diplay messages history when you update the page.
php code:
<script>var USER = {"id":"<?php echo $_SESSION['steamid']?>","login":"<?php echo $_SESSION['personaname']?>","image":"<?php echo $_SESSION['avatarmedium']?>","hash":"<?php echo md5($_SESSION['steamid']) ?>"};</script>
js site code:
var messageTpl = _.template($("#chat-message").html());
function sendMessage(text) {
socket.emit('message', {user: USER, message: text});
}
var lastUser = null;
function addMessage(data, checkLast) {
var a = $("#chatScroll")[0];
var isScrollDown = (a.offsetHeight + a.scrollTop) == a.scrollHeight;
if (checkLast && lastUser && lastUser.id == data.user.id) {
$('.chatMessage').last().find('.body').append('<br/>' + _.escape(data.message))
}
else {
console.log(data);
data.user.url = 'http://steamcommunity.com/profiles/' + data.user.id;
data.user.image = 'https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/' + _.escape(data.user.image).replace('_medium', '');
var html = messageTpl(data);
$('#messages').append(html);
if ($('.chatMessage').length > 100) {
$('.chatMessage').eq(0).remove();
}
}
lastUser = data.user;
if (isScrollDown) a.scrollTop = a.scrollHeight;
$("#chatScroll").perfectScrollbar();
}
socket.on('online', function(data) {
$('#online').text(data.online);
});
socket.on('chat-message', function(data) {
addMessage(data, true);
});
socket.on('chat-history', _.once(function(data) {
$("#chatScroll").perfectScrollbar();
if (data) _.each(data, addMessage);
}));
function addMessage works good, but with socket.on('chat-history') i got error
Uncaught TypeError: Cannot read property 'id' of undefined
js server code:
connection.query('SELECT * FROM cs_chat ORDER BY id DESC LIMIT 50', function(error, rows) {
if(!error) {
var user = [];
rows.forEach(function (data) {
user.push(data);
});
console.log(user);
socket.emit('chat-history', {user: JSON.stringify(user)});
} else {
console.log(error.message);
}
});
when you refresh the page - all last messages lost
console.log server js rows.forEach below.
[{"id":668,"message_text":"3qwe","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:15.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":667,"message_text":"12312","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":666,"message_text":"213123","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:14.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":665,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":664,"message_text":"cvb","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":663,"message_text":"g","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":662,"message_text":"gdf","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"},{"id":661,"message_text":"df","user_steamid":"76561198056267433","user_personaname":"#Saundefined","date":"2015-10-06T15:22:12.000Z","user_avatarmedium":"https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c2/c2ff9427410ea1121363de0e651f6d4e8c485ab6_medium.jpg"}]
I'm using jquery-bitly-plugin for shorten some URLs and I'm doing in this way:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
shorten = bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine
// I got something like http://bit.ly/1DfLzsF
return shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
Then I tried this:
console.log(shorten);
But got Undefined, why? How do I assign the var in order to use in other places?
EDIT: adding extra information around the problem
This info will clarify a bit what I'm trying to do with my question so I have this code which allow to share some content in social networks on click event:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0];
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + url;
}
else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + url;
}
else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
return false;
}
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
return false;
});
As you may notice url is common to share-facebook and share-twitter. I need to shorten that URL and pass back to the href on each possible choice. For shorten the URL I'm using jquery-bitly-plugin as follow:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
console.info(shortUrl); // this works fine I got
// something like http://bit.ly/1DfLzsF
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
How I can use shortUrl in href parameter? Do I need to repeat the code on each condition in order to use execute the action at onSuccess event from shorten() method? How do you deal with this?
To assign to a variable:
var opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
shorten = shortUrl;
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
The method shorten doesn't have a return on source code of plugin.
IMPROVED ANSWER
Based on your edite post, this is the correct answer on how to use it the shortUrl:
$('.share-item').click(function () {
var href = '',
url = base_url + 'main/show/' + imgUrl.split("/")[2].split(".")[0],
opts = {login: myLogin, key: myKey},
bitly = new $.Bitly(opts);
bitly.shorten(url, {
onSuccess: function (shortUrl) {
if ($(this).data('category') == 'share-facebook') {
href = 'https://www.facebook.com/sharer/sharer.php?u=' + shortUrl;
} else if ($(this).data('category') == 'share-twitter') {
text = 'SomeText';
via = 'SomeText2';
href = 'http://www.twitter.com/share/?text=' + text + '&via=' + via + '&url=' + shortUrl;
} else if ($(this).data('category') == 'share-mail') {
$('#finalImgModal').attr('src', imgUrl);
$('#image').val(imgUrl);
$('#mailModal').modal('show');
}
if ($(this).data('category') != 'share-mail')
window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
},
onError: function (data) {
console.log(data.errorCode, data.errorMessage);
}
});
return false;
});
As I said in a comment, you need to figure out a future for the shortened URL. This future here is "open a window with this URL". Here is a quick pseudocode:
function openWindow(shortUrl) {
window.open(shortUrl, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600');
}
$('.share-item').click(function () {
if ($(this).data('category') == 'share-mail') {
...
return;
}
if (....twitter...) {
href = ...
} else if (....facebook....) {
href = ...
}
bitly.shorten(url, {
onSuccess: openWindow,
onError: function(err) {
...
}
});
}
(I made the openWindow future into a separate function to make it obvious, but it could just as well have been left inline.)
var dbShell;
function doLog(s){
/*
setTimeout(function(){
console.log(s);
}, 3000);
*/
}
function dbErrorHandler(err){
alert("DB Error: "+err.message + "\nCode="+err.code);
}
function phoneReady(){
doLog("phoneReady");
//First, open our db
dbShell = window.openDatabase("SimpleNotes", 2, "SimpleNotes", 1000000);
doLog("db was opened");
//run transaction to create initial tables
dbShell.transaction(setupTable,dbErrorHandler,getEntries);
doLog("ran setup");
}
//I just create our initial table - all one of em
function setupTable(tx){
doLog("before execute sql...");
tx.executeSql("CREATE TABLE IF NOT EXISTS notes(id INTEGER PRIMARY KEY,title,body,updated)");
doLog("after execute sql...");
}
//I handle getting entries from the db
function getEntries() {
//doLog("get entries");
dbShell.transaction(function(tx) {
tx.executeSql("select id, title, body, updated from notes order by updated desc",[],renderEntries,dbErrorHandler);
}, dbErrorHandler);
}
function renderEntries(tx,results){
doLog("render entries");
if (results.rows.length == 0) {
$("#mainContent").html("<p>You currently do not have any notes.</p>");
} else {
var s = "";
for(var i=0; i<results.rows.length; i++) {
s += "<li><a href='edit.html?id="+results.rows.item(i).id + "'>" + results.rows.item(i).title + "</a></li>";
}
$("#noteTitleList").html(s);
$("#noteTitleList").listview("refresh");
}
}
function saveNote(note, cb) {
//Sometimes you may want to jot down something quickly....
if(note.title == "") note.title = "[No Title]";
dbShell.transaction(function(tx) {
if(note.id == "") tx.executeSql("insert into notes(title,body,updated) values(?,?,?)",[note.title,note.body, new Date()]);
else tx.executeSql("update notes set title=?, body=?, updated=? where id=?",[note.title,note.body, new Date(), note.id]);
}, dbErrorHandler,cb);
}
function init(){
document.addEventListener("deviceready", phoneReady, false);
//handle form submission of a new/old note
$("#editNoteForm").live("submit",function(e) {
var data = {title:$("#noteTitle").val(),
body:$("#noteBody").val(),
id:$("#noteId").val()
};
saveNote(data,function() {
$.mobile.changePage("index.html",{reverse:true});
});
e.preventDefault();
});
//will run after initial show - handles regetting the list
$("#homePage").live("pageshow", function() {
getEntries();
});
//edit page logic needs to know to get old record (possible)
$("#editPage").live("pageshow", function() {
var loc = $(this).data("url");
if(loc.indexOf("?") >= 0) {
var qs = loc.substr(loc.indexOf("?")+1,loc.length);
var noteId = qs.split("=")[1];
//load the values
$("#editFormSubmitButton").attr("disabled","disabled");
dbShell.transaction(
function(tx) {
tx.executeSql("select id,title,body from notes where id=?",[noteId],function(tx,results) {
$("#noteId").val(results.rows.item(0).id);
$("#noteTitle").val(results.rows.item(0).title);
$("#noteBody").val(results.rows.item(0).body);
$("#editFormSubmitButton").removeAttr("disabled");
});
}, dbErrorHandler);
} else {
$("#editFormSubmitButton").removeAttr("disabled");
}
});
}
Dats my code, awfully long, huh?
Well anyways I got most of it from here, however I get an error on line 67 saying "TypeError: 'undefined' is not a function.".
I'm using Steroids (phonegap-like) and testing dis on an iPhone simulator. I'm sure it uses some cordova for the database work.
Thank you for your help :-)
Which jQuery version do you use? Because .live() was removed with jQuery 1.9 (http://api.jquery.com/live/). You should use .on() instead: http://api.jquery.com/on/
After logged in I am trying to return if the user is either not a fan of a Facebook page, but the result is always "undefined". But if I replace "return" to "alert" works perfectly.
function pageFan()
{
FB.api({ method: 'pages.isFan', page_id: '175625039138809' }, function(response) {
showAlert(response);
});
}
function showAlert(response)
{
if (response == true) {
return 'like the Application.';
} else {
return "doesn't like the Application.";
}
}
var like = pageFan();
document.getElementById('debug').innerHTML = like; //return undefined
This question has already been answered.
Relevant Javascript:
$(document).ready(function(){
FB.login(function(response) {
if (response.session) {
var user_id = response.session.uid;
var page_id = "40796308305"; //coca cola
var fql_query = "SELECT uid FROM page_fan WHERE page_id = "+page_id+"and uid="+user_id;
var the_query = FB.Data.query(fql_query);
the_query.wait(function(rows) {
if (rows.length == 1 && rows[0].uid == user_id) {
$("#container_like").show();
//here you could also do some ajax and get the content for a "liker" instead of simply showing a hidden div in the page.
} else {
$("#container_notlike").show();
//and here you could get the content for a non liker in ajax...
}
});
} else {
// user is not logged in
}
});
That's because the return in showAlert is not returning "into" the pageFan function. The showAlert function is passed as a callback, meaning it will be called later, outside of pageFan's execution. I think you need to read more about callback functions and asynchronous programming.
function showAlert(response)
{
if (response == true) {
document.getElementById('debug').innerHTML = 'like the Application.';
} else {
document.getElementById('debug').innerHTML = "doesn't like the Application.";
}
}