utilize the registerclientscriptblock function during a javascript callback

I have a JavaScript function that checks for latitude and longitude upon page load. It calls a method on the page with those coordinates. Within the method, I utilize RegisterClientScriptBlock to define numerous variables and then generate a string of JavaScript code to showcase a map using those variables. The map does load, but I encounter an issue where the expected variables are undefined.

<script type="text/javascript">       
    function validateAndLoadMap() {           
        if (navigator.geolocation) {
            var progressPanel = $get('progress');
            progressPanel.style.display = '';
            var mapPanel = $get('map');
            mapPanel.style.display = 'none';              
            navigator.geolocation.getCurrentPosition(function (position) {                   
                // Access the location data
                PageMethods.SetSession(position.coords.latitude, position.coords.longitude, displayMap);
            });
        }
    }
    function displayMap(result) {         
eval(result);
    }
</script>

 [WebMethod]
public static string SetSession(string latitudeValue, string longitudeValue)
{
    // Perform necessary actions, use RegisterClientScriptBlock to set array variables like latitudes and longitudes
    return "showMap(" + latitudeValue + "," + longitudeValue + ");";
}

Answer №1

Unfortunately, the PageMethod won't work in this scenario because it doesn't go through the Page cycle. This means that the page doesn't trigger a postback and the script isn't rendered.

To get around this issue, you can return the script instead.

[WebMethod]
public static string SetSession(string latitude, string longitude)
{
    var js = "latitudes = new Array(); var longitudes = new Array();"; //etc...
    js += "displayCoordinates(" + latitude + "," + longitude + ");";
    return js;
}

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

Just starting out with GCP and Cloud Run, and still getting the hang of .Net. Struggling to locate any logging code samples

Currently, I am in the process of exploring Cloud Run along with .NET 7 and implementing Minimal APIs patterns. It is crucial for me to establish proper logging procedures before moving forward. While researching, I stumbled upon Google.Cloud.Diagnostics.A ...

Unable to retrieve array information within a reactjs environment

I encountered an issue while trying to retrieve data from the getObjectives function as it returned undefined. I am unsure whether the problem lies within the function itself or in the code implementation. Here is the GetObjectives() function: export asyn ...

Place a two-column table within another column, but do so only after reaching a specific row within the data

I need to create a table with two columns of data, but I want to wrap it only after a specific row in the data set. For example, I may want to start wrapping from the middle or from a certain <tr>, like the one that contains <td>Here:</td> ...

Ensuring that I accurately input the path to my JSON file within a JavaScript file

In my project using Python 3.6.4 and Django 2.0, I am facing an issue with loading a JavaScript file script.js in an index.html. The problem lies in correctly specifying the path to a JSON file data.json. Despite utilizing a XmlHttpRequest object, the ind ...

Tips for concealing a "PARTICULAR TAB BAR ITEM" on a bottom tab bar in @react-navigation/bottom-tabs

Check out this video displaying my current visible bottom tab items: Home, My Account, Cart, and Menu. Watch here I have additional bottom tab items like SettingsView that I want to render on the screen but keep them hidden from the bottom tab bar itself. ...

Combining numerous words from a dataset using HTML and Javascript

I'm attempting to include a text from a button into a modal window. Currently, it is working; however, if the data consists of more than two words, only the first word is displayed. What am I doing incorrectly? ... <button type="submit" class="ob ...

What is the best way to add two strings with indexes and points to a Three.js BufferGeometry?

I have a massive database containing tens of thousands of objects with various types of information, including their 3D meshes. Currently, I am attempting to display these objects in web browsers using Three.js. The object information is provided by anoth ...

Tips for looping through a JSON response in Angular 2

I received a response from a service containing form definition in JSON schema format. https://i.sstatic.net/BTHJM.png Now, I need to iterate through this response in an Angular component. Firstly, I fetched all the schema elements into a Formdata varia ...

Failure of Websocket on OpenShift platform with NodeJS

Although several similar questions have been raised here before, none of the suggested solutions appear to be effective. (Relevant responses will be shared below) I am facing an issue with running a basic websocket app on openshift. The application runs f ...

The function of sending files quickly

Currently, I am working on developing an API with node.js. In this project, I have a PDF file saved in the Temp folder, and my goal is to send it using res.sendFile(). However, every time I attempt to do so, it sends back an empty file instead of the PDF f ...

Ways to resolve the issue of "Property 'tenant' does not exist on type"

I have a request and I have exported this json body. export const settingsReq = { "states": [ { "initial": false, "style": "plain", "elements": [ { "type" ...

Achieving sequential actions in Javascript without the need for state updates

One aspect of jQuery that I find impressive is its ability to chain methods like .animate() and .css(). This is made possible by utilizing the special variable "this" in the backend code. I am interested in implementing a similar method chaining mechanism ...

Saving the ID of an iframe in a JavaScript variable

Can anyone help me with storing the id of an iframe in a JavaScript variable within different divs? <div id="player"> <iframe id="SAR7KmiCHto" width="560" height="315" src="http://www.youtube.com/embed/SAR7KmiCHto?enablejsapi=1" framebo ...

What is the best way to convert a string into a date and time format and then save it as varchar

In my mysql database, I am currently utilizing the data type varchar[1000]. My goal is to store date time values in this column. Is it possible to convert these dates into the datatime format and then store them back as varchar? Please forgive any errors ...

What is the process for extracting information from one table based on a column's data in another table?

Let's consider two tables: Table 1 id | email 1 | email1 2 | email2 Table 2 userid | username 2 | user1 3 | user2 Now, with the help of sails.js associations, here is what I aim to achieve: I have a username = user1. What I need to a ...

Retrieving the content of a component tag in Vue

Recently, I've been experimenting with Vue and I'm interested in achieving the following: <snippet name="Select From Table"> SELECT * FROM database.table </snippet> I want to create a link that, when clicked, triggers a ...

How to retrieve the href attribute within an anchor tag using jQuery with a selector based on the div/span ID and the

Hello, I'm new to jQuery and I was hoping someone could help me with extracting the href attribute from an anchor tag using a div or span ID selector along with the anchor tag's class. <span id="view-post-btn"><a href="https://blog.comp ...

Node.js function failing to return any value

I am facing an issue with retrieving the value of a function as it is not returning anything. Below is the function I am using (Request is an async function that sends a get request): var getVolumesOKCoin = function(pair){ request('https://www.okc ...

Copying a DOM element's appearance

I have a search box located at the top of my layout <input type="text" id="rec_search_input" ...> I am looking to duplicate this element in another location on the page, maintaining its appearance and functionality. While I understand that IDs mus ...

The image conversion should generate a shortened URL instead of the base code

Presently, I am uploading an image onto a canvas and then converting the canvas into an image using toDataURL. However, this conversion results in a lengthy base code being generated. What I'm looking for is a shorter URL instead of the Base Code. ...