Is it possible to dynamically change the object name using $.ajax function and pass it as a

I'm attempting to parse multiple JSON files into different objects.

Here is my approach:

function downloadDataSave (targetObject) {
//  DOWNLOAD CALCULATION BACKUP
    var filename, response;
        filename = targetObject.name + '.json' ;

    $.ajax
    ({
        type: "POST",
        url: datasaveHostname,
        timeout : 3000 ,
        data: {
            action : "download", target : filename, data : ""
            },
        success: function (data) {
            response = JSON.parse(data) ;
            this[targetObject] = response ;    // doesn't work , results in empty object
            window[targetObject] = response ;  // doesn't work , results in empty object (as it's the same)
            resolutionHistory = response ; // does work, but how to solve this for more than one targetObject??
        },
        error : function (data) { console.log(targetObject.name + " : Download failed , ServerMessage : " + data); }
    });
};

Please see the comments inside success. Functions like "console.log(response)" are returning the correct Object(s) inside resolutionHistory for example.

Any ideas?

derdigge

EDIT

This is how objects are created:

objects = [
"resolution", "resolution_history",
"roughsorting", "roughsorting_history",
"cleaning", "cleaning_history",
"fractionation", "fractionation_history",
"finalseparation", "finalseparation_history",
"thickening", "thickening_history"
];

function createObjects () {
    for (var i = 0; i < objects.length; i++) {
        window[objects[i]] = {};
        window[objects[i]].name = objects[i] ;
    }
};

EDIT2

I have added more console logs inside the code snippet:

Function downloadDataSave (targetObject, target) {
    //  DOWNLOAD CALCULATION BACKUP

    var filename, response ;

    console.log(this[aufloesungHistory]) ;     //undefined

    if (!(arguments[1])) {
        filename = targetObject.name + '.json' ;
    } else {
        filename = arguments[1] + '.json' ;
    }

        $.ajax
        ({
            type: "POST",
            url: datasaveHostname,
            timeout : 3000 ,
            data: {
                action : "download", target : filename, data : ""
                },
            success: function (data) {
                    response = JSON.parse(data) ;
                console.log(aufloesungHistory) ;       //  empty object
                    this[targetObject] = {} ;
                console.log(aufloesungHistory) ;       //  empty object
                    this[targetObject] = response ;
                console.log(aufloesungHistory) ;       //  empty object
                    aufloesungHistory = {} ;
                console.log(aufloesungHistory) ;       //  empty Object
                    aufloesungHistory = response ;
                console.log(aufloesungHistory) ;       //  right contents inside object
                console.log(this[aufloesungHistory]) ; //  right contents inside object 
                console.log(this[targetObject]) ;      //  right contents inside object
            },
            error : function (data) { console.log(targetObject.name + " : Download failed , ServerMessage : " + data); }
        });
};

The actual data looks like this inside a correct object: correct object

The .json file is created earlier from a correct object using JSON.stringify(targetObject) in an upload function which has a similar structure.

Here is an example of a json blob:

{"name":"aufloesung_history","0":{"start":1446043200,"stop":1446063000,"start_h":"28.10.2015, 15:40","stop_h":"28.10.2015, 21:10","duration":19800},"1"... (truncated for brevity)

EDIT_3 (SOLUTION)

I found the solution! The issue was caused by "this" being an Object inside ajax. jQuery and my Brain led to that error. console.log(this) inside the success section of ajax helped me understand. I used the key name (aufloesung.name for instance) to populate a new object. This only occurs on the first load of the project so it should be okay. Please refer to the comments inside the code.

Answer №1

It's not common for me, but I decided to answer my own question this time. Check out the comment inside the ajax function.

function saveData(target) {
//  DOWNLOAD CALCULATION BACKUP
var fileName, attempt = 0;

fileName = target.name + '.json';

$.ajax({
  type: "POST",
  url: datasave_hostname,
  timeout : 3000 ,
  data: {
    action : "download", target : fileName, data : ""
  },
  success: function (data) {
      window[target.name] = JSON.parse(data);   // Functioning as expected ;)
      window[target] = JSON.parse(data);   // Not working (unsure why). 'target' here is an object with only one key (name)
      this[target.name] = JSON.parse(data);     // Doesn't "work" because 'this' isn't referring to the DOM window Object
  },
  error : function (data) {
    console.log("Attempt : " + attempt + " failed. Trying again.");
  }
});

};

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

Result array, employed as an input for auto-suggest functionality

I’m currently working with an array where I am iterating over an object from an API endpoint that is in stdClass format: foreach($searchResults->hits as $arr){ foreach ($arr as $obj) { $fullType = $obj->_source->categories; print_r($fu ...

Extract all objects from an array where a specific field contains an array

data:[ { id:1, tags:['TagA','TagB','TagC'] }, { id:2, tags:['TagB','TagD'] }, { id:3, tags:[&a ...

Select dropdown population that dynamically changes

I have searched extensively for solutions to my current issue, but unfortunately, none of the existing answers were helpful. Therefore, I am reaching out with a new question. My goal is to dynamically populate a second dropdown list based on the selected ...

Utilize local JSON file to display images on a webpage using AngularJS

Where am I making a mistake? I am trying to display images from a datahl.json file on my web page, but for some reason, I am unable to access them. Please review the code snippets below and help me out. If possible, provide a solution using Plunker edito ...

Creating mock implementations using jest in vue applications

I have been experimenting with testing whether a method is invoked in a Vue component when a specific button is clicked. Initially, I found success using the following method: it('should call the methodName when button is triggered', () => { ...

The process of merging these two functions involves ensuring that one function does not start until the other has successfully completed its task

A closer look at the two functions in question: const handleSubmit = async (e) => { e.preventDefault(); console.log(songLink) const newSong = { songName, songLink, userId }; const song = await dispatch(pos ...

How to confirm the parent state in Angular's UI router?

In summary, I am seeking a function similar to state.is() that can verify a state with multiple child states from one of those child states? This is the structure I have: Parent 1 Child 1.1 Child 1.2 Child 1.3 Parent 2 Child 2.1 ...

Use Puppeteer and Node.js to repeatedly click a button until it is no longer present, then initiate the next step

Imagine a dynamic web page filled with rows of constantly updated data. The number of rows on the page remains fixed, meaning old rows are replaced and not stored anywhere. To navigate through this page, you need to click on a "load more" button that app ...

The sorting function in Vue data table is not functioning as intended

In my code, I have implemented a v-data-table: <v-data-table :headers="walletInHeaders" :items="filteredByQuantityIncome" class="elevation-1"> <template v-slot:items="props"> <td class=&quo ...

Angular formly - Enhancing User Input Focus

I have created a field wrapper that converts normal text into an input when hovered over with the mouse. Additionally, I have a directive that sets focus on the field when it is activated. Now, I am looking for a solution where the field remains open as l ...

Practice window.performance.getEntriesByType with a mock function

I am facing an issue in my component where I need to check if the page is reloaded and redirect to another page. Here is the code snippet I am using: useEffect(() => { //this will prevent users from accidentally refreshing / closing tab window.o ...

Tips on editing a file exclusively when a specific requirement is fulfilled

Looking for a way to implement a put method within an Express API that allows users to update a document conditionally? Consider this scenario: you have an Instance document with an attribute called executed, which is set to true if the instance has been e ...

Accessing the value of a hidden field within an ng-repeat loop when binding to an HTML table

I am working on a project where I have an HTML table with data being bound from AngularJS. The structure looks something like this: <tr ng-repeat="item in List| filter: { MachineType: 'Physical' }"> <td>{{item.MachineType}}< ...

The translateX property will be set to the offsetX value of the event when the mouse is moved, resulting in a

Here's a quick and easy question regarding some kind of scrubber tool. Check out the fiddle below. When using jQuery to bind to the mousemove event and adjusting the transformX property in the positive direction, there's a 50% chance it will ret ...

Ways to implement a delay in a function?

I'm looking for a way to introduce a delay in my function. Should I enclose the function within a delay function, or is there a different method to ensure that the animation doesn't trigger until 5 seconds after the page has loaded? var textTo ...

Using jQuery to compel a user to choose a value from the autocomplete suggestions within a textarea

Currently, I have implemented a snippet that allows the user to choose cities from a list and insert them into a textarea separated by commas. However, I am looking to enhance this feature. I want the user to be able to search for a city by typing a part ...

Error encountered: The fiber texture failed to load due to a component becoming suspended during the response to synchronous input

I'm encountering an issue while attempting to load a texture through the TextureLoader: const texture = useLoader(TextureLoader, '/textures/texture.png') The error message I receive from react is as follows: ERROR A component suspended w ...

Tips for adjusting the value of a textbox up and down

I am facing an issue with my booking flight form that is supposed to take input from users regarding the number of travelers. I have three textboxes for Adult, Children, and Infants respectively, along with a main textbox to display the final result. Howev ...

Is it possible to use the AngularJS function with the <div> HTML element?

I am facing an issue with displaying a modal when clicking on a <div> element. The function assigned to show the modal by changing the CSS property 'display' from 'none' to 'block' works fine when attached to a button, b ...

Successor in a JavaScript array with multiple dimensions

I am grappling with a complex nested multidimensional array that resembles the following structure in JSON format: [ { "Object": "Car", "Child": [ { "Object": "Toyota", "Child": [ ...