Retrieve outcome from successful AJAX post and update HTML using globalEval

I have a function in JQuery that asynchronously posts data

function post_data_async_globalEval(post_url, post_data, globaleval) {
$.ajax({
    type: 'POST',
    url: post_url,
    data: post_data,
    dataType: 'html',
    async: true,
    timeout: 20000, // in milliseconds ~ 20 secs
    success: function (result) {
        jQuery.globalEval(globaleval);
    }
});
}

Here's an example of how I call the function:

post_data_async_globalEval("../Internal/RTV_COM?vid=1578", "type=TM", "$('#postinnerhtml').html(result);");

The goal is to execute this JavaScript function:

$('#postinnerhtml').html(result);

and replace the HTML content with the result received from the successful AJAX post request.

However, when running the code, I encounter this error:

Uncaught ReferenceError: result is not defined

While I could simply include the JS code within the success function, I prefer to dynamically parse and execute the desired JS code after the operation has successfully completed.

Answer №1

Instead of utilizing a string for the globaleval argument, you have the option to pass a function instead:

function(result) {$('#postinnerhtml').html(result);}

Then, in the ajax call:

success: globaleval

(By the way, in this scenario, it might be advisable to change the argument name...)

[Edit] I would like to reiterate my initial comment that you also have the choice to use native eval() in place of jQuery.globalEval(). However, it is worth noting that eval() is typically frowned upon when dealing with input from an external source (such as the result of an ajax call).

Answer №2

If you're looking to simply update the content of #postinnerhtml with the result, it's safe to move your

$('#postinnerhtml').html(result);
code into the success: function (result) { }. This way, the process will be more streamlined and straightforward. You can check out an example here: http://jsbin.com/OGOgEnO/1/edit

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

Can a Div Maintain White Space No Wrap and Stretch to the Full Width of its Parent Element?

Within a parent element, I have a div that allows for horizontal scrolling. Using CSS and jQuery, the content can overflow horizontally with white space no wrap. Setting a fixed width for the div works well, but my responsive website requires a dynamic wid ...

How to dynamically insert variables into a separate HTML file while creating a VS Code extension

Currently working on a vscode extension, I'm facing an issue with containing the html in a string (like this: https://github.com/microsoft/vscode-extension-samples/blob/main/webview-view-sample/src/extension.ts). It leads to a large file size and lack ...

How can I verify the status of an occasional undefined JSON value?

There are times when the JSON object I'm trying to access does not exist. Error: Undefined index: movies in C:\xampp\htdocs\example\game.php In game.php, I'm attempting to retrieve it from the Steam API using this code: $ ...

Unable to retrieve file path from image selection in JavaScript by clicking on a button

I am trying to create a simple browsing feature that only accepts images. However, after clicking the button, I am unable to retrieve the full path in JavaScript. All I can get is the filename. JavaScript <script type="text/javascript"> functio ...

The current status of the ajax call is set to 0

I am currently attempting to retrieve information from a remote server on my local machine. The readyState seems to be fine, equal to 4. However, the status is consistently showing as 0 instead of 200. When I click the button, it doesn't return anythi ...

Is Protractor compatible with Internet Explorer 9?

For my Angular App that is running on IE9, I need to create end-to-end acceptance tests. I'm curious to know if the browser simulated by Protractor matches the behavior of IE9 or a newer version? ...

Equality and inequality in arrays

Could someone help clarify why these comparisons between different JavaScript arrays result in true? ["hello"] !== ["world"] [42] !== [42] ["apple"] != ["orange"] [7] != [7] ...

Obtaining serverTime from a webpageWould you like to learn

Is it possible to retrieve the serverTime using jquery ajax functions like $.get() or $.post()? I am looking to store this serverTime in a variable that can be utilized later on in javascript. You can access the webpage at: To use the get and post functi ...

Error: The property 'ss' cannot be accessed because it is undefined

Our main source page will be index.html, while Employees.html is where our results end up. An error occurred: TypeError - Cannot read property 'ss' of undefined Error in the code: let rating = req.body.ss; Seeking assistance please >< C ...

Can you explain the purpose of the window.constructor and global.constructor functions in JavaScript?

Can someone explain the purpose of this function? I've been searching for information but can't find anything. I tested it in Firefox: window.constructor() // TypeError: Illegal constructor new window.constructor() // TypeError: Illegal constru ...

Getting a JSON response from a JSP page through an AJAX request

I'm encountering an issue with a JSP page that is supposed to send a JSON response when requested through an AJAX call. However, the response is being directed to the error part of the AJAX call instead of the success part. Below is the code in my JS ...

How to make the 'no data' message more noticeable in jqGrid?

When there is no data, jqGrid typically shows the message 'No records to view' within a pager (I use the top pager for my grids). However, this message can easily be overlooked. I want to change it so that the message appears below the top head ...

Looking for a way to store data in a sub-document in MongoDB? I am having an issue where my farm sub-documents

After many attempts, I am still facing issues while saving farm data for a User. I created an API to sign up a user and save their data, including the farm object. However, every time I try to update the code, the farm object turns into null. The goal is t ...

When trying to access a property in Typescript that may not exist on the object

Imagine having some data in JS like this example const obj = { // 'c' property should never be present a: 1, b: 2, } const keys = ['a', 'b', 'c'] // always contains 'a', 'b', or 'c' ...

Ways to reset all jqGrid tables currently displayed on the interface

Is there a method to collect all grids displayed on a webpage? I am interested in looping through every grid visible on the page and invoking clearGridData() for each grid. ...

What is the function of the OmitThisParameter in TypeScript when referencing ES5 definitions?

I came across this specific type in the ES5 definitions for TypeScript and was intrigued by its purpose as the description provided seemed quite vague. /** * Removes the 'this' parameter from a function type. */ type OmitThisParameter<T> ...

Sending both the minimum and maximum slider values to PHP using POST can be achieved by formatting the data correctly

I am attempting to transmit the minimum and maximum values to PHP using submit through a dual slider bar The static page makes a request to the server-side PHP code <?php include('server/server.php') ?> Below is the JavaScript code ...

Ingesting RSS feed into an Express server

I've been searching for hours, but I just can't seem to find a solution. I was able to figure things out when working on the client side, but now that I'm trying to load posts on the server and render them in the view, I'm hitting a roa ...

Enhancing HTML Layouts using Visual Basic for Applications

I'm currently experiencing some difficulties when embedding HTML into VBA to send an email. The formatting is not appearing as intended, and I've been experimenting with different options. My first concern is regarding the font size displayed in ...

What is the best way to change a Buffer array into hexadecimal format?

After making a call to one of my API endpoints, I am receiving a Buffer array in a JSON object. My goal is to convert this array into a more user-friendly format such as hex so that I can easily compare them. Below is a snippet of the current object struct ...