Sending object as a parameter to onreadystatechange

Is there a way to make the AJAX callback trigger the alert() function within myFunction and display "It worked"? How can I reference the myobject object as 'this' in ajaxResponse?

function myobject() {
    this.val = "worked";

    http.onreadystatechange = function ajaxResponse() {
        if (http.readyState == 4) {
            this.myFunction();
        }

        http.send(null);  
    }

    myobject.prototype.myFunction = function() {
    alert("it "+this.val);
}

Answer №1

To associate the parent object with the xhr object, simply add it as a property:

xhr.parent = this; // Add the parent here
xhr.onreadystatechange = function handleResponse()
{
    if (xhr.readyState == 4)
        console.log(this.parent.value) // Retrieve it here
}

Answer №2

When working with closures in JavaScript, it's important to understand that variables defined in the parent function can be retained in memory even after the parent function has completed its execution. One way to approach this is by assigning the parent context to a temporary variable:

var objTmp = this;

This allows you to access the parent context within the closure. Another approach is to use a self-executing function to pass the parent context explicitly:

http.onreadystatechange = (function(objTmp){
                         return 
                             function ajaxResponse{alert(objTmp.value)}
                       })(this)

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 achieve the functionality of this ajax jquery using vanilla JavaScript?

I am attempting to replicate this jQuery ajax POST request in Vanilla JS, which currently looks like: $.ajax({ method: 'POST', url: window.location.href + 'email', data: { toEmail: to, fromName: from, ...

The journey of a JavaScript file within an iframe devoid of any src attribute

Consider this scenario: In a folder labeled /jscript, there are two files named my_js_file1.js and my_js_file2.js. I also have an /index.html page structured like this: <html> <head> <script type='text/javascript' sr ...

What steps can be taken to prevent relying on static file names in the code

Currently, my web application project is being bundled using webpack. The webpack configuration in use is outlined below: const HtmlWebPackPlugin = require("html-webpack-plugin"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const path = requ ...

When the second history.push is triggered in react-router-dom, it may result in returning an

Hello, I am working with an Antd modal that contains a form. The code snippet for the modal is as follows: <Modal visible={visible} onOk={handleOk} onCancel={handleCancel}> <MyForm onSubmit={handleOpenUrl}> <CustomInput name= ...

The Storybook compilation consistently encounters errors

Check out my repository here: https://github.com/zapify-ui/zapify I'm facing an issue with building Storybook using the command: npm run build-storybook How can I identify the specific error or debug it effectively? The error thrown is: (node:46619) ...

Can someone show me how to use the IN operator in a PostgreSQL query in an Express.js (Node.js

My Approach to Writing Code var employees=[1,2,3]; await client.query( "SELECT user_id FROM group_user WHERE user_id IN($1)", employees ); An error is thrown indicating that only one parameter needs to be provided ...

What is the method for presenting an integer column from a specific table to a user on the front end as a series that automatically increments from 1?

I'm currently developing a comprehensive full-stack application designed to function as a task and project management tool. It features a table layout with a convenient drag and drop functionality that enables upper-management to easily re-prioritize ...

Create an array and populate it using a for loop

I'm attempting to use a for loop in JavaScript to create an array. The goal is to have an array with 10 or more variables (var kaunt1, var kaunt2, etc...) that are filled with numbers from div tags. I've given the code below a try, but it doesn& ...

"Enhancing Event Handling with JQuery Delegate on Internet Explorer

My pop-up menu is set to hide when someone clicks anywhere else on the page. $(window).delegate("body", 'click', hide); While this functionality works in most browsers, I am encountering issues specifically with IE8. Can anyone advise on what m ...

Making sure that a commitment does not come to fruition

Perhaps this code snippet below functions correctly as it is, but I'm uncertain if it's the best approach to prevent potential runtime issues. Here's the code in question: const ep = `${environment.api.baseUrl}/login`; return this.http.pos ...

Transfer data between PHP files seamlessly using Jquery

I need help passing a variable from file1.php to file2.php using jQuery. file1.php <?php $user_rank = $rank; ?> file2.php <?php $user_rank = $_GET['user_rank']; ?> AJAX function getRank() { $.ajax({ type: "GET", ...

Execute a function upon pressing the enter key

Currently, I am working on coding a webpage with a form that includes one field where users input a set of numbers. After typing in the numbers, they should then press a button labeled 'Run' to execute the code. However, the issue arises when use ...

Combining MVC4 with the power of Ajax and jQuery 2

Help needed with getting ajax.beginform to function correctly in my MVC4 project. I have updated the jQuery library to version 2 and included jquery.validate.js and jquery.validate.unobtrusive.js, but the form is still redirecting to a new page instead of ...

Changing text and applying a different span class using a Jquery button toggle

My current issue involves a functional toggle button that smoothly slides a div up and down. However, I am facing problems when attempting to change the toggle button status: You can view a demonstration of my code here: http://jsfiddle.net/zwu0sn83/3/ B ...

Learn how to utilize AJAX in a JSF input textbox to dynamically update a h:selectOneRadio component

In my development project, I used JSF 2.0, RichFaces, and a4j. There is a radio button group with 3 options, each accompanied by an input textbox positioned next to it as shown below: radio button A | input textbox A radio button B | input textbox B radio ...

Launching the webpage with Next.js version 13

Hey there! I'm currently working on implementing a loading screen for my website to enhance the user experience. Since it's quite a large site, I believe a loading screen would be beneficial. However, I'm having trouble getting it to work on ...

What are some techniques for styling the content within a table?

I have a function that dynamically creates tables: function generateTableContent(data) { var table = $('<table id="tblResultsList">'); var tr; var td; $.each(data.d.foundItems, function(i, item) { var button = $(& ...

In the event that the get request fails, go ahead and clear the

Currently facing an issue and seeking a solution: I have a game running that retrieves the state of the game periodically. However, if a user logs out, the game ends but continues to send put requests at the set interval. I am exploring options like setti ...

Transcluding an element into an ng-repeat template in AngularJS: How can it be done?

Incorporating a carousel directive involves chunking the passed in array of items and mapping it into an array of arrays of elements. This structure then generates markup resembling the pseudo code provided below: <array of arrays> <array of i ...

Entering a string into Angular

Within my function, I trigger the opening of a modal that is populated by a PHP file template. Within this template, there exists a div element containing the value {{msg_text}}. Inside my JavaScript file, I initialize $scope.msg_text so that when the mod ...