IN.UI.Share() success callback not working - javascript

I'd like to use Linkedin share functionality with my custom button, but the callback function won't be called on success, any idea?
This is my code:
var sh = IN.UI.Share().params(
{
url: "someUrl"
});
sh.success(function(){console.log('Linkedin share success')});
sh.place();

Created a mini-pen which you can view here https://codepen.io/craigiswayne/pen/Bqqbjz
Documentation on this subject can be found here: https://developer.linkedin.com/docs/share-on-linkedin
IN.Event.on(IN, 'systemReady', function() {
var shareLink = document.getElementById('shareLink');
shareLink.onclick = function(){
event.preventDefault();
var params = {
"comment": "Check out developer.linkedin.com! https://www.example.com",
"visibility": {
"code": "anyone"
}
};
IN.API.Raw("/people/~/shares?format=json")
.method("POST")
.body(JSON.stringify(params))
.result(function(xhrResult){
alert('success :)');
})
.error(function(errorObj){
alert('Error');
alert(errorObj.errorMessage);
});
};
});

Related

How to add a process bar when you waiting for a response from the server

could someone help me with one problem? I want to add a process bar when you waiting for a response from the server (Django 3.x).
Step to reproduce:
On the page 'A' we have the form.
Enter data to form.
Submit POST request by clicking to button on the page 'A'.
Waiting for getting the result on the page 'A'.
Get the result on the page 'A'.
So, I want to add process bar after 4th and before 5th points on the page 'A'. When you will get the result on the page 'A' it should disappear.
Python 3.7
Django 3.x
You can use nprogress, it's a library used for progress bars. Use this inside the interceptor where you can config it for displaying only when request is in progress until finished.
There are lots of ways to do this. I think using jquery would be easier. Basically you just need to prevent submitting the page and do an Ajax request to server. something like
<script type='text/javascript'>
$(document).ready(function () {
$("form").submit(function (e) {
// prevent page loading
e.preventDefault(e);
$('#loadinAnimation').show();
// preapre formdata
$.ajax({
type: "yourRequestType",
url: "yourUrlEndpoint",
data: formdata,
success: function (data) {
$('#loadinAnimation').hide();
// do rest of the work with data
}
});
});
});
</script>
and show appropriate loading animation in your html part
<div id='loadinAnimation' style='display:none'>
<div>loading gif</div>
</div>
You can also do it using UiKit Library in Javascript on your Django Template Page.
Below code is when a file is Uploaded
In your template file (template.html)
<body>
..
<form>
<progress id="js-progressbar" class="uk-progress" value="0" max="100" hidden></progress>
...
<div class="uk-alert-danger uk-margin-top uk-hidden" id="upload_error" uk-alert></div>
...
</form>
</head>
<script type="text/javascript">
$(document).ready(function(){
var bar = document.getElementById('js-progressbar');
UIkit.upload('.js-upload-list', {
url: '',
name : "customer-docs",
params :{
"csrfmiddlewaretoken":"{{csrf_token}}"
},
method : "POST",
concurrent:1,
allow:'*.(csv|xlsx)',
beforeSend: function (environment) {
console.log('beforeSend', arguments);
// The environment object can still be modified here.
// var {data, method, headers, xhr, responseType} = environment;
},
beforeAll: function (args,files) {
console.log('beforeAll', arguments);
},
load: function () {
console.log('load', arguments);
},
error: function (files) {
console.log("---------------")
},
complete: function () {
console.log('complete', arguments);
},
loadStart: function (e) {
console.log('loadStart', arguments);
bar.removeAttribute('hidden');
bar.max = e.total;
bar.value = e.loaded;
},
progress: function (e) {
console.log('progress', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
loadEnd: function (e) {
console.log('loadEnd', arguments);
bar.max = e.total;
bar.value = e.loaded;
},
completeAll: function (data) {
console.log('completeAll', arguments);
console.log('completeAll', data);
let redirect_loc = ""
setTimeout(function () {
bar.setAttribute('hidden', 'hidden');
}, 1000);
// This is the response from your POST method of views.py
data.responseText = JSON.parse(data.responseText)
if(data.responseText.status == 201){
// swal is another library to show sweet alert pop ups
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Done: true
},
}).then((value) => {
switch (value) {
case "Done":
window.location.href = ""
break;
}
});
}
else if(data.responseText.status == 500){
swal({
icon: data.responseText.status_icon,
closeOnClickOutside: true,
text: data.responseText.message,
buttons: {
Ok: true
},
}).then((value) => {
switch (value) {
case "Ok":
window.location.href = ""
break;
}
});
}
}
});
// This block of code is to restrict user to upload only specific FILE formats (below example is for CSV & XLSX files)
(function() {
var _old_alert = window.alert;
window.alert = function(e) {
console.log(e)
if(e.includes("csv|xlsx") || e.includes("Invalid file type")) {
$("#upload_error").html("Invalid file format. Valid formats are CSV, XLSX").removeClass('uk-hidden')
}else if(e.includes("Internal Server Error")) {
$("#upload_error").html("Internal Server Error Kindly upload Documents again").removeClass('uk-hidden')
}
else {
_old_alert.apply(window,arguments);
$("#upload_error").addClass('uk-hidden').html("")
}
};
})();
});
</script>
On your views.py you can do your computation and once done, you can return a response like below
resp_json = {
"status" : 201,
"status_icon" : "success",
"url" : "/",
"message": message
}
return HttpResponse(json.dumps(resp_json))
For more info on SWAL (Sweet Alerts), visit https://sweetalert.js.org/guides/

Angular apply same success and error function bodies to different $http requests

I am not sure what exact keywords to search for this. So I decided to ask here for help.
I think this is more a JavaScript related question rather than angular. Anyways here is my problem.
I am in a DRY situation (don't repeat yourself). I am trying to merge the two of my $http.put and $http.delete methods' success and error function under single one, because they share the same functionalities.
Here is my current code
// Delete permanenty button action
$scope.delete_donor = function(form) {
$http.delete(url)
.success(function() {
// #TODO DRY? DELETE UPDATE delete_donor update_donor
response.ipv4 = INT_TO_STR_IP(response.ipv4)
// Show deleted data to user after operation
$scope.donor.saved_data = response.saved_data
$location.path("/")
})
.error(function(response) {
$scope.donor.validation_errors = SERVER_VALIDATION_ERROR(response)
})
}
// Save changes button action
$scope.update_donor = function(form) {
var body = $scope.donor.data
delete body.ipv4
$http.put(url, body)
.success(function(response) {
// #TODO DRY? DELETE UPDATE delete_donor update_donor
response.ipv4 = INT_TO_STR_IP(response.ipv4)
// Show new updated data to user after operation
$scope.donor.saved_data = response.saved_data
$location.path("/")
})
.error(function(response) {
$scope.donor.validation_errors = SERVER_VALIDATION_ERROR(response)
})
As you can see $http.delete().success().error() and $http.put().success().error() methods are same.
I am trying to do something like
WHATSTHIS unify(response) {
WOOT .success(function(response) { // SAME CODE BODY })
WOOT .error(function(response) { // SAME CODE BODY })
}
// Delete permanenty button action
$scope.delete_donor = function(form) {
$http.delete(url)
.unify(response)
}
// Save changes button action
$scope.update_donor = function(form) {
var body = $scope.donor.data
delete body.ipv4
$http.put(url, body)
.unify(response)
I just know one way to achieve something similiar which is:
var unifySuccess = function(response) {
// DO
}
var unifySuccess = function(response) {
// DO
}
// Delete permanenty button action
$scope.delete_donor = function(form) {
$http.delete(url)
.sucesss(unifySuccess)
.error(unifyError)
But maybe there is an other clever way to do this?
Thanks for your help.
what you could do is create your own http request service that will do these functionalities and return the promise as a response
something like this
angular.module('myApp')
.service('proxyHttp', function($http) {
return function(options) {
return $http(options)
.then(
function() {
// success callback
},
function() {
// error callback
});
}
})
Update: For example
angular.module('myApp', [])
.service('proxyHttp', function($http, $q) {
return function(options) {
console.log('Run proxy http');
return $http(options)
.then(
function(response, status) {
console.log('always do this on success');
// success callback
return response;
// here we return the response or what ever you want,
// and we can continue handling it
})
.catch(function() {
console.log('we failed!');
// error callback
return $q.reject();
})
}
})
.controller('testController', function($scope, proxyHttp) {
$scope.testError = function() {
console.log('Run test error method');
proxyHttp({
url: 'http://www.google.com',
method: 'GET'
})
.then(
function() {})
.catch(function() {
console.log('we continue handling our error here...');
});
}
$scope.testSuccess = function() {
console.log('Run test success method');
proxyHttp({
url: 'http://httpbin.org/ip',
method: 'GET'
})
.then(
function(response) {
console.log('continue chaining after success for the original promise');
console.log('Response data: '
response.data.origin);
console.log('read more about pomise and chaining here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise');
})
.catch(function() {
console.log('error');
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<div ng-controller="testController">
<button ng-click="testError()">Click Me for error!</button>
<br/>
<br/>
<button ng-click="testSuccess()">Click Me for success!</button>
</div>
</div>
Depending on your actual use case, this may end up sacrificing too much readability to be helpful, but since you asked specifically for cleverness:
function attachHttpResponseHandling(httpPromise) {
httpPromise
.success(function(response) {
response.ipv4 = INT_TO_STR_IP(response.ipv4);
// Show new updated data to user after operation
$scope.donor.saved_data = response.saved_data;
$location.path("/");
})
.error(function(response) {
$scope.donor.validation_errors = SERVER_VALIDATION_ERROR(response);
})
;
}
// Delete permanenty button action
$scope.delete_donor = function(form) {
attachHttpResponseHandling($http.delete(url));
};
// Save changes button action
$scope.update_donor = function(form) {
var body = $scope.donor.data;
delete body.ipv4;
attachHttpResponseHandling($http.put(url, body));
};

I want the push notification work for registered member

i am trying to register the devuice fror push notification using the phonegap plugin. In the success action of the AJAX i call the registration action but its not alerting the registration ID. can anyone figure out it.
here the index.js
// Begin boilerplate code generated with Cordova project.
var app = {
// Application Constructor
initialize: function () {
this.bindEvents();
},
// Bind Event Listeners
//
// Bind any events that are required on startup. Common events are:
// 'load', 'deviceready', 'offline', and 'online'.
bindEvents: function () {
document.addEventListener('deviceready', this.onDeviceReady, false);
connectionStatus = navigator.onLine ? 'online' : 'offline';
if(connectionStatus !="online")
{
//$.mobile.changePage($("#seconddiv"));
window.location.replace("no-internet.html");
}
},
// deviceready Event Handler
//
// The scope of 'this' is the event. In order to call the 'receivedEvent'
// function, we must explicitly call 'app.receivedEvent(...);'
onDeviceReady: function () {
},
setupPush: function() {
console.log('calling push init');
var push = PushNotification.init({
"android": {
"senderID": "xxxxxxxxx"
},
"ios": {
"sound": true,
"vibration": true,
"badge": true
},
"windows": {}
});
console.log('after init');
push.on('registration', function(data) {
console.log('registration event: ' + data.registrationId);
var oldRegId = localStorage.getItem('registrationId');
if (oldRegId !== data.registrationId) {
// Save new registration ID
localStorage.setItem('registrationId', data.registrationId);
// Post registrationId to your app server as the value has changed
}
alert(localStorage.getItem('registrationId'));
var parentElement = document.getElementById('registration');
var listeningElement = parentElement.querySelector('.waiting');
var receivedElement = parentElement.querySelector('.received');
listeningElement.setAttribute('style', 'display:none;');
receivedElement.setAttribute('style', 'display:block;');
});
push.on('error', function(e) {
console.log("push error = " + e.message);
});
push.on('notification', function(data) {
console.log('notification event');
navigator.notification.alert(
data.message, // message
null, // callback
data.title, // title
'Ok' // buttonName
);
});
}
};
i call the app.setupPush(); inside the ajax success handler
here the signin.js
var KPSCtuts = KPSCtuts || {};
$("#btn-submit").click(function(){
var userName = $("#txt-username").val();
var password = $("#txt-password").val();
//alert(KPSCtuts.Settings.Url);
$("#loaderIcon").show();
$.ajax({
type: 'POST',
dataType: "json",
url: KPSCtuts.Settings.Url,
data:"username=" + userName + "&password=" + password + "&login=",
success: function (resp) {
if (resp.success === true) {
// Create session.
var today = new Date();
var expirationDate = new Date();
expirationDate.setTime(today.getTime() + KPSCtuts.Settings.sessionTimeoutInMSec);
KPSCtuts.Session.getInstance().set({
userProfileModel: resp.userProfileModel,
userId: resp.userId,
userName: resp.userName,
sessionId: resp.sessionId,
expirationDate: expirationDate,
keepSignedIn:$('#chck-rememberme').is(":checked")
});
app.setupPush();
// Go to main menu.
window.location.replace("index.html");
$("#loaderIcon").hide();
return;
} else {
if (resp.extras.msg) {
$("#ctn-err").html("<p>"+resp.extras.msg+"</p>");
$("#dlg-invalid-credentials").show();
$("#ctn-err").addClass("bi-ctn-err").slideDown();
$("#loaderIcon").hide();
}
}
},
error: function (e) {
//$.mobile.loading("hide");
//console.log(e.message);
// TODO: Use a friendlier error message below.
$("#ctn-err").html("<p>1-Oops! KPSCtuts had a problem and could not log you on. Please try again in a few minutes.</p>");
$("#ctn-err").addClass("bi-ctn-err").slideDown();
$("#loaderIcon").hide();
}
});
});
Try the registration code in onDeviceReady function.Registration ID will be same until you uninstall the app.
In HTML:
<body onload="onLoad()">
In Script:
function onLoad()
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
var push = PushNotification.init({
"android": {
"senderID": "xxxxxxxxx"
},
"ios": {
"sound": true,
"vibration": true,
"badge": true
},
"windows": {}
});
push.on('registration', function(data) {
console.log('registration event: ' + data.registrationId);
});
push.on('error', function(e) {
console.log("push error = " + e.message);
});
push.on('notification', function(data) {
console.log('notification event');
navigator.notification.alert(
data.message, // message
null, // callback
data.title, // title
'Ok' // buttonName
);
});
}

Framework7: Login redirect

When user visits login.html page, localStorage is used to check if a user is logged in. The page should redirect to profile.html and display notofication message.
The message is displayed, but the page (login.html) is the same..
if( localStorage.user_login ) {
mainView.router.loadPage({url:'profile.html', ignoreCache:true, reload:true });
myApp.addNotification( {
message: 'Welcome '+ localStorage.user_username +'!'
} );
}
How can i make the page redirect if the user is logged in?
put this before myApp framework7 initialization.
$$(document).on('pageInit', function (e) {
var page = e.detail.page;
if (page.name === 'index') {
try{
var storedData = window.localStorage['f7form-'+ 'idofyourloginform'];
if(storedData) {
//do your ajax login request here
// if successful do your login redirect
mainView.router.loadPage({url:'profile.html', ignoreCache:true, reload:true });
}
}
);
Inside your Login page, use like this codes:
HTML
Log In
JavaScript
return {
methods: {
signIn: function () {
var $ = this.$;
var app = this.$app;
var username = $('input#demo-username-1').val();
var password = $('input#demo-password-2').val();
app.request.post('http://localhost:4103/api/User/Login?username='+username+'&password='+password, function (data) {
var obj = JSON.parse(data);
console.log(obj);
console.log(obj.success);
if (obj.success) {
app.data.IsLogin=true;
app.data.UserName='salman';
app.views.main.router.navigate(obj.RedirectUrl);
} else {
app.dialog.alert(obj.Message , function () {});
}
});
}
}
}
Try calling
myApp.closeModal('.login-screen.modal-in')
before
mainView.router.loadPage({url:'profile.html', ignoreCache:true, reload:true })
That should solve the problem.
login page ajax post and response in Framework7 with jquery
inside your my-app.js file use like this codes
myApp.onPageInit('sign-in', function(page) {
$('#loginb').click(function() {
$('#loginb').html('Please Wait...');
var fuid = $('#uid').val();
var fpass = $('#pass').val();
$.ajax({
url: 'chklogin.php',
data: {
"uid": fuid,
"pass": fpass
},
type: 'post',
success: function(returnedData) {
$('#loginb').html(returnedData);
if (returnedData == "Success") {
mainView.router.load({
url: 'deshboard.php',
ignoreCache: true
});
} else {
mainView.router.load({
url: 'login.php',
ignoreCache: true
});
}
}
});
});
});
Use this function with route name:
app.views.main.router.navigate('/profile');
But make sure app is which you initialize project such as:
var app = new Framework7({....});

Redirect to a react route using phonegap

I'm working with a react.js project and convert it into a mobile application, that part is ok, the idea is that the app must receive push notifications, once the user clicks the notification, it must change the react route, I've been trying this code but had not success the app doesn't change the route once the user clicks the notification, I had success getting the react-router instance, but i don't know how to use it properly to go to the desired route.
var app = {
initialize: function() {
this.bindEvents();
},
bindEvents: function() {
document.addEventListener('deviceready', this.onDeviceReady, false);
},
onDeviceReady: function() {
var mmjUser=localStorage.getItem("mmj-user");
if (mmjUser !== null) {
var push = PushNotification.init({
"android": {
"senderID": "491359499412",
"forceShow": 'true'
},
"ios": {
"alert": "true",
"badge": "true",
"sound": "true",
"senderID": "491359499412"},
"windows": {}
});
push.on('registration', function(data) {
console.log("registration event");
});
push.on('notification', function(data) {
console.log("notification event");
console.log(JSON.stringify(data));
var reactRouter=require('react-router');
reactRouter.HistoryLocation.replace('/waiting');
push.finish(function () {
console.log('finish successfully called');
});
});
push.on('error', function(e) {
console.log("push error");
});
}
}
};
app.initialize();
this is the reactRouter object that i'm getting
Thanks for your help!

Categories