Error in Google SignOut process Uncaught Error: nb JS - javascript

Just to make my code refactored I have written google SignOut function as follows
function googleSignOut() {
if (typeof module_google_login == 'undefined') {
return false;
}
gapi.load('auth2', function () {
var gApiAuth = gapi.auth2;
gApiAuth.init().then(doGoogleLogout(gApiAuth));
});
};
function doGoogleLogout(gApiAuth) {
console.log(gApiAuth);
var googleAuth = gApiAuth.getAuthInstance();
googleAuth.signOut().then(function () {
$.ajax({
type: 'POST',
url: '/account/logout/',
success: function () {
auth2.disconnect();
window.location = "/account";
}
});
});
}
But it gives an error in the console like this
Uncaught Error: nb
at tE (cb=gapi.loaded_0:201)
at jF.<anonymous> (cb=gapi.loaded_0:248)
at new _.C (cb=gapi.loaded_0:123)
at jF.BT (cb=gapi.loaded_0:248)
at Ay.Qv.a.<computed> [as signOut] (cb=gapi.loaded_0:227)
at doGoogleLogout (main.js:48)
at main.js:41
at platform.js:18
at Sa (platform.js:10)
at Y (platform.js:18)
But I implement it like this
function googleSignOut() {
if (typeof module_google_login == 'undefined') {
return false;
}
gapi.load('auth2', function () {
gapi.auth2.init().then(function () {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
$.ajax({
type: 'POST',
url: '/account/logout/',
success: function () {
window.location = "/account";
}
});
});
});
});
};
then it works fine though it does not look that good. If someone can tell me what is wrong with my previous implementation and what that is not working.

Problem is with this line
gApiAuth.init().then(doGoogleLogout(gApiAuth));.
For success handler of the promise, you need to pass functional reference not call the function directly. Here doGoogleLogout(gApiAuth) will be called before the promise is resolved. Change this to gApiAuth.init().then(()=>doGoogleLogout(gApiAuth))
Read more about from this link

Related

Bootstrap modal js is giving Synchronous XMLHttpRequest on the main thread is deprecated message

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));

How to call function method inside ajax success function?

How to call pagePresets.setFilter() inside $.ajax(){success} method?
self.setFilter.call('network', data.networks); returns
Uncaught TypeError: Cannot read property 'call' of undefined(…)
when self.setFilter('network', data.networks);
Uncaught TypeError: self.setFilter is not a function(…)
Code:
function pagePresets() {
this.loading = true;
this.isLoading = function () {
return this.loading;
};
this.setLoading = function (state) {
this.loading = state;
return;
};
/** this function loads saved filters */
this._loadFilters = function() {
jQuery.ajax({
type: 'post',
dataType: "json",
url: 'data.json',
success: function (data) {
//HOW TO CALL setFilter? this solution is not working
pagePresets.prototype.setFilter.call('network', data.networks);
}
});
};
}
pagePresets.prototype.setFilter = function (target, value) {
console.info(target + ' ' + value );
}
The call function takes as first argument a "context object". Take a deeper look at the call function here.
In the ajax callback function this or self doesn't refere to your class object anymore. And pagePresets is a function class with no static properties. So you need to get the object instance.
You need to specify which instance you want to call your prototype function with. I usualy declare a private property in my "class" wich holds a reference to the object for such scenarios where the context changes.
function pagePresets() {
//create a local variable here
var localInstance = this;
this.loading = true;
this.isLoading = function () {
return this.loading;
};
this.setLoading = function (state) {
this.loading = state;
return;
};
/** this function loads saved filters */
this._loadFilters = function() {
jQuery.ajax({
type: 'post',
dataType: "json",
url: 'data.json',
success: function (data) {
//Use the variable here to specify the correct context.
//the functions arguments need to be an array for the call function
pagePresets.setFilter.call(localInstance, [ 'network', data.networks ]);
}
});
};
}
pagePresets.prototype.setFilter = function (target, value) {
console.info(target + ' ' + value );
}
you can try to invoke that in the another function like this
function success() {
pagePresets.prototype.setFilter.call('network', data.networks);
}
function error() {
alert("error");
}
function searchEntity(id,userName, family) {
$.ajax({
type : "POST",
contentType : "application/json",
url : "http://localhost:8080/mvc-test/rest/user/searchAll?pageNumber=1&pageSize=2&&orderBy=userName asc",
headers: {'X-CSRF-TOKEN': getMetaContentByName('_csrf')},
data : JSON.stringify({
"id":id,
"userName" : userName,
"familyName" : family
}),
dataType : 'json',
success : success,
error : error
});
}
Another way is to pass the parent context into the success method or delegate.
In the code below, onAjaxResponseReceived function is called with with the reference to the parent (class) context self from which other methods func1 and func2 can be accessed.
class TestClass{
constructor(searchUrl) {
this.searchUrl = searchUrl;
}
bind() {
self = this;
$.ajax({
url: self.searchUrl,
type:"POST",
data: data,
success: function (responseData) {
self.onAjaxResponseReceived(self, responseData);
}
});
}
onAjaxResponseReceived(self, data) {
self.func1(data);
self.func2(data);
}
func1(data) {
console.log('func 1');
}
func2(data) {
console.log('func 2');
}
}

Ajax unit test using Jasmine "TypeError: Cannot read property 'done' of undefined"

function download() {
$.ajax({
method: 'GET',
url: 'http://jsonplaceholder.typicode.com/posts',
}).done(function(data) {
//processJasonData(data)
}).fail(function () {
//$fail();
})
}
Im trying to make unit test with Jasmine using ajax but i get "TypeError: Cannot read property 'done' of undefined".
describe('AJAX check', function () {
var url = "http://jsonplaceholder.typicode.com/posts";
it('test1', function () {
spyOn($, "ajax");
download(url);
expect($.ajax).toHaveBeenCalled();
});
});
Anyone know how to resolve this problem ? And how to check when ajax is done?
I think I should use promises and deferred in this case, so can someone explain them to me?
(I`m using jQuery > 1.5)
rest code :
function download(url) {
$.ajax({
method: 'GET',
url: url,
}).done(function(data) {
processJasonData(data)
}).fail(function () {
$fail();
})
}
function $fail() {
var error_msg_1 = '<div class="jumbotron text-center"><h1 style="size: 10px;color: red"> Faill </h1></div>';
$('.tresc').html(error_msg_1);
}
function processJasonData(data) {
var _data = $('.panel-group');
var dataTemplate = $('#item_tmp').html();
$.each(data, function (i, item) {
_data.append(Mustache.render(dataTemplate, item));
});
}
Jasmines spyOn blocks the call to the function and "swallows" it (returning undefined). To make it pass the call to the spied function use spyOn($, 'ajax').and.callTrough(). See Jasmine Docs.

javascript oop multiple classes

Hi Im having problems with javascript! i have main.js and Model.js. Model.js is a javascript oop class in need to access its functions in main.js how do i do that? I keep getting an error that Model is not defined. Are there tools needed for this to work or something is wrong in the code?
Model.js
Model = {};
Model.init = function() {
alert("model");
}
Model.getList = function(){
var list;
$.ajax(
{
url:'???',
type: 'GET',
dataType: 'json',
success: function(data)
{
list=data;
}
error: function(data)
{
alert("error");
}
});
return list;
}
main.js
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
var testins=new Model();
var list=Model.getList();
alert("result: "+testins);
}
I really could use some help.
so I tried MrCode approach and for experimental reasons put the code in one file because main.js still could not access the Model.js file.
main.js
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
alert("aaa"); //first
var testins=new Model();
var list=testins.getList();
alert("result: "+testins); // third
alert("list"+list); //fourth
}
function Model()
{
this.init = function()
{
alert("Model");
}
this.getList = function()
{
var list;
$.ajax(
{
url:'??',
type: 'GET',
dataType: 'json',
success: function(data)
{
list=data;
alert("success"+list); //fifth
},
error: function(data)
{
alert("error");
}
});
alert("success"+list); //second
return(list);
}
}
but following the alerts i see the that the $.ajax part is done last.
Do
function Model() { // this is the "constructor"
}
And replace
Model.init = function() {
by
Model.prototype.init = function() { // provide the function to all instances
(and the same for getList)
This will enable
you to call new Model()
the init function to be inherited by the objects you create with new Model().
Use it like this :
var testins=new Model(); // create an instance
var list=testins.getList(); // call the instance method
You may be interested by this MDN document about prototype and inheritance.
function Model()
{
// define public methods
this.init = function()
{
alert("Model");
}
this.getList = function()
{
var list;
$.ajax(
{
url:'???',
type: 'GET',
dataType: 'json',
success: function(data)
{
list=data;
}
error: function(data)
{
alert("error");
}
});
return list;
}
}
var testins = new Model(); // create an instance of Model()
var list = testins.getList(); // call its method

Extending jQuery ajax success globally

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0
Sample response
{"code": "0", "message": "your code is broken"}
or
{"code": "1", "data": "return some data"}
I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
so your call, instead of $.ajax, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
This solution transparently adds a custom success handler to every $.ajax() call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
Here's a couple suggestions:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});​
Working: http://jsfiddle.net/pF5cb/3/
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
this is your call to ajax method
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});

Categories

Resources