Is it true that including <%%> in a JavaScript function will ensure it is executed upon page load?

Here is the javascript function I am working with:

        function redirect() {
        window.setTimeout(function () { <% Response.Redirect("~/Pages/ExecrcisePlan.aspx"); %> }, 2000);
    }

I tried calling this function from inside my asp.net page, but it seemed to execute on page load and redirect me without being called. Even after commenting out that line, the same issue persisted. I am aware that there are other javascript alternatives available, but I was curious why this method did not work and if there is a way to make it functional?

Answer №1

Utilizing <% %> blocks within an aspx or cshtml page triggers immediate code evaluation upon page generation, given that they are classified as server-side code blocks. An alternative approach involves incorporating an ASP.Net AJAX Timer control instead of relying solely on pure javascript.

Alternatively, you could opt for a javascript redirection method such as location.href, followed by utilizing a block <% Response.Write(url) %> to display the desired URL.

Answer №2

Here is a solution for what you want to achieve:

redirect();

function redirect() {
  var timer = setTimeout(function() {
  window.location.replace(<% Url.Content("~/Pages/ExecrcisePlan.aspx"); %>);
  }, 2000);
}

http://jsbin.com/bCdEfGH/2/

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

Is there a way to ensure that a method is always called in JavaScript after JQuery has finished loading

We recently integrated jquery load into our website to dynamically load content into a div without refreshing the whole page. However, we've noticed that in the complete function, we have to constantly re-apply various bindings. Is there a way to set ...

Displaying empty values as zeros

Currently, I am creating a chart using Morris js. The data for the chart comes from a server and consists of dates and values. However, there are cases where certain dates do not exist in the data set. In such situations, I want to display these non-existe ...

Utilizing Jquery to Integrate Hashtags

I'm looking to implement a feature where any text I write starting with a # symbol automatically changes color to blue, and then returns to black once I hit the space key to end the text. I attempted to achieve this using the following logic within a ...

The ChartistJs is unable to find the property '_index' of an undefined value, either being 0 or null

I recently incorporated chartistJS to display charts on my website. I have successfully implemented the 'onClick' function provided by chartist. Here is a snippet of the code I used: public horizontalBarchartoptions = { 'onClick&apo ...

Looking for assistance with submitting two forms in one AJAX request to a single file.php

Hey there, I'm looking to submit 2 forms using a single ajax or jquery request to a common file. The code snippet I currently have is as follows: <form id="filter-group1" class="form" target="remember" autocomplete="on" method="post"> <i ...

Limit the length of text using jQuery by specifying the maximum pixel width

Trying to utilize jQuery for a quick function that calculates the pixel width of a string on an HTML page and then shortens the string until it reaches a desired pixel width... Unfortunately, I'm encountering issues with this process as the text is n ...

Storing a Mongoose value as a date: best practices

Whenever I store a date in Mongoose, it always gets saved as a string. let currentDate = new Date().toISOString(); let item = await Item.findOne({}); item.details.expiryDate = currentDate; await item.save(); After checking the database ...

When I click on the button, the page reloads instead of executing the essential code

On my website, there is a settings page where users can edit their profiles. After editing, they click the update button which triggers the updateProfileData function. This works smoothly in Chrome browser, but in Firefox, the page reloads as soon as the b ...

Which specific technological platform or framework would be most suitable for constructing a similar project?

https://i.stack.imgur.com/LL1g9.png Looking at the image provided, my goal is to allow users to navigate between pages on the Home page without having to refresh the entire browser window. I believe this can be achieved using Ajax technology, am I correct ...

ASP.NET Utilizes Datalist Controls for Enhanced Accessibility

Utilizing a DataList that includes several TextBox elements inside a table. I attempted the following code in the code-behind: TextBox txtbox = dlCRR.FindControl("TextBox1") as TextBox; An error message appears: Object reference not set to an instance ...

Creating a unique tooltip component for ag-grid with the use of Material tooltips

I am facing an issue with the current angular ag-grid tooltip example, as it is not functioning properly. https://stackblitz.com/edit/angular-ag-grid-tooltip-example-fb7nko Utilizing Javascript/typescript in Angular 8 with the latest ag-grid release. I h ...

the navigation process in $state was not successful

In order to navigate from page A to B, I included the following code in my page A (history.html) view: <a href="#/history/{{data.id}}"> <li class="item"> {{data.items}} </li> </a> In my app.js file, I set the state as ...

Set the rows of the Lookup(master) table to "readonly" once they are being accessed

Our system contains multiple lookup tables; if a lookup table is already referenced by another table, the "value" column within that lookup table should not be allowed to be updated or deleted. For example, the EnrollStatusName in the EnrollStatus table. ...

Steps for fixing the error "Fixing the MongooseServerSelectionError: Incorrect message size while trying to connect to MongoDB

Encountering a problem when attempting to link up with my MongoDB database using Mongoose in a Node.js program. The error message reads: Cannot connect to the database MongooseServerSelectionError: Invalid message size: 1347703880, maximum allowed: 67108 ...

What method can I use in Javascript to extract the mealtype data from the Edamam nutritional API?

My goal is to extract the mealtype information from the API linked below. After reviewing the API, it seems that a POST request is required to retrieve mealType data. However, I am uncertain about the correct syntax for this request. For instance, if a u ...

The string entered was not in the correct format and the RequiredFieldValidator is malfunctioning

After incorporating the suggestions, I made some updates to my code. Textbox: <asp:TextBox ID="txtStudent_Id" runat="server"></asp:TextBox></td> <asp:RequiredFieldValidator runat="server" ControlToValidate="txtStudent_Id" Erro ...

A deadlock is caused by the slow execution of Application_Start in the global.asax file

My global.asax Application_Start code takes around 2-3 minutes to complete due to long database queries and other processes. Whenever I deploy a new version of the site, deadlocks occur on aspnet_isapi.dll causing the application to not start. The only w ...

The JSON parser was anticipating a data entry but instead encountered a 'function'

I am currently working with a collection that contains BsonJavascript objects. { "Name" : "HourlyMP", "MapFunction" : function(){ var _id = this.srcip + " - " + this.hour var valueData = { ip: this.srcip, ...

What exactly is the mechanism behind this callback functioning in the given code?

Could someone please explain how cb(); functions in this code snippet? What is its purpose? beforeCreate: function(user, cb) { bcrypt.genSalt(10, function(err, salt) { bcrypt.hash(user.password, salt, function(err, hash) { if (e ...

Does NodeJS have a counterpart to C#'s GetAwaiter function?

Here is the code I am working with: async function testingFunction() { var mongo = await MongoClient.connect(connectionString); var db = await mongo.db(databaseName); var auditCollection = db.collection(collectionName); var result = await ...