Unable to execute JavaScript within a partial view called through an AJAX request in MVC

In my partial view, I have written JavaScript code that retrieves the Geo-location of a client.

<h1>Map</h1>
<style type="text/css">
    #map-canvas {
        height: 500px;
    }
</style>

<script type="text/javascript"
        src="http://www.google.com/jsapi?autoload={'modules':[{name:'maps',version:3,other_params:'sensor=false'}]}"></script>

<script type="text/javascript">        
    function initialize() {

        var myLatlng = new google.maps.LatLng(37.4219985, -122.0839544);
        var mapOptions = {
            zoom: 12,
            center: myLatlng
        }
        var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            title: 'Provider'
        });

    }
    google.maps.event.addDomListener(window, 'load', initialize);
</script>

<div id="map-canvas"></div>

When loading this partial view through an Ajax call from another view using an action-link click, the text appears but the map does not load. However, when I directly load the view, the map is visible. Any suggestions on how to fix this issue?

Answer №1

The reason your initialize function is not triggering is likely because it is attached to the window instead of the body element. To fix this, simply call it after the ajax call is successful. Here's what you need to do:

$(function () {
    $('.provider-details').on('click', function (e) {

        $.get("/Provider/Map", function (response) {
            $('#map').html(response);
            initialize();
        });

        e.preventDefault();
    })
});

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

Link Array with Google Charts

I've been struggling for a long time to connect this array to a Google chart with no success. I would really appreciate some assistance in identifying what mistake I've made. I have created a jsfiddle where the array appears to be correct, and wh ...

Troubleshooting an Ajax Error

Encountering an issue when trying to bind two components (checkbox and label) by using the "for" tag attribute for the label and the "id" tag attribute for the checkbox. An ajax debug error is thrown: "Cannot bind a listener for event "click" on element "v ...

What is the significance of the error message '[WDS] Disconnected!' in the context of using webpack and Vue.js?

Currently, I am engaged in a Django project that utilizes Vue.js for the frontend. Whenever I refresh the page, I encounter the "[WDS] Disconnected!" error. Despite the website's full functionality and absence of issues, this error appears every time ...

How come Google Code Beautifier suddenly ceases to function properly when combined with JQuery DatePicker?

When the Google Code Prettifier or JQuery Syntax Highlighter is used on the same page as the JQuery DatePicker, both functionalities may not work correctly. What could be causing this issue? ...

Enforcing automatic spell check on dynamically generated content

After some experimentation, I have discovered that the spell check feature in most browsers is only activated when the user moves to the next word after inputting text. Another interesting finding is that it is possible to "query" the spellchecker by simpl ...

How can one retrieve unspecified elements from a third-party website using AJAX?

Currently, I am working on extracting an element from an external website using AJAX. I have successfully retrieved the page using the following code: var xmlhttp; var version; if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari ...

When using a jsonp ajax call, the response is successfully returned as json in Firebug, but unfortunately it

After encountering a jsonp cross domain ajax query, I am facing an issue where the jQuery ajax function's error part is triggered despite receiving a status of 200 OK and a status text of success. Even though I can monitor the response in Firebug and ...

Click on an image to dismiss a material-ui dialog

Trying to include a clickable image to close a material-ui dialog, but encountering an issue where the onClick event is not responding. The props.onRequestClose function works fine when clicking outside of the dialog. What could be causing this problem? ...

Exploring the vulnerability in switching an ajax request to another PHP file for potential exploitation clarification

I am currently developing an application that processes an ajax call (using jquery) and provides validated users with an entry token for the website. For instance, if the ajax call is made to checkAuth.php and all other php files are in the same directory ...

Ways to initiate a transition upon clicking a button, causing it to switch from being hidden (`display: none`) to visible (`display: block`)

I'm attempting to create a smooth transition effect when a button is clicked, similar to a toggle function, where the content below it seamlessly shifts instead of abruptly moving. The classic example of this is the Bootstrap navbar hamburger menu, wh ...

Retrieve the value of EJS depending on the JavaScript variable

I am in the process of developing a website for booking appointments using Express, EJS, and MongoDB. When a request is made to '/booking', the book page appears displaying all details about the doctor. Upon clicking the book button next to each ...

Challenge with Angular *ngFor: Struggling to Access Previous Elements

In my angular and node application, I am using socket.io. When a user joins the room, they can see their username in the user list. If another user joins, the first user can see both usernames but the new user can only see their own. This pattern continues ...

The Frida server experienced a crash when attempting to connect with an Android device

I'm attempting to conduct a penetration test and hook into my Android application method using Frida. However, when I execute the command from the Windows command prompt, my application crashes, and the intended method is not executed from the APK. I ...

Adding a Bearer Token to a GET request using location.href: A step-by-step guide

At the moment, I have all my ajax requests sending an Authentication token. However, I have created a service for exporting to excel and since ajax doesn't support that, I am using location.href for the get request. Is there a way to include the token ...

Having trouble importing a variable from a precompiled library in TypeScript JavaScript

Here is the content of my package.json file: { "name": "deep-playground-prototype", "version": "2016.3.10", "description": "", "private": true, "scripts": { "clean": "rimraf dist", "start": "npm run serve-watch", "prep": "browserify ...

Encountering issues with certain Bootstrap components while integrating with ReactJS

I'm currently experimenting with Bootstrap components such as Modals and Popovers, but I'm facing an issue where nothing is being displayed. Specifically, when I attempt to click on the button to show the modal Fading or popover, nothing happens. ...

When an absolute positioned DIV is nested inside a relatively positioned DIV, it disappears when the page is scrolled

A unique feature of my DIV is that it remains fixed at the top of the page as you scroll. This is achieved by setting its position to fixed. However, within this main container, I have another div with a relative position. While the content in the relative ...

Is the syntax incorrect or is there another reason for the empty array being passed, as the "resolve" callback is running before the completion of the for loop?

The for loop will iterate over the length of req.body, executing a Customer.find operation in each iteration. The resolve function will then be called with an array containing the results of all the find operations. let promise = new Promise(function(res ...

Incorporating a node module into my Angularjs application

Recently, I stumbled upon a handful of modules that I would like to incorporate into my Angular app. However, I find myself at a crossroads on how to effectively integrate them into my project as I will need to use "require()" in my factory file. One part ...

Tips for creating animated arc fills using CSS

Can we gradually fill the color of a CSS semi-circle in a counterclockwise direction, similar to a progress bar? Here is the code for the semi-circle: https://jsfiddle.net/sonymax46/wqfovdjh/7/. .cc{ background-color: transparent; overflow: hidd ...