Can you assign a value to a variable via an AJAX request?

If not, is there an alternative solution?

Consider the following:

Page 1:

<script>
  var placeholder = '';

    *** Perform an AJAX Request to Page 2 ***

  document.write(placeholder);
</script>

Page 2:

<script>placeholder = "data for testing";</script>

Answer №1

Have you considered setting the variable value within the callback function of the ajax request? Here is an example:

$.ajax({
    url: "test.html",
    context: document.body
}).done(function(res) {
    test = res.value;
});

Page 2's script could potentially return a JSON Object with the key 'value' containing 'test Data'.

Answer №2

When making an ajax request, you have the ability to set variables based on the page you are requesting, especially if that page contains JavaScript code.

Instead of setting the variable within the ajax request itself, it might be more logical to do so in the callback function of your ajax request.

Since there was no mention of server-side languages, I am assuming you are referring to manipulating client-side variables.

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

Issue with data table row click event not functioning

I am fetching data from a database using coldfusion to populate a dataTable. I am looking to implement a feature where clicking on a row in the dataTable triggers an event to display that row's details in divs on the same page. The code I have curren ...

Utilizing jQuery to Construct a Multi-Level Array

Struggling to understand how to create a multidimensional array in jQuery. I've declared the array outside of the loop. <script> var myArray = []; </script> Within the loop, I intend to add elements to the array. i = 0 [loop sta ...

Top method for effectively handling transactions using Promise

I'm in the process of developing a utility class for NodeJs to streamline database transactions handling. My plan is to implement a method similar to this: transactionBlock(params) { let _db; return mySqlConnector.getConnection(params.db) ...

Is there a way to replace a text box with a <label>, <div>, or <span> using jQuery?

Currently, I am working on "single sourcing" a form page that can switch between edit mode and view mode. Rather than utilizing the ASP.Net FormView or DetailsView controls, I am exploring alternative methods. One of the challenges I encountered is that t ...

Refreshing the access token in Linkedin's oauth does not result in extending the expiration time

Currently, I am implementing a strategy to renew Linkedin OAuth2 access tokens. When starting the OAuth process in the browser, the dialogue is skipped and a new code is generated. This code is then used to acquire a fresh access_token that differs from t ...

Creating a dynamic table based on selected dropdown option

I need to create a dynamic table of questions depending on the user's selection from a dropdown menu. When the user chooses a category, I want to pass that information to an API using the GET method. My controller is built using AngularJS. However, I ...

Utilizing EventEmitters for cascading operations in Angular 2 dropdown menus

I have a form with several cascading drop-downs - the selection in one drop-down determines the options available in the next. Each drop-down retrieves its values from an async data service, and Angular EventEmitter is used to handle events and populate su ...

Puppeteer App Error: An error has been detected on the client side

I am facing an issue using Puppeteer with NEXT.JS while attempting to capture a screenshot. Everything runs smoothly on localhost, but in production, the captured image comes back with the following error message: Application error - a client-side exceptio ...

"Problem with AngularJS: Unable to display data fetched from resource using ng-repeat

I am currently working on an AngularJS application that retrieves data from a RESTful API using $resource. However, I have encountered an issue where the view is not updating with the data once it is received and assigned to my $scope. As a beginner in An ...

Tips for redirecting a port for a React production environment

I am currently setting up both Express.js and React.js applications on the same Ubuntu server. The server is a VPS running Plesk Onyx, hosting multiple virtual hosts that are accessible via port 80. To ensure these apps run continuously, I have used a too ...

What is the best way to merge my ajax request into a single line of code?

My AJAX data looping process is successful, however, when I console log, the data appears on a new line. How can I fix this? $.ajax(settings).done(function(response) { $.get(settings).then(data => makeTable(data.contracts)) const makeTable = (contra ...

Is AJAX content indexed by Google's web crawlers?

When visitors land on my website's homepage, I utilize JQuery's ajax feature to retrieve a list of recent user activity. The recent activities are then showcased on the page, with each activity line containing a link to the respective user' ...

Using PHP to send JSONP callback responses

Is it possible to achieve "two-way" communication using JSONP and PHP? For example: jQuery / JSONP $.ajax({ url: 'http://server/po.php', cache : false, dataType: 'jsonp', timeout: 30000, type: 'GET', ...

Storing progress of a multi-step form in Laravel 5.6 on both the database and local drive

I've been working on implementing a multi-step form using JQuery Steps in Laravel 5.6. Instead of just saving all the data at the end, I want to save each step of the form in the MySQL database and on the user's local drive. This way, I can track ...

Switch between a JavaScript and CSS file with every click using jQuery on a single link

"Kundan Singh Chouhan" assisted me in resolving a problem a few weeks back: How to call a CSS file using JQuery .append() and delete it on the second click However, the issue has since become more complex. I now aim to incorporate our ancient script, "Rov ...

How can I detect Mongoose events through syntax?

Is there a way to detect the open event in Mongoose based on their documentation located here? According to the documentation, once connected, the open event is fired on the Connection instance. If you're using mongoose.connect, the Connection is m ...

Package.json file is not included in Typescript

Each time I execute tsc, it converts the files to JS format successfully, except for package.json. I want this file included in my output directory. Currently, my tsconfig.json looks like this: { "exclude": ["node_modules"], "compilerOptions": { " ...

The dropdown menu vanishes from sight as soon as the cursor moves away from a link

Recently, I encountered an issue while trying to create a dropdown menu using Jquery. The problem arose when attempting to select the second link, as the entire menu would disappear. Additionally, is there a way to ensure that only one dropdown menu is vis ...

Interval set does not refresh an integer

I'm struggling with a function that is supposed to show the number of milliseconds elapsed since Midnight on January 1st, 1970. I've been trying to use setInterval to update the integer every second or millisecond, but it doesn't seem to be ...

Use jQuery to target an element by its class name and node index

I am trying to target a specific element with the class ".myclass" by its node index, but I keep encountering an error stating that the element has no "animate" function. Here is an example: <div class="myclass"></div> <div class="myclass" ...