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.)
Related
I am using local storage to restore data incase a user accidentally reloads the page, but when they reload a checkbox is checked even when they did not check it.
Below is my code, the only wrong value that's being rendered is the checkbox. I have other fields which value the are being restored are accurate upon reload of the page.
I think I am missing one thing, or two, any help would be really appreciated. Thanks.
var remember_state = {
name: "rememberState",
clearOnSubmit: true,
_defaultNoticeDialog: function() {
return $("<p />", { "class": "remember_state" })
.html('Restore previously entered information? <a class="btn btn-sm btn-link" href="#"><i class="mrx far fa-history"></i>Restore</a>');
},
noticeConfirmSelector: "a",
noticeSelector: ".remember_state",
use_ids: false,
objName: false,
restoreState: function(e) {
var data = JSON.parse(localStorage.getItem(this.objName)),
$f = this.$el,
$e;
for (var i in data) {
$e = $f.find("[name=\"" + data[i].name + "\"]");
if ($e.is(":radio")) {
$e.filter("[value=\"" + data[i].value + "\"]").prop("checked", true);
}
else if ($e.is(":checkbox") && data[i].value) {
$e.prop("checked", true);
}
else if ($e.is("select")) {
$e.find("[value=\"" + data[i].value + "\"]").prop("selected", true);
}
else {
$e.val(data[i].value);
}
$e.change();
}
this.noticeDialog.remove();
e && e.preventDefault && e.preventDefault();
},
cancelNotice: function(e) {
e.preventDefault();
this.noticeDialog.remove();
},
chooseStorageProp: function() {
if (this.$el.length > 1) {
if (console && console.warn) {
console.warn("WARNING: Cannot process more than one form with the same" +
" object. Attempting to use form IDs instead.");
}
this.objName = this.$el.attr("id");
}
},
errorNoID: function() {
if (console && console.log) {
console.log("ERROR: No form ID or object name. Add an ID or pass" +
" in an object name");
}
},
saveState: function(e) {
var instance = e.data.instance;
var values = instance.$el.serializeArray();
// jQuery doesn't currently support datetime-local inputs despite a
// comment by dmethvin stating the contrary:
// http://bugs.jquery.com/ticket/5667
// Manually storing input type until jQuery is patched
instance.$el.find("input[type='datetime-local']").each(function() {
var $i = $(this);
values.push({ name: $i.attr("name"), value: $i.val() });
});
values = instance.removeIgnored(values);
values.length && internals.setObject(instance.objName, values);
},
save: function() {
var instance = this;
if (!this.saveState) {
instance = this.data(remember_state.name);
}
instance.saveState({ data: { instance: instance } });
},
bindNoticeDialog: function() {
if (!this.noticeDialog || !this.noticeDialog.length || !this.noticeDialog.jquery) {
this.noticeDialog = this._defaultNoticeDialog();
}
this.noticeDialog.on("click." + this.name, this.noticeConfirmSelector, $.proxy(this.restoreState, this));
this.noticeDialog.on("click." + this.name, this.noticeCancelSelector, $.proxy(this.cancelNotice, this));
},
setName: function() {
this.objName = this.objName || this.$el.attr("id");
if (!this.objName) { this.errorNoID(); }
},
init: function() {
this.bindNoticeDialog();
this.setName();
if (!this.objName) { return; }
this.bindResetEvents();
this.createNoticeDialog();
$(window).bind("unload." + this.name, { instance: this }, this.saveState);
}
};
EDIT:
I did a console.log on the in the for loop and the value of console.log(data.value[i]) at $e.is(":checkbox") is 0
We are using the jquery library jquery_remember_state and my problem was a bug they had where similar names of checkboxes would return the same value even if they had different values. We are using simple_form and it adds a hidden value for checkbox so it would give us the bug when trying to restore state.
The change I had to make was this:
if ($e.is(":checkbox") && data[i].value) {
$e = $e.filter("[value=\"" + data[i].value + "\"]");
if ($e.length) {
$e.prop("checked", true);
}
}
Here's the file with the full code incase anyone ever experiences this problem:
https://github.com/RepairShopr/jquery_remember_state/blob/multiple-checkboxes/source/javascripts/jquery.remember-state.js
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");
}
});
}
I am trying to explicitly get the system properties from my table but it is not working. I can see that the URL is returning all the data including these fields if I use https://myservice.azure-mobile.net/tables/todoitem?__systemProperties=* but on the code I cannot get it as item.__version or item.version. I have tried adding todoitemtable = WindowsAzure.MobileServiceTable.SystemProperties.All; but no success! I have also looked at http://azure.microsoft.com/en-us/documentation/articles/mobile-services-html-validate-modify-data-server-scripts/ but this is adding a new column instead of using the existing system columns.
$(function() {
var client = new WindowsAzure.MobileServiceClient('https://ib-svc-01.azure-mobile.net/', 'key');
var todoItemTable = client.getTable('todoitem');
// = WindowsAzure.MobileServiceTable.SystemProperties.All;
// Read current data and rebuild UI.
// If you plan to generate complex UIs like this, consider using a JavaScript templating library.
function refreshTodoItems() {
var query = todoItemTable.where({ complete: false });
query.read().then(function(todoItems) {
var listItems = $.map(todoItems, function(item) {
return $('<li>')
.attr('data-todoitem-id', item.id)
.append($('<button class="item-delete">Delete</button>'))
.append($('<input type="checkbox" class="item-complete">').prop('checked', item.complete))
.append($('<div>').append($('<input class="item-text">').val(item.id))
.append($('<span class="timestamp">'
+ (item.createdAt && item.createdAt.toDateString() + ' '
+ item.createdAt.toLocaleTimeString() || '')
+ '</span>')));
});
$('#todo-items').empty().append(listItems).toggle(listItems.length > 0);
$('#summary').html('<strong>' + todoItems.length + '</strong> item(s)');
}, handleError);
}
function handleError(error) {
var text = error + (error.request ? ' - ' + error.request.status : '');
$('#errorlog').append($('<li>').text(text));
}
function getTodoItemId(formElement) {
return $(formElement).closest('li').attr('data-todoitem-id');
}
// Handle insert
$('#add-item').submit(function(evt) {
var textbox = $('#new-item-text'),
itemText = textbox.val();
if (itemText !== '') {
todoItemTable.insert({ text: itemText, complete: false }).then(refreshTodoItems, handleError);
}
textbox.val('').focus();
evt.preventDefault();
});
// Handle update
$(document.body).on('change', '.item-text', function() {
var newText = $(this).val();
todoItemTable.update({ id: getTodoItemId(this), text: newText }).then(null, handleError);
});
$(document.body).on('change', '.item-complete', function() {
var isComplete = $(this).prop('checked');
todoItemTable.update({ id: getTodoItemId(this), complete: isComplete }).then(refreshTodoItems, handleError);
});
// Handle delete
$(document.body).on('click', '.item-delete', function () {
todoItemTable.del({ id: getTodoItemId(this) }).then(refreshTodoItems, handleError);
});
// On initial load, start by fetching the current data
refreshTodoItems();
});
I was trying to access the system properties from within the API scripts and found this and thought it was useful and relevant: http://www.brandonmartinez.com/2014/10/22/retrieve-system-properties-in-azure-mobile-services-javascript-backend/
Basically you can do this (example from the post):
myTable.read({
systemProperties: ['__createdAt', '__updatedAt'],
success: function(tableEntries) {
// So on and so forth
}
}
I am stuck with Social login (Facebook, Google and twitter) through Phonegap.
I have googled and found so many solutions, but they don't work on either platform (i.e: android or iOS).
Does any one have implemented social login in his/her app using phonegap?
If any one could provide me the running code, that would be appreciated.
Thanks,
Sabir
I know it's probably late to answer your particular question but I have had the same issue - all of the current (September 2016) scripts, snippets and libraries for social login in PhoneGap/Cordova that I have tried did not work so I made some simple functions from scratch which may still be useful to people ending up here. You can use them to log the user in with LinkedIn, Facebook and Google(+). I have also made some simple functions that retrieve some basic user information from the access token that is returned by logging the user in with the given network. You can examine the functions but they usually save the token or/and the user data to localStorage for later usage. They have been tested in September 2016 and work perfectly. I hope that this would help other people who also land on failing snippets around the web.
You can just insert the code and use the functions whenever you want. It requires jQuery and PhoneGap's InAppBrowser (besides having made apps/clients in the social media in order to fill the app id and app secret).
As a side note, it is not the best move to store the client secret directly in the PhoneGap application as the source can be viewed by malevolent people.
The code can be refactored at many places, so feel free to do that, but it does the trick. You may also have to handle cases where the user cancels the login process.
var facebookLogin = function(appId, appSecret, successCb,errCb) {
/*$.get("https://graph.facebook.com/oauth/access_token?client_id=" + appId + "&client_secret=" +appSecret + "&grant_type=client_credentials", function(res) {
if (res.indexOf("access_token=") !== -1) {
successCb(res.replace("access_token=", "").trim());
}
else {
errCb(res);
}
})
*/
var ref = window.open("https://www.facebook.com/dialog/oauth?display=popup&response_type=token&client_id="+appId+"&redirect_uri="+"http://anyurlhere.com", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("#access_token") !== -1) {
localStorage.fbToken = evt.url.split("#access_token=")[1];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.fbToken);
})
}
}
})
}
var linkedinLogin = function(appId,appSecret,successCb,errCb) {
var ref = window.open("https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id="+appId+"&redirect_uri="+(encodeURI("http://anyurlhere.com"))+"&state=987654321&scope=r_basicprofile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("code=") !== -1) {
var code = evt.url.split("code=")[1];
code = code.split("&")[0];
//TODO: get actual token to access user profile
$.post("https://www.linkedin.com/oauth/v2/accessToken", {"grant_type": "authorization_code", "code": code, "redirect_uri":encodeURI("http://anyurlhere.com"), "client_id":appId,"client_secret":appSecret}, function(data) {
for (key in data) {
if (key == 'access_token') {
localStorage.linkedinToken = data[key];
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.linkedinToken);
})
}
}
})
}
}
})
}
var googleLogin = function(appId, appSecret, successCb, errCb) {
var ref = window.open("https://accounts.google.com/o/oauth2/v2/auth?response_type=token&client_id=" + appId + "&redirect_uri="+encodeURI("http://anyurlhere.com")+"&scope="+encodeURIComponent("email profile")+"&state=profile", "_blank", "location=no");
ref.addEventListener("loadstop", function(evt) {
if (evt.url.indexOf("anyurlhere.com") !== -1) {
if (evt.url.indexOf("access_token=") !== -1) {
var accessToken = evt.url.split("access_token=")[1];
accessToken = accessToken.split("&")[0];
localStorage.gToken = accessToken;
ref.close();
ref.addEventListener("exit", function() {
successCb(localStorage.gToken);
})
}
}
})
}
var getGoogleInfo = function(successCb, errCb) {
//get basic user profile
$.get("https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=" + localStorage.gToken, function(userInfo) {
successCb(userInfo);
})
}
var getFacebookInfo = function(successCb, errCb) {
//get basic user profile-name
$.get("https://graph.facebook.com/me?fields=email,name,picture&access_token=" + localStorage.fbToken, function(userInfo) {
var myInfo = {};
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.email) {
myInfo.email = userinfo.email;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture.data.url;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
// localStorage.myInfo = myInfo;
})
}
//get basic data for linked in
var getLinkedinInfo = function(successCb, errCb) {
$.ajax({
url: "https://api.linkedin.com/v1/people/~?format=json",
headers: {
"Authorization": "Bearer " + localStorage.linkedinToken
},
success: function(userInfo) {
var myInfo = {};
if (userInfo.firstName && userInfo.lastName) {
myInfo.name = userInfo.firstName + " " + userInfo.lastName;
}
if (userInfo.headline) {
myInfo.linkedinHeadline = userInfo.headline;
}
localStorage.myInfo = JSON.stringify(myInfo);
successCb(myInfo);
},
fail: function(err) {
alert(err);
for (key in err) {
alert(key);
alert(err[key]);
}
}
})
}
//example of logging in the user with Google + and getting his/her data
googleLogin("93-54932-423-fkfew.apps.googleusercontent.com", "", function(accessToken) {
getGoogleInfo(function(userInfo) {
var myInfo = {};
alert(userInfo.name);
if (userInfo.email) {
myInfo.email = userInfo.email;
}
if (userInfo.name) {
myInfo.name = userInfo.name;
}
if (userInfo.given_name) {
myInfo.firstName = userInfo.given_name;
}
if (userInfo.familyName) {
myInfo.familyName = userInfo.family_name;
}
if (userInfo.picture) {
myInfo.picture = userInfo.picture;
}
I'm working on a validation form, I'm sending the data from the html fields with JS pulling the validation with a php document and sending it back via AJAX, it works pretty fine in Chrome but not Internet Explorer (I'm testing it in IE9):
function Checkfiles() {
var fup = document.getElementById('flUpload');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
var chkext = ext.toLowerCase();
if(chkext=="gif" || chkext=="jpg" || chkext=="jpeg" || chkext=="png") { return true; } else { return false; }
} // Checkfiles
function Checksize() {
var iSize;
if ($("#flUpload")[0].files[0]){ iSize = ($("#flUpload")[0].files[0].size / 1024);}
if(Checkfiles()==true && iSize <= 51.200) { return true; } else { return false; }
} //Checksize
$(document).ready(function() {
$("#ff1").submit(function(e){
// prevent submit
e.preventDefault();
var email = document.getElementById("email").value;
var title = document.getElementById("title").value;
var url = document.getElementById("url").value;
var parametros = {"emaail":email, "tiitle":title, "uurl":url};
$.ajax({
data: parametros,
url: 'validate.php',
type: 'post',
context: this,
error: function (response) {
alert("An error has occurred! Try Again!");
},
success: function (response) {
if($.trim(response)=='b' && Checksize()==true) {
this.submit(); // submit, bypassing jquery bound event
}
else {
if (Checksize()==true) {
$("#ajax_call_val").html('<div id="validation"><ul>'+response+'</ul></div>');
} else {
if(response!='b') {
$("#ajax_call_val").html('<div id="validation"><ul>'+response+'<li>Only GIF, PNG, JPG images, smaller than 50 KB</li></ul></div>');
} else { $("#ajax_call_val").html('<div id="validation"><ul><li>Only GIF, PNG, JPG images, smaller than 50 KB</li></ul></div>'); }
}
}
}
});
});
});
Any wonder why is not working in IE? Thanks in advance.