I'm trying to get the contacts from google using javascript api:
$(document).on('click', '#connect_to_google', function() {
$('body').addClass('loading');
var config = {
client_id: GOOGLE_CP_CIENT_ID,
scope: 'https://www.google.com/m8/feeds'
};
gapi.auth.init(function() {
gapi.auth.authorize(config, function() {
var token = gapi.auth.getToken();
if (null !== token && (typeof token.access_token !== 'undefined')) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json&v=3.0",
dataType: "json",
cache: false,
success: function(data) {
//doStuff(data);
$('body').removeClass('loading');
},
error: function (xhr, error) {
$('body').removeClass('loading');
},
complete: function (xhr, error) {
$('body').removeClass('loading');
}
});
} else {
$('body').removeClass('loading');
}
});
});
});
The moment the client clicks the login button, the page displays a layer over it ($('body').addClass('loading');), to restrict any user interaction outside google auth page.
All works well, except for the situation when the user closes the google auth window manually, then nothing happens.
Is there any way to check if the user closed that window, to call the $('body').removeClass('loading');?
Or is there any way to open the gapi.auth.authorize window in a modal dialog container? That way I could very easy check it's status.
This seems to do the trick:
(function(wrapped) {
window.open = function() {
var win = wrapped.apply(this, arguments);
var i = setInterval(function() {
if (win.closed) {
clearInterval(i);
$('body').removeClass('loading');
}
}, 100);
};
})(window.open);
It's not the best solution, but it does the work
Related
I am using Bootstrap Modal Js. However, whenever the modal pops up , I am getting this error
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
Also, in one page I am getting the erorr below when the modal launches using
if (auth=="False"){
setTimeout(function(){
if ($('#registerModal').hasClass('show')){
}else{
$('.register-btn').trigger('click');
}
}, 25000);
}
Error:
jquery.validate.unobtrusive.min.js:5 Uncaught TypeError: Cannot set property 'unobtrusive' of undefined
at jquery.validate.unobtrusive.min.js:5
at jquery.validate.unobtrusive.min.js:5
Here is the js
/*
django-bootstrap-modal-forms
version : 2.0.1
Copyright (c) 2020 Uros Trstenjak
https://github.com/trco/django-bootstrap-modal-forms
*/
(function ($) {
// Open modal & load the form at formURL to the modalContent element
var modalForm = function (settings) {
$(settings.modalID).find(settings.modalContent).load(settings.formURL, function () {
settings.asyncSettings=true;
settings.async = true;
$(settings.modalID).modal("show");
$(settings.modalForm).attr("action", settings.formURL);
addEventHandlers(settings);
});
};
var addEventHandlers = function (settings) {
// submitBtn click handler
$(settings.submitBtn).on("click", function (event) {
isFormValid(settings, submitForm);
});
// Modal close handler
$(settings.modalID).on("hidden.bs.modal", function (event) {
$(settings.modalForm).remove();
});
};
// Check if form.is_valid() & either show errors or submit it via callback
var isFormValid = function (settings, callback) {
$.ajax({
type: $(settings.modalForm).attr("method"),
url: $(settings.modalForm).attr("action"),
data: new FormData($(settings.modalForm)[0]),
contentType: false,
processData: false,
beforeSend: function () {
$(settings.submitBtn).prop("disabled", true);
},
success: function (response) {
if ($(response).find(settings.errorClass).length > 0) {
// Form is not valid, update it with errors
$(settings.modalID).find(settings.modalContent).html(response);
$(settings.modalForm).attr("action", settings.formURL);
// Reinstantiate handlers
addEventHandlers(settings);
} else {
// Form is valid, submit it
callback(settings);
}
}
});
};
// Submit form callback function
var submitForm = function (settings) {
if (!settings.asyncUpdate) {
$(settings.modalForm).submit();
} else {
var asyncSettingsValid = validateAsyncSettings(settings.asyncSettings);
var asyncSettings = settings.asyncSettings;
if (asyncSettingsValid) {
var formdata = new FormData($(settings.modalForm)[0]);
// Add asyncUpdate and check for it in save method of CreateUpdateAjaxMixin
formdata.append("asyncUpdate", "True");
$.ajax({
type: $(settings.modalForm).attr("method"),
url: $(settings.modalForm).attr("action"),
data: formdata,
contentType: false,
processData: false,
success: function (response) {
var body = $("body");
if (body.length === 0) {
console.error("django-bootstrap-modal-forms: <body> element missing in your html.");
}
body.prepend(asyncSettings.successMessage);
// Update page without refresh
$.ajax({
type: "GET",
url: asyncSettings.dataUrl,
dataType: "json",
success: function (response) {
// Update page
$(asyncSettings.dataElementId).html(response[asyncSettings.dataKey]);
// Add modalForm to trigger element after async page update
if (asyncSettings.addModalFormFunction) {
asyncSettings.addModalFormFunction();
}
if (asyncSettings.closeOnSubmit) {
$(settings.modalID).modal("hide");
} else {
// Reload form
$(settings.modalID).find(settings.modalContent).load(settings.formURL, function () {
$(settings.modalForm).attr("action", settings.formURL);
addEventHandlers(settings);
});
}
}
});
}
});
}
}
};
var validateAsyncSettings = function (settings) {
var missingSettings = [];
if (!settings.successMessage) {
missingSettings.push("successMessage");
console.error("django-bootstrap-modal-forms: 'successMessage' in asyncSettings is missing.");
}
if (!settings.dataUrl) {
missingSettings.push("dataUrl");
console.error("django-bootstrap-modal-forms: 'dataUrl' in asyncSettings is missing.");
}
if (!settings.dataElementId) {
missingSettings.push("dataElementId");
console.error("django-bootstrap-modal-forms: 'dataElementId' in asyncSettings is missing.");
}
if (!settings.dataKey) {
missingSettings.push("dataKey");
console.error("django-bootstrap-modal-forms: 'dataKey' in asyncSettings is missing.");
}
if (!settings.addModalFormFunction) {
missingSettings.push("addModalFormFunction");
console.error("django-bootstrap-modal-forms: 'addModalFormFunction' in asyncSettings is missing.");
}
if (missingSettings.length > 0) {
return false;
}
return true;
};
$.fn.modalForm = function (options) {
// Default settings
var defaults = {
modalID: "#modal",
modalContent: ".modal-content",
modalForm: ".modal-content form",
formURL: null,
errorClass: ".invalid",
submitBtn: ".submit-btn",
asyncUpdate: true,
asyncSettings: {
closeOnSubmit: false,
successMessage: null,
dataUrl: null,
dataElementId: null,
dataKey: null,
addModalFormFunction: null
}
};
// Extend default settings with provided options
var settings = $.extend(defaults, options);
this.each(function () {
// Add click event handler to the element with attached modalForm
$(this).click(function (event) {
// Instantiate new form in modal
modalForm(settings);
});
});
return this;
};
}(jQuery));
I want to show the a toast notification after the page is reloaded that says that the file is uploaded. This is what I got so far
_fileUploads.delete = function(reload_on_return) {
var filtered = root.fileUploads().filter(_ => _._id() == _fileUploads._id());
var index = root.fileUploads.indexOf(filtered = filtered[0]);
filtered = ko.toJS(filtered);
swal({
text: 'Are you sure you want to delete this file?',
buttons: true,
dangerMode: true,
icon: 'warning'
}).then(function (allowDelete) {
if (allowDelete) {
$.ajax({
type: 'DELETE',
url: '/api/gridfs/files/' + filtered._id,
statusCode: {
204: function(response) {
toastrTrigger('The File has been Deleted')
if (reload_on_return) {
setTimeout( function() {
location.reload();
}, 0001);
}
}
},
error: function (xhr, status, error) {
console.log(xhr);
}
});
}
});
}
This only refreshes the page and not show the notification
This is the toastrtrigger function()
function toastrTrigger(message, title, type) {
setTimeout(function() {
toastr.options = {
closeButton: true,
progressBar: true,
showMethod: 'slideDown',
timeOut: 4000
};
toastr[type || "success"](message, title || 'File Uploads Repository');
}, 500);
}
Scripts do not persist after the page has been reloaded: once the document is closed, all scripts associated with the document go away with it. There's no way around that. You'll have to somehow pass information to the page you navigate to purely through the URL.
One solution is to pass a query string to the reloaded page:
if (reload_on_return) {
window.location.href = window.location.pathname + '?deleteSuccess=1';
}
Then, on the same page, on page load, do a check to see if a query string are present:
const { search } = window.location;
const deleteSuccess = (new URLSearchParams(search)).get('deleteSuccess');
if (deleteSuccess === '1') {
// The page was just reloaded, display the toast:
toastrTrigger('The file has been deleted');
}
Another solution is to save the data in sessionStorage instead, and retrieve data from sessionStorage on page load to identify whether a notification should be displayed.
If user changes the formID what should i do to make the ajax call and jquery validation success.
<form id="formID" action="">
(function ($, W, D)
{
var JQUERY4U = {};
JQUERY4U.UTIL =
{
setupFormValidation: function ()
{
$("#formID").validate({
rules: {
input:"required",
},
messages: {
input: "required",
},
submitHandler: function (form) {
var form = $('#formID')[0];
var formData = new FormData(form);
$.ajax({
type: 'post',
url: '/',
data: formData,
contentType: false,
processData: false,
success: function(data) {
if (data.response == true) {
alert('true');
} else {
alert('false');
}
}, error: function (jqXHR, exception) {
console.log(jqXHR.status);
}
});
}
});
}
}
$(D).ready(function ($) {
JQUERY4U.UTIL.setupFormValidation();
});
})(jQuery, window, document);
Just remove var form = $('#formID')[0]; in the submitHandler. The form element is already exposed as an argument
The plugin will have already initialized before an ID could be changed by user in console and probably before any userscript or browser extension also
Changing an ID does not affect events already attached to that element.
Beyond that you can't control what a user does in their browser and just need to make sure your back end is secure
I'm having an issue with a facebook app on Android 4.3 (and maybe other versions but 5 & 6 seem okay).
It's a web app, users can share pictures and their friends can go and vote for it, but they have to be logged in to the app. I'm using the JS SDK.
Facebook opens the link in it's own browser and the FB.login seem to fail. I have an "unknown" status so I try a FB.login and nothing seems to happen...
If I open the same link in chrome, everything works fine, Facebook asks for the permissions (after i got a "not_authorized" status) and I can vote.
Is there a way to make it work with the old versions of the facebook browser ? Or maybe a way to know the user is using this old browser so I can put an error message?
See comments for the fiddle
// Rate a picture
function rateApic(domLink) {
var $link = $(domLink);
$.ajax({
url: '/rateAPicture',
type: 'POST',
dataType: 'json',
data: {
id: $link.attr('data-entry')
},
success: function(result, status) {
var content = result.message;
switch (result.returnCode) {
case 0: // OK
$link.parent().find('.nbRatings').html(result.nbRatings); // rate number +1
popupManager(content); // display success message
break;
case 1: // Not logged in
loginFb('rateAphoto', $link);
break;
default:
popupManager(content); // display error message
}
},
error: function(result, status, error) {},
complete: function(result, status) {}
});
};
// Check user login state
function checkLoginState() {
var status = "";
FB.getLoginStatus(function(response) {
status = response.status;
});
return status;
}
// Connect to facebook app
function loginFb(redirectUrl, object) {
var loginState = checkLoginState();
if (loginState === 'unknown' || loginState === "not_authorized" || loginState == undefined) {
// within Facebook's app built-in browser on Adroid (4.3 & 5.1.1 and other versions but 6.0.1 is okay)
// loginState is always unknown
FB.login(function(response) {
if (response.status === 'connected') {
loginToApp(redirectUrl, object);
};
}, {
scope: 'public_profile,email,user_friends'
});
} else if (loginState === 'connected') {
loginToApp(redirectUrl, object);
}
}
// Connect to local app
function loginToApp(redirectUrl, object) {
// Connect to local app with facebook informations
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<a onclick="rateApic(this);" data-entry="42" href="#">Like</a>
Facebook says it's not a bug (it's for security reasons) and they won't fix it so...
This is what I did :
if (loginState === 'unknown' || loginState === "not_authorized" || loginState == undefined) {
FB.login(function(response) {
if (response.status === 'connected') {
loginToApp(redirectUrl, object);
};
}, {
scope: rights
});
if (checkLoginState() === 'unknown') {
// Redirect to the login page
$.ajax({
url: '/GetFacebookAppId',
type: 'POST',
dataType: 'json',
success: function(result, status) {
window.location.href = 'https://www.facebook.com/dialog/oauth?' + 'client_id=' + result.appId + '&redirect_uri=' + redirectUrl + '&scope=' + rights;
},
error: function(result, status, error) {},
complete: function(result, status) {}
});
}
}
So anytime the FB.login is not working and the FB.getLoginStatus returns "unknown", I redirect the user to the login page.
I am implementing a video conference room and I have a variable (room_status) which holds the status of the room (0 = close & 1 = open). Now this variable is only accessible my the client who clicks open-room.
I need to save the room_status variable to the server so that it can be accessed on other client's side. Here is a piece of my code:
var room_status = 0; //room closed
$('#open-room').click(function () {
// http://www.rtcmulticonnection.org/docs/open/
$.ajax({
type: 'GET',
url: "../invite",
data: {
videoconference_id: $('#meetingID').val(),
invitee_id: 1111,
status: "Accepted"
},
success: function() {
alert("success!");
},
error: function() {
alert("fail");
}
});
//room_status = 1; //room opened
rmc.open();
rmc.streams.mute({video : true});
document.getElementById("on-off-video").style.color= 'red';
});
$('#join-room').click(function () {
if(room_status) {
// http://www.rtcmulticonnection.org/docs/connect/
rmc.connect();
rmc.streams.mute({video: true});
document.getElementById("on-off-video").style.color= 'red';
} else {
console.log("Waiting for meeting organizer");
}
});
Ajax is your friend.
Here is an example from a prject of mine with jquery ui :
function prepare_ajax_button(l){
$("#button").button().click(function(event,ui){
$.ajax({type: "GET",data: {"arg1":l},url: "update_variable.php",success: function(data){
alert("Success ?!");
},error: function(data){alert("Problem ?!");}});
});
}
The page "update_variable.php" can for instance write the variable in a text file, mysql...