Object-oriented programming in JavaScript allows for the passing of variables to a parent class using $

I am attempting to transfer variables from an XML file to the parent class in JavaScript. The code follows Object-Oriented Programming principles, with a class named "example" and a method called getData().

The issue I'm encountering is that the AJAX call only returns integer values, not string ones - which seems quite strange.

(modified as per T.J. Crowder:)

function example(){
    this.b;
    this.str;
}
example.prototype ={
    getData:function(){
        $.ajax({
                type: "GET",
                url: "Bar.xml",
                dataType: "xml",
                            context: this,
                success: function(xml) {
                    this.b = parseInt($(xml).find('current_madad').text()); //int_from_xml- works!
                           this.str = $(xml).find('graph_title').text(); //string_from_xml - doesnt work!!
            }
        })//end ajax    
    }
};

var c = new example();
c.getData();

The XML file can be found here for further review of the code:

<?xml version="1.0" encoding="utf-8"?>
<root>
  <Bars>
    <Bar>
      <bar_start>1010</bar_start>
      <lower_danger_zone>1030</lower_danger_zone>
      <mid_safe_zone>1050</mid_safe_zone>
      <upper_danger_zone>1150</upper_danger_zone>
      <upper_fbdn_zone>1200</upper_fbdn_zone>
      <bar_range>200</bar_range>
      <ideal_range>5</ideal_range>
      <current_madad>1115</current_madad>
    </Bar>
  </Bars>
  <Bars_Desc>
    <Bar>
      <graph_title>פוזיצית אפריל</graph_title>
      <lower_fbdn_zone_Desc>תחום אסור תחתון תיאור</lower_fbdn_zone_Desc>
      <lower_danger_zone_Desc>תחום מסוכן תחתון תיאור</lower_danger_zone_Desc>
      <mid_safe_zone_Desc>תחום בטוח אמצעי תיאור</mid_safe_zone_Desc>
      <mid_safe_ideal_zone_Desc>תחום בטוח פקיעה אידיאלית תיאור</mid_safe_ideal_zone_Desc>
      <upper_danger_zone_Desc>תחום מסוכן עליון תיאור</upper_danger_zone_Desc>
      <upper_fbdn_zone_Desc>תחום אסור עליון תיאור</upper_fbdn_zone_Desc>
    </Bar>
  </Bars_Desc>
</root>

Answer №1

When making the ajax call, keep in mind that it is an asynchronous operation. The getData function initiates the call, but the completion occurs later, after getData has already returned. Therefore, when you are assigning a value to this.b, a may not have been set by the success callback yet. To address this, adjust your getData call like so:

getData:function(){
    var self = this;           // <=== Create a reference to `this`
    alert("functionlasdkfj");
    $.ajax({
            type: "GET",
            url: "Bar.xml",
            dataType: "xml",
            success: function(xml) {
                self.b = 1;    // <=== Utilize the reference to set `b` directly
        }
    })//end ajax
}

Alternatively, you can utilize the context option of ajax to modify what this refers to within the callback:

getData:function(){
    alert("functionlasdkfj");
    $.ajax({
            type: "GET",
            url: "Bar.xml",
            dataType: "xml",
            context: this,     // <=== Set `context` accordingly
            success: function(xml) {
                this.b = 1;    // <=== You can now set `b` directly
        }
    })//end ajax
}

I'd like to highlight two additional points:

  1. Regarding the following code snippet:

    function example(){
        this.b;
    }
    

    The presence of this.b does not have any impact as it essentially acts as a comment. Notably, it does not actually create a property named b on the object.

  2. In your initial code, if you hadn't declared a elsewhere, you might have encountered issues related to The Horror of Implicit Globals.

Answer №2

Understood! I've got the necessary data and am sending it through a function embedded within the success callback of an ajax call! fetchData:function(){

$.ajax({
        type: "GET",
        url: "Foo.xml",
        dataType: "xml",
        context: this,     // <=== Setting `context` - which proved to be helpful
        success: function(xml) {
           arr.value1 = 10;    // 
           arr.value2 = 567;
           transmit_data_to_processor_function(arr); //<= Now awaiting for response

})//end ajax

}

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

What is the best approach to dealing with a non-TypeScript project that is requesting the installation of @types for

With the project set up using create-react-app and custom-react-scripts to utilize decorators for MobX, I am aiming to incorporate the react-c3js library for data visualization. Surprisingly, everything is functioning correctly, but there's a warning ...

What is the process for updating the URL for specific functions within $resource in Angular?

Check out this code snippet: angular.module('app.posts.services', []).factory('Post', ['$resource', 'API_ENDPOINT', ($resource, API_ENDPOINT) => $resource(API_ENDPOINT, { id: '@id' }, { updat ...

Utilizing JavaScript Fetch with User Input to Integrate OpenWeather API Retains Previous Data on HTML Page

I have been working with JavaScript Fetch to retrieve data from the OpenWeather API. In my project, I have created a form where users can input the name of a city to view its weather information. However, I am facing an issue where the data from the previo ...

Using Jquery to send dynamic id and base url to a Laravel route

I have a jQuery script that uses AJAX to update the rating for a contest and sends the data to a controller to make changes in the database. My challenge is figuring out how to dynamically retrieve the contest ID and base URL of the website from the curre ...

Adding elements to an array within a JSON object in Angular: What you need to know

Within my json object named "flowComponents," there is a string called "name" and an array of strings labeled "edition." As an example: { "_id": "553e87f3205465e83b46999b", "name": "FLOWCOMPONENT_CONTACTCOMBINATION_EDITION", "__v": 0, "edition ...

How can I transform an HTML element into a textarea using CSS or JavaScript?

While browsing a webpage, I discovered a <div> element with the class .plainMail and I want to find a way to easily select all its text by simply pressing Ctrl+A. Currently using Firefox 22, I am considering converting the div.plainMail into a texta ...

Issue with Django div reloading: Using ajax GET after POST does not fetch the most recent database model instances

Within a chat-like application, I am utilizing ajax calls to POST a new message and dynamically update the messages displayed on the page without having to reload the entire page. The ajax call for posting functions correctly as it creates a new message in ...

The JWT Cookie has successfully surfaced within the application tab and is now being transmitted in the request

When sending a JWT token to an authorized user in Express, the following code is used: The cookie-parser module is utilized. module.exports.getUser = async (req, res, next) => { console.log('i am in getuser'); const { SIT } = req.query; ...

javascript display error message in innerHTML if passwords do not match

Hello, I found your code to be helpful but I am facing an issue. I want to display a message using innerHTML when the passwords do not match. I have been trying to implement this feature but it is not working for me. Below is my current code. Please provid ...

Switching Profiles in XPages

In my Xpages project, I have two different user profiles set up. I am currently attempting to develop a function that would allow me to easily switch between these two profiles. However, I am unsure of the steps needed to accomplish this task. ...

What are the best ways to make this date more visually appealing and easy to understand?

Hey there! So I have a date that looks like this: 2022-06-28T17:09:00.922108+01:00 I'm trying to make it more readable, but unfortunately, when I attempted using moment-js in my javascript/react project, it threw an error stating "invalid format". ...

Steps for adjusting the position of this div in relation to the main container

Apologies in advance for my lack of HTML skills. I am struggling with a page layout issue. I have a website at . When the window is resized, the ads div on the right side overlaps the main container. What I would like to achieve is to make this ads div re ...

``There Seems to be an Issue with Loading Content in Tabs

Hey! I'm encountering an issue with my jquery tabs. The first tab content loads fine, but when I select another tab, the content doesn't display. Then, when I try to go back to the first tab, it doesn't load either. Here's the HTML cod ...

Receive regular updates every week for an entire month using Javascript

How can I calculate the number of check-ins per week in a month using Javascript? I have been unable to find relevant code for this task. Specifically, I am interested in determining the total count of user check-ins on a weekly basis. For example, if a u ...

Issues related to ng-model within a dropdown list

Currently, I am facing an issue with retrieving the selected value from a select element using ng-model. Even though the value is displayed correctly on the application page, it remains at the initial value in the app controller. Despite my efforts to find ...

What is the reason for a jQuery load to fail when www is included in the URL?

Can anyone explain why adding www to an ajax request causes it to fail? For example, this code works fine: $('#mydiv').load(''); But this one doesn't work (returns empty): $('#mydiv').load(''); It's wo ...

Using Javascript to create bold text within a string

I have noticed that many people are asking about this issue, but it seems like a clear and simple answer is hard to come by. Currently, I am working with Vue and trying to display text from an object in a component. My goal is to highlight the price port ...

Monitoring the execution of a PHP script triggered by a jQuery post request

I am looking to create a system where I can periodically check the status of a PHP script and display it in the browser. Below is the jQuery code that I currently have for posting the data: $(document).ready(function() { $("#tempbut").click(function ...

Display HTML content using AJAX within a div element

Within my HTML code, I have the following: <li class="register"><a href="">Registreer</a></li> as well as <div id="content"> </div> I attempted to load an HTML file into the div using the code below in the header se ...

QuickCopy - Capture only what's in view

Hi there, I have a question: I'm trying to figure out how to make a button copy only the visible text within the element with id="description". Can someone help me troubleshoot? HTML: <p id="description"> Test <span style="display:none"> ...