Retrieve the JavaScript object that was initialized within a function

As I venture into the world of working with javascript objects and php objects, I've encountered an issue. While everything seems to be functioning correctly so far, I'm having trouble accessing the javascript object created in the ajax success response outside of the function.

Below is my JS code snippet:

function settings(mannstage, stundenlohn, tags) {
    this.mannstage = mannstage;
    this.stundenlohn = stundenlohn;
    this.tags = tags;
}
var currentSettings;
SendAjaxJsonRequest("getSettings");

function SendAjaxJsonRequest(method, jsonObject) {
    jsonObject = (typeof jsonObject === "undefined") ? "none" : jsonObject;
    $.ajax({
        type: "POST",
        url: "app/class/controller/ajax.php",
        data: {
            method: method,
            jsonObject: jsonObject
        },
        success: onSuccess
    })
};

function onSuccess(content) {

    var response = $.parseJSON(content);
    currentSettings = new settings(response.mannstage, response.stundenlohn, response.tags);
    console.log(currentSettings); //Returns the object
}
console.log(currentSettings); //This is undefined

The last `console.log` statement is showing `undefined`. Any suggestions on how I can make `currentSettings` accessible outside of the `onSuccess` function?

Thank you!

Answer №1

Due to its asynchronous nature, in Ajax the final console.log statement will usually run before the success function is triggered.

Answer №2

currentSettings is available outside the onSuccess function. However, the console.log call at the end is executed immediately after defining onSuccess, before it's actually invoked. This means that currentSettings remains undefined at that point.

To clarify, consider revising your code as shown below:

function onSuccess(content) {

    var response = $.parseJSON(content);
    currentSettings = new settings(response.mannstage, response.stundenlohn, response.tags);
    console.log(currentSettings); //Returns the object
    afterSuccess(); // Also returns the object
}

function afterSuccess() {
    console.log(currentSettings);
}

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 way to test the Express router catch branch in this specific scenario with Jest?

My current task involves working with a file containing two routes. The first route is located in routes/index.js const express = require('express') const router = express.Router() router.get('', (req, res, next) => { try { r ...

What could be causing an error with NextJS's getStaticPaths when running next build?

When attempting to use Next.js's SSG with getStaticPaths and getStaticProps, everything worked fine in development. However, upon running the build command, an error was thrown: A required parameter (id) was not provided as a string in getStaticPath ...

Can you explain the variance between using querySelector() and getElementById/getElementsByClassName/getElementsByTagName()?

I'm confused about the distinction between using querySelector() and getElementById(). From what I understand, querySelector is able to retrieve an element using any selector, giving it more flexibility. Are there additional contrasts between the two ...

Cookies are strangely absent from the ajax call to the web api - a puzzling issue indeed for Web Api users

Hello, here is the code I'm working with using Ajax: function GetCurrentUserId() { return $.ajax({ type: "GET", url: rootUrl + '/api/Common/CurrentDateAndUser', dataType: 'json', ...

Retrieve class attributes within callback function

I have integrated the plugin from https://github.com/blinkmobile/cordova-plugin-sketch into my Ionic 3 project. One remaining crucial task is to extract the result from the callback functions so that I can continue working with it. Below is a snippet of ...

Execute another ajax call based on the response received from the initial ajax request

I have a header file with a search box where users can search for products using an ajax request. The search results are retrieved from the livesearch.php file. Now, I want to add an 'Add to Cart' button next to each searched product. This button ...

Is it necessary to clean and reinstall node_modules every time I deploy in a production environment?

We manage over 10 production servers and each time we update our dependencies, performing a clean installation seems more controlled but also slower. The issue is that the devops team is concerned about the time it takes to perform a clean npm install aft ...

When using navigator.mediaDevices.getUserMedia on an iPhone, the webcam is activated in fullscreen mode

I'm facing an issue with the webcam functionality on my app. It works perfectly on Android and Windows, but when I try to use it on iPhone, the webcam opens in a separate full-screen view. Any ideas on how to resolve this? Thank you for your help in a ...

Discovering the most recent messages with AJAX

I'm feeling a bit lost on this topic. I'm looking to display the most recent messages stored in the database. (If the messages are not yet visible to the user) Is there a way to achieve this without constantly sending requests to the server? (I ...

Any methods for integrating js.erb files in Ruby on Rails 7?

I've been searching for a while now on how to integrate js.erb files into my Ruby On Rails 7 project, but I haven't been able to find any helpful information. Have js.erb files become obsolete in Rails 7? If so, is there a way to include partials ...

creating a form for submitting data and images using PhoneGap

I'm currently working with a combination of Phonegap, HTML, AJAX, jQuery, MySQL, and PHP. Within my Phonegap application, I have a form that includes fields for username, password, and user photo. I am looking to submit this form from an HTML page, ...

Unusual Characteristics of Synchronous Ajax Requests in JavaScript

First and foremost, I'd like to apologize if my approach seems unconventional. My background is primarily in C development, so I tend to tackle AJAX issues in a way that reflects my experience in C programming. The scenario at hand involves a script ...

Calculate the total width of all images

I'm on a mission to calculate the total width of all images. Despite my attempts to store image widths in an array for easy summing, I seem to be facing some challenges. It feels like there's a straightforward solution waiting to be discovered - ...

Accessing data from another domain using JavaScript with Cross-Origin Resource Sharing (

After researching various CORS and JSON request discussions, I find myself puzzled as to why the first script functions correctly while the second one does not. I am eager to enhance my understanding of CORS, Javascript, XMLHTTPRequest2, and AJAX. The fol ...

Rails : A user was automatically logged out after inadvertently deleting an irrelevant object with the remote attribute set to true

Currently, I am implementing an authentication system following the guidance provided at , and it is functioning as anticipated. In my application, there is a model containing the following partial: <%= content_tag_for(:li, post) do %> <%= link ...

Guide to automatically update div with new table rows with the help of Ajax

Can you assist me in updating the div called "table" that contains a table fetching rows from the database? <div id="table"> <h1 id="Requests"> <table></table> </h1> </div> <button id="refresh-btn"&g ...

Adding the ability to export CSV files from Bootstrap Table to an Angular 15 project

Struggling to incorporate the Bootstrap-table export extension into my Angular project without success so far. Visit this link for more information Any assistance or examples would be greatly appreciated. Thank you in advance! This is what I have tried ...

When attempting to execute a query in Node using oracledb, an error with the code 'npm ERR! errno 3221225477' occurred

Encountered the following error message in the command line: npm ERR! code ELIFECYCLE npm ERR! errno 3221225477 npm ERR! [email protected] start: `node ./bin/www` npm ERR! Exit status 3221225477 npm ERR! npm ERR! Failed at the [email protected] start sc ...

Error alert: The function is declared but appears as undefined

Below is the javascript function I created: <script type="text/javascript"> function rate_prof(opcode, prof_id) { $.ajax({ alert('Got an error dude'); type: "POST", url: "/caller/", data: { ...

Issue with animation transition not triggering on initial click

I am currently working on creating an animation for a form using JS and CSS. Here is the code snippet I have: var userInput = document.getElementById("login-user"); var userLabel = document.getElementById("user-label"); // User Label Functions funct ...