In the world of JavaScript and JQuery, there exists a concept similar to "require_once" that

I have created a JavaScript class, but I am encountering issues with making an Ajax request in the constructor function. I want the response from the Ajax request to populate my object's attributes, but it is not working as expected. Can someone help me identify what I'm doing wrong?

class Question {
      constructor(questions = [], answers = [], challenges = [], value = 100, position = 0){
        this.questions = questions;
        this.answers = answers;
        this.challenges = challenges;
        this.position = position;
        this.value = value;
        jQuery.ajax({
           url: '../php/consult.php' + location.search,
           type: "GET",
           dataType: 'json',
           success: function(question, challenge){
               this.questions = question.question;
               this.answers = question.answer;
               this.challenges = challenge.description;

             }
           });

}

    }
    const question = new Question();
    console.log(question);

Answer №1

When utilizing jQuery's AJAX function, the reference of this inside the callback pertains to the request object. If you wish to retrieve the value of this from the parent scope, you can utilize .bind:

    jQuery.ajax({
       url: '../php/consulta.php' + location.search,
       type: "GET",
       dataType: 'json',
       success: function(question, challenge){
           this.questions = question.question;
           this.answers = question.answer;
           this.challenges = challenge.description;

         }.bind(this)
       });

In cases where you need to cater to a browser that does not support .bind, an additional variable can be used:

class question {
      constructor(questions = [], answers = [], challenges = [], value = 100, position = 0){
        var _this = this;
        this.questions = questions;
        this.answers = answers;
        this.challenges = challenges;
        this.position = position;
        this.value = value;
        jQuery.ajax({
           url: '../php/consulta.php' + location.search,
           type: "GET",
           dataType: 'json',
           success: function(question, challenge){
               _this.questions = question.question;
               _this.answers = question.answer;
               _this.challenges = challenge.description;

             }
           });

}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a custom URL based on the text provided

I have a task of creating a new URL based on user input text Name: <input type="text" id="myText" > <button onclick="myFunction()">check tracking</button> When using DHL service, it requires adding a specific code to the URL like this: ...

Trouble with nested components not refreshing correctly within VueJs

I've just started working with Vue and I'm currently developing a forum-style application that allows nested comments. Within this structure, there are two main components: PostForum and Comment. The PostForum component consists of an input box f ...

I find myself a little mixed up with this syntax in JavaScript: `arr.indexOf(searchElement[, fromIndex])`

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // ...

Create a new design of a Three.js element

After reviewing this particular example involving three.js for drawing particles with images, I found it to work flawlessly. However, I am interested in replacing the image by toggling it with a switch upon clicking a button. Here is the function for this ...

The content inside a Textbox cannot be clicked on. I am seeking help with implementing JavaScript to enable it to be

As a newcomer in the world of programming, I am sharing a snippet of my JavaScript and HTML code with you. I am facing an issue where I want to enable users to start typing in a text box upon clicking on the text "User Name", without deleting any existing ...

Strange behavior of Jquery

I've run into a bit of confusion regarding how JQuery is behaving. Initially, I expected to see the results fname and zetest pop up on alert. Unfortunately, I'm getting unexpected outcomes. Could it be that I've missed something along the wa ...

Perform a function in jQuery only after the previous one has finished running in a cascading manner

Looking for guidance from an expert on how to accomplish this task. I have HTML code for a multiple choice question with options A to E: <div id="correct-answer-XXXXX" style="display:none;"></div> <div id="wrong-answer-XXXXX" style="display ...

Setting a background image as a variable in Vue.js

I am currently working on a vue.js component that includes a div.icon: Vue.component('obj', { props: ['img', 'name'], template: '<div><div class="icon"></div> {{ name }}</div>' }) While ...

Creating editable text in an edit field with jQuery: A step-by-step guide

Each table contains an edit button: <table class="table-responsive table-striped col-lg-12 col-md-12 col-sm-12 padding_left_right_none dash_table"> <tr> <td style="width:10px;">&nbsp;</td> <td style="width: 130px; ...

Obtain the JSON data and save it for later use

I have a JSON file with key : value pairs and I need to extract values from a specific pair and store them in an ArrayList called rating in order to sort them. However, with my current code, I am only able to retrieve the "reviews" key. Can someone help ...

Issue with populating labels in c3.js chart when loading dynamic JSON data

Received data from the database can vary in quantity, ranging from 3 to 5 items. Initially, a multi-dimensional array was used to load the data. However, when the number of items changes, such as dropping to 4, 3, 2, or even 1, the bars do not populate acc ...

SSL-enabled Websocket server powered by websocket.io

I have built a basic Websocket server using node.js and websocket.io var ws = require('websocket.io') , server = ws.listen(8000); server.on('connection', function (socket) { console.log("connected"); socket.on('message&ap ...

What is the best way to retrieve a property value from an object using the .find() method?

I've encountered a problem with the following code snippet in my function: let packName: string = respPack.find(a => {a.id == 'name_input'}).answer.replace(/ /,'_'); My goal is to locate an object by matching its id and retrie ...

Retrieve the JSON encoded output from the Controller and pass it to the View

I am trying to convert a json encoded result from ManagementController.php, specifically the statisticAction, into Highchart syntax within the view file (stat.phtml) in my Phalcon project. Originally, in the stat.phtml file, I had the following: ...

Tips for showcasing an array in PHP with either JSON or XML structure?

I am currently working on creating an API web service using PHP. My goal is to display all the records from my database table in both JSON and XML formats using arrays. However, I am facing an issue where only one record is being displayed or receiving a r ...

Ways to resolve the issue with the information window on Google Maps

I have a problem with displaying infowindows in Google Maps; currently, it only shows the information for the last marker added. let myLatlng = new window.google.maps.LatLng(-33.890542, 151.274856 ); let mapOptions = { zoom: 13, cent ...

The PHP form is causing an error: Notice - Trying to convert array to string

I am currently working with a basic form that leads to the following code for processing purposes. include("connect.php"); $items = array_key_exists('equipment', $_POST) ? $_POST['equipment'] : ''; if(!empty($items)) { ...

Variable fails to be assigned to Element

Having trouble updating the innerHTML attribute for both elements with ids containDiv and status. For some reason, it only changes containDiv but not status. The console shows an error "Cannot set property innerHTML of undefined", indicating that the eleme ...

Can you provide me with the sequelize query that is equivalent to this raw query?

Retrieve the ID from the offers table where the user ID is not equal to '2' and the ID is not present in the list of notified offers for user '2'. ...

React-modal triggers the file-explorer upon exiting the dropzone

Within my project, I have implemented a button that triggers a modal to appear on mouse-over. This button is nested inside a dropzone element. https://i.sstatic.net/95dxy.png The issue arises when I exit the modal by clicking (not exiting with the escape ...