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

Using jQuery.post to select and manipulate the target div displaying Google search results

I am trying to implement a custom form and display the results in a specific target DIV ('results') using ajax. However, I am facing difficulties and unable to figure out what is going wrong. Even after referring to this demo (https://api.jquery ...

Using Javascript to dynamically add an element to an array with a unique index

Given let inputArray = []; $('some_selector').each(function() { let outer, inner; outer=$(this).parent().attr('some_property'); inner=$(this).attr('a_property'); if (!inputArray[outer]) inputArray[outer] = ...

What is the process for loading an HTML form into a specific target using Angular?

Is there a way to load an HTML form into a target in Angular without the use of jQuery? I have a working script, but I am currently stuck on: <html> <head> <script src="components/angular/angular.js"></script> <script&g ...

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

I am looking to view all products that belong to the category with the ID specified in the request, and have red-colored stocks

Within my database, I have defined three mongoose models: Product, Category, and Stock. The Product model contains two arrays - categories and stocks, each including respective category and stock ids. My goal is to retrieve all products where the category_ ...

Activate function upon closure of window.open

I'm facing an issue where I need to load a URL in window.open that saves some cookies in my browser. After the window.open is closed, I want to access those cookies but I haven't been able to find a way to do it. I've tried the following cod ...

Transferring canvas element via socket with JS stack size limit

I'm encountering an issue where I need to transfer a canvas element over sockets using socket.io and Node.js. The code snippet below illustrates my approach: var myCanvas = document.getElementById("myCanvas"); var ctx = myCanvas.getContext("2d"); // ...

"Enhance user experience with the React Popover feature from Material UI

Looking for help on creating a dynamic color palette with a hover feature for the PaletteIcon. The issue I'm facing is that when I try to select a color, the palette disappears. Is there a specific property I should add to the React component or anoth ...

The animation did not cause a transition to occur

After creating a search modal triggered by jQuery to add the class -open to the main parent div #search-box, I encountered an issue where the #search-box would fade in but the input did not transform as expected. I am currently investigating why this is ha ...

Adding items to a dropdown list using AngularJS

I'm attempting to add an item to my dropdown list by targeting its ng-class after a save function in AngularJS. However, I am struggling to understand what the issue might be as I am still new to AngularJS. Any advice would be greatly appreciated: Dr ...

What is the best way to send an action through a URL in Laravel?

In my view, I have a form that needs to trigger an action and update a table when submitted. However, after submitting the form, instead of updating the table, it redirects me to /users/{id}. Here is the code for my action: public function userToadmin($id ...

Installing a package from a private repository using a different package name with npm

I'm looking to incorporate a module from a private GitHub repository into my project. To achieve this, I will execute the command npm install git+https://[API-KEY]:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0b737c6e607 ...

Tips for changing the click event of a button with .on/off

My approach for attaching and detaching event handlers is through on()/off(). HTML: <div id='load' class="UnfiledContainer"> <button onclick="loaded()">Try it</button> <p id="demo"></p> </div> JS: ...

The charts created using chartjs-vue display no data

After following some examples to create a test chart, I am facing an issue where the chart renders blank with dummy data. My initial suspicion is that maybe the options are not being passed for the lines, but it seems like dataCollection is not being popu ...

Tips for implementing controlled components in Vue to update values in the parent component object

Utilizing controlled components, I am able to emit the selected value. For example, // app-select.vue <v-select :items="[1,2,3]" @change="$emit('input', $event)"></v-select> // parent-component.vue <app-sele ...

Display the date string in Material-UI TableCell格式

I have a TableCell component in Material-UI that displays dates in the format 2019-03-25T19:09:21Z: <TableCell align="left">{item.created_at}</TableCell> I want to change this to a more user-friendly format showing only the date as either 25/ ...

What is the reason behind DWR being asynchronous? Is there a solution to this?

When I try to send a message through the first web page (http://localhost/chat/test.jsp) and then open the second page, the second page does not immediately receive the message. Only after sending a message through the second page am I able to see the mes ...

Using VueJS to fetch and display data from a JSON file using

Currently, I am dealing with a JSON value in the following format: { "T1" : "online", "T2" : "offline" } Additionally, I have an online API which only sends me the following response: { StatusCode :"T1" } My task is to extract the code from the API res ...

I am unable to create a visual representation using the data obtained from the API

After utilizing Redux-Saga to fetch data from an API, I encountered difficulties accessing the updated state. This issue may stem from attempting to retrieve the data before it has been fully loaded into the redux state. //saga.js import axios from ' ...

"Ensuring Security with Stripe Connect: Addressing Content Security Policy Challenges

Despite using meta tags to address it, the error persists and the Iframe remains non-functional. <meta http-equiv="Content-Security-Policy" content=" default-src *; style-src 'self' 'unsafe-inline'; ...