Tips for creating a delay in executing an inline expression in JavaScript

In my code, I have a specific expression <%= GetAddPinScript() %> that calls a method located in the backend of my application. This method generates JavaScript code dynamically and returns it, as shown below:

AddPushpin('data', 'more data', numbers, numbers, 'no');

The important part to note here is that the variable 'no' within the generated JavaScript is crucial for determining whether certain content should be displayed or not in the rest of my code (essentially acting as a boolean).

The issue I'm facing is related to timing - the method in my backend requires a variable (result in the code snippet provided) to be passed through an AJAX call prior to the evaluation of the expression, so that the correct variable can be generated in the JavaScript. However, the expression evaluates during page load every time.

So, the question is: How can I delay the evaluation of the expression until after the AJAX call has been made?

Below is the relevant JavaScript function:

function displayGeneralInfo(specifics)
     {
     var callback = AddQueryString(window.location.href, "action", "displayResults");
     $.ajax({
            url: callback,
            type: "POST",
            async: false,
            data: {
                specifics: specifics
                }
                });
                <%= GetAddPinScript() %>
     }

and the AddPushpin JavaScript function:

function AddPushpin(name, description, latitude, longitude, selected) {
    // Add a pin to the map
    var center = new Microsoft.Maps.Location(latitude, longitude);
    var pin = new Microsoft.Maps.Pushpin(center, null);

    if(selected !== null || selected!="")
      {
      if(selected == "yes")
       {
       infoboxOptions = new Microsoft.Maps.Infobox(center,
        {                          width: 285,
                               height: 170,
                               visible:true,
                               actions:[{label: 'Associate', eventHandler: associate}]
                               });
                               map.entities.push(infoboxOptions);
        }
    }
    map.entities.push(pin);
}

Lastly, here's a snippet from the backend code:

public string GetAddPinScript()
    {
foreach (Location location in foo(x => !string.IsNullOrWhiteSpace(x.Longitude) && !string.IsNullOrWhiteSpace(x.Latitude)))
        {
            selected = "no";
            if (!result.IsNullOrEmpty())
            {
                if (location.MapPinDescription.IndexOf(result) > 0)
                    selected = "yes";
            }
            pins.Add(string.Format("AddPushpin('{0}', '{1}', {2}, {3}, '{4}');",
                location.etc1("'", @"\'"), location.etc2("'", @"\'"), location.etc3, location.etc4, selected));
           string retVal = string.Join("\n", pins.ToArray());
           return retVal;

Answer №1

Delaying execution is not possible in this scenario. The JavaScript is executed on the client side, while this particular function runs on the server side. Asp.net completes all data binding before sending it to the client, making it impossible to wait for some client-side code to finish executing before running this function. My recommendation is to call this function when the ajax call is made to the server. Have the function return some HTML, then include it in your HTML within the success callback.

Answer №2

To ensure the add pin script runs after the completion of the ajax call, it should be set as the complete handler for the ajax call:

function showSpecificInfo(details)
 {
 var successCallback = UpdateURL(window.location.href, "action", "showResults");
 $.ajax({
        url: successCallback,
        type: "POST",
        async: true,
        data: {
            details: details
            },
        complete:  <%= RetrieveAddPinScript() %>
 });

It is important to note that in the provided syntax, RetrieveAddPinScript is expected to return a function, which could either be the name of an existing function or an anonymous function block.

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

Set up a two-dimensional array within a loop within another loop

Currently grappling with a conundrum in which I must declare a 4x4 two-dimensional array named multiplicationTable. The goal is to initialize it within a nested loop so that the elements equal the product of their respective index values. Subsequently, u ...

Tips for adjusting the position of rows within a v-data-table - moving them both up and down

Is there a way to rearrange rows up and down in the table? I've been using the checkbox feature and the CRUD data table from the documentation, but I haven't found any examples on how to implement row movement. Currently, my v-data-table setup l ...

Ways to showcase the coordinate values on the surface of a 3D cube using three.js

I am currently working on developing a 3D cube using three.js, which rotates and translates continuously. At the moment, I am rotating the 3D cube using randomly generated numbers, but eventually, these numbers will be sourced from an accelerometer and gyr ...

When the page is refreshed, the ContextProvider fails to mount

For the complete code, you can view it on codesandbox. Within my countries API application, I have implemented two Route components - <> <Header/> <Router> <Switch> <CountriesDataProvider> ...

Showcasing the template dynamically in Angular directive as the scope changes

Provided below is my custom directive: function ajaxMessageData() { var ajaxMessage = { link: link, restrict: "EA", template: "success", scope: { success: '=' } }; return ajaxMessa ...

Identify the default constructor generated by the compiler through reflection in C#

My project is focused on .NET 3.5 SP1 and I am utilizing CommentChecker to validate my XML documentation. Everything is functioning correctly until I encounter a class structure like the one below: /// <summary> /// documentation /// </summary> ...

Effortless script to make a URL request and display the response status | using JavaScript with jQuery

Is there a way to use JavaScript or jQuery to request a URL or website address and display the response code? For example: request www.google.com if (response_code = 200) { print "website alive" } else if (response_code = 204) { print "not found"; } ...

Tips for modifying HTML elements using Javascript after a link is clicked

Imagine a scenario where there is a DIV called "videoplayer" containing an image within it. Is there a straightforward method to modify the HTML content inside this DIV when a link is clicked? For instance, the current content of the DIV is as follows: ...

Tips for transforming my JSON format into the necessary column layout for C3.js

The data structure returned by my API is as follows. However, I need to reformat this structure for use in C3.js. { "data":{ "test7":[ { "Date":"2016-04-26 00:00:00", "aId":7, "Amount":436464, "Piece":37 ...

What is the best way to stringify a JavaScript object that contains a blob as its data?

While recording my webcam using MediaRecoder and sending each blob to the server via Websocket, I encountered a challenge. Initially, I was using the following code: recorder = new MediaRecorder(canvasStream); recorder.ondataavailable = e => ...

Removing zeros from a one-dimensional tensor in TensorFlow.js: A step-by-step guide

If I have a 1D tensor (distinct from an array) with the values [0,2,0,1,-3], my goal is to retrieve only the non-zero values. Using the example provided, I want to receive [2,1,-3] as the output. Is there a way to achieve this in TensorFlow.js? ...

Refine results by searching through the text contained in the elements of every div

I recently came across a helpful fiddle that allows text to be hidden based on what is entered into a search box. However, I am struggling to apply this method to a div that contains multiple elements. Is there a way to modify the jQuery in the provided fi ...

JSF not triggering Ajax event

I'm facing an issue where the Ajax event is not firing to call the actionListener or update the second select menu. Can anyone help me with what might be causing this problem? <p:selectOneMenu value="#{player}" converter="playerCon ...

An issue caused by the interaction between node.js and mongodb

Whenever I try to run my JS file, I encounter the following error: Charon:modules Modius$ node testfile.js node.js:201 throw e; // process.nextTick error, or 'error' event on first tick ^ ReferenceError: define is not def ...

Converting an object of type Object into List<AnotherObject>

I am facing an issue with deserializing JSON to C# classes in my application. One of the classes includes a property of type object: public object invoiceDetails { get; set; } I decided to make it of type object because it was the only way the JSON could ...

What is the best way to send a parameter to the callback function of a jQuery ajax request?

I am facing an issue where I need to pass additional variables to a jQuery ajax callback function. Consider the following scenario: while (K--) { $.get ( "BaseURL" + K, function (zData, K) {ProcessData (zData, K); } ); } func ...

The functionality for reading cookies in asp.net is not working on the same page

I am having issues with reading and writing cookies on my single page application. The page includes a button and a textbox, and I expected the previous cookie to be read on page load. However, the cookie named "mycookie" is always null, leading me to wo ...

Using Ng If with a boolean value to dynamically update the title of a webpage

On my Stock page, I have multiple fields labeled as Title 1. https://i.sstatic.net/FpCsW.png When I run a console.log, it indicates that I am on the first page! ngOnInit() { this.currentPortfolio = this.shrd.getData('currentPortfolio'); ...

What is causing the inefficacy of this particular SQL request method, while the alternative one proves effective?

It's surprising that the one not working is from the mssql package page. Why isn't it functioning on my machine? What am I missing here? The other example I found online works perfectly. On a side note - should these requests be done asynchronou ...

Retrieve data from the database and showcase it in the input fields

There are 7 checkboxes for each day of the week (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) with start and end time tags for each. Take a look at the design picture below. Within the database, there are multiple entries where the firs ...