Reputation: 97
I want to prevent a function to execute before get a value from ajax, I'm trying using async:false it works but deprecated. So, I'm using callback like what I found on internet. It's works too, but the browser still tell me if the callback is not the function. Here's my code
function User() {
this.nama;
this.nis;
this.pass;
this.role;
this.url = "http://localhost/elearning-web/";
this.Login = function(call) {
$.ajax({
type:"POST",url:this.url+"dologin.php",data:"nis="+this.nis+"&pass="+this.pass,
success:function(e){
call(e);
}
});
}
}
When I check the console.log it's show what I want to display, but the browser tell me if the call (callback) is not a function. Thanks in advance
Upvotes: 1
Views: 55
Reputation: 23859
What you want to do is already achievable using Promise API, and yes, jQuery supports it too.
You just need to change the Login
function as below:
function User() {
// .. other code truncated for brevity
this.Login = function() {
return $.ajax({
type: 'POST',
url: 'your_url'
// Note that `success` function has been removed from here
});
}
}
Now this solves a lot of problems. First of all, the caller of User.Login
doesn't need to pass a callback function. The login function can just be used like this:
var user = new User();
user.Login()
.then(function(e) {
// `e` is accessible here
});
Second, there can be unlimited number of .then()
chained with each other, providing better code readability.
Third, you need not to validate the callback to be a function since .then
accepts a function as its argument (validates it for free).
Fourth, success
callbacks are deprecated by jQuery. .then()
uses the new syntax.
Upvotes: 2
Reputation: 2678
You have to declarate a call function the pass it to User.Login(call);
function call1(e) {
console.log('Hi, from call ', e);
}
function User1() {
this.Login = function(call) {
// simulating $.ajax http request ;]
setTimeout(function() {
call(';)');
}, 2000);
}
}
var user1 = new User1();
user1.Login(call);
// in your case
function call(e) {
console.log('Hi, from call ', e);
}
function User() {
this.nama;
this.nis;
this.pass;
this.role;
this.url = "http://localhost/elearning-web/";
this.Login = function(call) {
$.ajax({
type:"POST",
url:this.url+"dologin.php",
data:"nis="+this.nis+"&pass="+this.pass,
success:function(e){
call(e);
}
});
}
}
var user = new User();
user.Login(call);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 0
Reputation: 4615
The call
argument, that you are passing to the method Login
must be a function, for example:
var call = somethingFunction(){ return 'called!';}
var user = new User();
user.Login(call)
Upvotes: 2