Spines Spines - 9 days ago 6
Ajax Question

why the program doesn't call the js class function?

I have a class in JS, that contains a series of methods inside, related with a login and user's register. These methods basically catching the page's events and they do something.

When it's created the instance for UsersOperations(), and it's called (due to click event)

$("#login").click(function(){});
, is executed correctly... until before calling the
saveUserInfo();
, in this point, the page is reload, and i don't know why, i don't understand, i had the same methods but without class and all worked fine.

Please, help me, or else, i'll die with this existential problem.

$(document).ready(function(){
new UserOperations();
});

class UserOperations{
constructor() {
if(!this.checkUserWithLogin())
this.addLoginAndRegisterButtons();
var self = this;
$("#Log_In").click(function(){
$.ajax({
type: "GET",
url: "php/request.php",
async: true,
data: {nick_log:$("#username").val(),
pass_log:$("#userpass").val()},
success: function(data){
var dataJson = JSON.parse(data);

if(dataJson==null)
alert("You are not registered");
else {
if($("#Keep_log").is(':checked'))
self.saveUserInfo(dataJson,"localStorage");

else
self.saveUserInfo(dataJson,"sessionStorage");
self.checkUserWithLogin();
},
error: function (obj, error, objError){
alert("There is an error!");
}
});
});
}
}

PMV PMV
Answer

Because this isn't referring to the object anymore so it can't find the function. The function you attach as a callback doesn't close over this. You can either use another variable like var self = this; or you can bind your callback using Function.prototype.bind().