You have 2 problems here:
Ajax is asynchronous, you can not #1
after instantiating the class, because this happens before the replies come from the server.
# 1:
Within this
#2
points to jQuery, not to what's around. So if you want to have console.log
pointing to your class you have 3 alternatives:
- use the
success: function(pergunta, desafio){
property and pass in the context reference you want:
Example:
jQuery.ajax({
url: '../php/consulta.php' + location.search,
type: "GET",
dataType: 'json',
context: this,
success: function(pergunta, desafio){
this.perguntas = pergunta.pergunta;
this.respostas = pergunta.resposta;
this.desafios = desafio.descricao;
}
});
- You can use
this
/ this
, giving the name context
to this out of sósia
of jQuery to have a pointer after (the idea that Heber also suggested ).
Example:
const self = this;
jQuery.ajax({
url: '../php/consulta.php' + location.search,
type: "GET",
dataType: 'json',
success: function(pergunta, desafio){
self.perguntas = pergunta.pergunta;
self.respostas = pergunta.resposta;
self.desafios = desafio.descricao;
}
});
- use
alias
that does not change the execution context:
Example:
jQuery.ajax({
url: '../php/consulta.php' + location.search,
type: "GET",
dataType: 'json',
success:(pergunta, desafio) => {
this.perguntas = pergunta.pergunta;
this.respostas = pergunta.resposta;
this.desafios = desafio.descricao;
}
});
# 2:
Here you have to use callbacks , promises or self
/ success
An example with Promisses might look like this:
class pergunta {
constructor(id, title) {
return new Promise((res, rej) => {
jQuery.ajax({
url: '../php/consulta.php' + location.search,
type: "GET",
dataType: 'json',
success: (pergunta, desafio) => {
this.perguntas = pergunta.pergunta;
this.respostas = pergunta.resposta;
this.desafios = desafio.descricao;
}
});
});
}
}
new pergunta().then((perguntas) => {
console.log(perguntas);
});
Demo with promisse:
class pergunta {
constructor(id, title) {
return new Promise((res, rej) => {
jQuery.ajax({
url: 'https://jsonplaceholder.typicode.com/posts/1',
type: "GET",
dataType: 'json',
success: ({
id,
title
}) => {
this.id = id;
this.title = title;
res(this);
}
});
});
}
}
new pergunta().then((perguntas) => {
console.log(perguntas);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>