Incorporate JavaScript .js file into the webpage asynchronously to invoke a web service

JavaScript File: JScript.js

function Helloworld() {
$(document).ready(function () {
    $.ajax
    ({
        type: "POST",
        url: "Default.aspx/Helloworld",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
            document.getElementById('textbox').value = msg.d;
        }
    })
});

}

Default.aspx

    <head runat="server">
    <script src="jquery-1.7.1.min.js" type="text/javascript"></script>

   //This section works fine when uncommented 
   <%--  <script src="JScript.js" type="text/javascript"></script>--%>

    <script type="text/javascript" language="javascript">
        (function () {
        var load = document.createElement('script');
        load.type = 'text/javascript';
        load.src = 'JScript.js';
        load.async = true;
        (document.getElementsByTagName('head')[0] ||    document.getElementsByTagName('body')   [0]).appendChild(load);
    })();
    </script>
    </head>
    <body>
        <form id="form1" runat="server">
            <input type="input" id="textbox" />
    </form>
    </body>

Code-Behind: Default.aspx.cs

protected void Page_Load(object sender, EventArgs e)
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "KeyHelloworld", "<script type='text/javascript'>Helloworld()</script>");
}

[WebMethod(EnableSession = true)]
public static string Helloworld()
{
    return "Hello World";
}

I am attempting to asynchronously load a JavaScript file into a page, but the function is not executing. The above is the complete code to load the JavaScript file asynchronously.

Answer №1

One issue that stands out to me is the placement of the $(document).ready() within the Helloworld() routine. To resolve this, I suggest removing the $(document).ready() altogether. Since you are using RegisterStartupScript, it is implied that you want the JavaScript to execute when the document is ready, making the inclusion of $(document).ready() unnecessary. This redundancy may be causing your problem, as $(document).ready() could have already been triggered before the Helloworld() routine is called.

To address this issue, consider modifying your code as follows:

function Helloworld() 
{
    $.ajax
    ({
        type: "POST",
        url: "Default.aspx/Helloworld",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: true,
        cache: false,
        success: function (msg) {
            document.getElementById('textbox').value = msg.d;
        }
    })
}

Answer №2

It appears that your script is being loaded asynchronously, but then called synchronously. Can you identify where the

Page.ClientScript.RegisterStartupScript
would appear in the resulting HTML?

To address this issue, consider adding a load handler for the dynamically loaded script:

    ...
    load.async = true;
    load.onload = function() {
        Helloworld(); // should this be executed upon loading?
    };
    ...

Alternatively, you can directly execute the script by removing the method declaration of Helloworld.

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

You were supposed to provide 2 arguments, but you only gave 1.ts(2554)

Hey everyone, I hope you're having a good morning. Apologies for the inconvenience, I've been practicing to improve my skills and encountered an issue while working on a login feature. I'm trying to connect it to an API but facing a strange ...

Using an array inside a for loop to follow the same structure

I am in need of prompt assistance on how to integrate my array into a for loop. Currently, my graph accepts the following as nodes: var classes = [ {"name":"test.cluster1.item1"}, {"name":"test.cluster1.item2"}, {"name":"test.cluster1.item3"} ...

react-query: QueryOptions not functioning as expected when utilizing userQueries()

When passing certain "query options" while using useQueries() to fetch multiple queries simultaneously, these specified "query options" do not get applied during query executions (e.g. refetchOnWindowFocus has a value of true but I want it to be false). F ...

Chaining multiple ajax calls in jQuery is a powerful technique that allows you

I am looking to execute a series of N ajax requests without causing the browser to freeze, and I intend to utilize the jquery deferred object for this purpose. Below is a sample scenario involving three requests, but in reality, my program might need to h ...

Investigating the variety of HTTP 206 responses pertaining to video content

Currently, I am utilizing Amazon CloudFront to serve HTML5 videos. These videos are being requested through HTTP range requests and the expected responses are often in the form of HTTP 206 Partial Content. I have a requirement where I want to log the requ ...

From Spring MVC to JSON data output

I have a JAVA EE backend and I am using Spring MVC. Currently, I have an AJAX call set up as follows: function getAllProjects() { $.getJSON("project/getall", function(allProjects) { ??? }); } In my backend system: @Reques ...

Is there a way to identify the specific button that was clicked within an Angular Material dialog?

import {Component, Inject} from '@angular/core'; import {MdDialog, MdDialogRef, MD_DIALOG_DATA} from '@angular/material'; /** * @title Dialog Overview Example with Angular Material */ @Component({ selector: 'dialog-overview-ex ...

Optimal approach for integrating enum with Angular, Mongoose, and Node.js

When it comes to fetching values from MongoDB and displaying them with AngularJS, the process can be straightforward with Jade but becomes more complex with Angular. Here is how the data flows: An array of items is retrieved from MongoDB, each containin ...

"Make sure to specify Safari input field as an email and mark

I am experiencing an issue with a contact form in my HTML/PHP code. Everything seems to be working fine, but when using the SAFARI browser, the form fails to validate if I try to submit without filling out all input fields. For example, my form includes: ...

Craft a Flawlessly Repeating Sound Experience - Online

I'm facing a challenge in creating a flawless loop of an audio file. However, all the methods I've tried so far have resulted in a noticeable gap between the end and the start. Here are the approaches I experimented with: The first approach inv ...

Maximizing Efficiency: Top Techniques for Emphasizing Grid Rows with jQuery

Currently, I am facing an issue with the jQuery code I am using to highlight the selected row in my grid. It seems to be taking longer than anticipated to select the row. Does anyone have suggestions on how I can optimize this code for better performance? ...

Hide the div when hovering occurs

I need a way to hide the 'sample' div when hovering over it and then show it again when the mouse moves away $('.secmenu').hover(function() { $('.sample').css('opacity', '0'); if ($('.secmenu&a ...

How to enable CORS in Flask while avoiding the "Response to preflight request does not have an HTTP ok status" issue

Seeking assistance with setting up client-side Javascript code to send post requests to my Flask backend. I referenced this helpful answer regarding an issue with flask-cors being blocked by CORS policy, resulting in a preflight request error without passi ...

Refreshing the entire page upon modifying a single state

I am currently in the process of constructing a page that includes numerous Charts, and I am utilizing a Material UI menu to switch between graphs. Each time I click on a new MenuItem, it alters my state and presents a new array of components. The pr ...

React modal not triggered on click event

As a newcomer to react, I am exploring a modal component import React, { useState, useEffect } from 'react'; import { Modal, Button } from "react-bootstrap"; function TaskModal(props) { return ( <Modal show={pro ...

Differences between importing {fn1} from 'lib' and importing fn1 from 'lib'

When it comes to importing functions from lodash, I have been advised by my coworker that it is more efficient to import each function individually rather than as a group. The current method of importing: import {fn1, fn2, fn3} from 'lodash'; ...

I keep encountering a parse error when trying to parse JSON that contains a numerical key

After receiving data in JSON format from a Java application, I encountered a parse error when the key was of type Long: 1: { "CONGESTION": 1, "ANSWER": 7 } However, after changing the key to a String as shown below: "1": { ...

What is the best way to retrieve the value from local storage?

const value = document.getElementById("demo").getAttribute('value'); if(typeof(Storage)!=="undefined") { alert(value); localStorage.setItem("GetData", value); alert(localStorage.getItem("GetData")); } function loading() { alert("coming" ...

Using JQuery to create a button inside a Modal dialog box

My goal is to select a row within a Table that is located inside a Modal window, and then have a button ('newBtn') within that Modal window trigger a post request to the server with the selected id of the row. However, the issue I am encountering ...

Is it possible to include a callback function as a property in an object in React?

I need to include a callback function in a prop of type object. I have developed a custom component for a data table where I pass columns, data, and actions as props. The actions prop consists of an array of objects with handler callback functions linked ...