Using Javascript to redirect to a link using JSON

Is there a way to display the CustomerPartial without reloading the page or triggering a postback when a button is clicked? Currently, when I click the button, data is posted to Home/Customer but the browser link always remains as:

localhost:49461

How can I ensure that the browser link displays the following URL after using json post to Home/Customer?

localhost:49461/Home/Customer

I need the browser link to reflect the correct URL instead of always displaying localhost:49461.

What steps should I take in order to change/redirect the browser link using JavaScript and Json?

Here is the HTML code for the button:

<button type="button" onclick="MyFunction">Go To Customer Page</button>

And the corresponding JavaScript function:

function MyFunction() {
$.ajax({
url: "/Home/Customer",
type: "POST",
dataType: "json",
contentType: 'application/json',
success: function (mydata) {
$("#MyDiv").html(mydata);
},
error: function () {
$("#MyDiv").html("Error");
}
});
return false;
}

The Controller method used:

public ActionResult Customer(MyModel model)
{
var stringView = RenderRazorViewToString("CustomerPartial", model);
return Json(stringView, JsonRequestBehavior.AllowGet);
}

Contents of CustomerPartial:

<h1>Welcome To Customer Page</h1>

To handle Json requests:

public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}

Answer №1

To implement this functionality, include the following code within the .success function of your Ajax request (compatible with HTML5 only):

function updatePageWithData(response, path){
     document.getElementById("content").innerHTML = response.html;
     document.title = response.pageTitle;
     window.history.pushState({"html":response.html,"pageTitle":response.pageTitle},"", path);
 }

Answer №2

Resolution:

I inserted the following code snippet into my success section within my JavaScript code.

history.pushState('', 'Updated URL: '+href, href);

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

What is the method to make a file download using JavaScript?

In my jQuery ajax form, a user inputs their email and upon submission, they should receive an automatic download of a file. Here is the structure of the form: $(".email-form").submit(function(event) { event.preventDefault(); var $form = $(this), ...

Is it possible to generate unique identifiers for v-for keys using vue-uuid?

I'm attempting to utilize a random string (UUID v4) using vue-uuid for existing items and future additions to the list in my to-do list style application. However, I'm uncertain about the correct syntax to use. After installation, I included it ...

Retaining the Chosen Tab upon Page Reload in Bootstrap 5.1

Struggling to maintain the selected tab active after page refresh. It's worth noting that I'm using Bootstrap 5.1 and have tried various solutions found for different versions without success. <ul class="nav nav-pills mb-3" id=&q ...

Troubleshoot: Inline Styling Problem with Bootstrap 4 Popover

Is there a way to dynamically change the color of the Bootstrap 4 popover title using inline HTML style attributes? It seems that the plugin is removing them without any logical reason. Below is an example demonstrating this issue: $('#test'). ...

Initiate an "execute.document" command directly from the address bar

While reviewing my old website, I stumbled upon this snippet: <input type="image" id="QuickPass" name="QuickPass" src="/images/QuickPass.gif" alt="Quick Pass" onclick="document.pressed=this.value" value="QuickPass" /> nestled within this form: & ...

Saving variable with the selected option from the DropDown menu, and subsequently utilizing this value to display a specific HTML page

I have a dropdown menu that pulls values from my SQL database. Once a value is selected, it is stored in a variable. For example, if I choose "ABC" and store it in the variable, I want to use this variable to open a local HTML file named ABC.html. The o ...

Sticky header in React data grid

Is there a way to implement a sticky header for a data grid in react? I have tried various methods but haven't been able to figure it out. Any suggestions would be appreciated. You can find my code sandbox example here. #react code export const Styl ...

I'm trying to create a drop-down list in JS that will save selected options to a database using PHP. I'm feeling a bit lost, anyone

My goal is to upload a pdf file with specific options that determine its category. The challenge arises when creating multiple options, as the second option depends on the first choice and involves JavaScript functionality for which I am unsure how to stor ...

Incorporating additional value attributes without replacing the existing ones

Is there a way to add a value attribute through jQuery without removing the old attribute, similar to how addClass works? I have 7 input fields that are being typed in, and I need to combine them into one word and pass it to another input field. When I try ...

Passing two variables through a Javascript URL to dynamically update a dropdown menu based on the specified values

What is the best way to send two variables to a JavaScript function in order to modify the dropdown list according to those values? $(document).ready(function() { $("#date").change(function() { $(this).after('<div id="loader">& ...

Temporary redirection of external links page

There is a specific feature I am trying to implement on my website, but I am having trouble figuring out how to make it work seamlessly. When a user connects to my website and starts navigating through the menus, I want them to be redirected to a specific ...

Click to expand for answers to commonly asked questions

Having trouble setting up a FAQs page on my blog and can't seem to get the code right. Check out what I'm trying to do here: http://jsfiddle.net/qwL33/ Everything seems fine but when I click on the first question, both questions open up. Can som ...

Tips on accessing a Google Apps Script function or variable within an HTML reference tag

I am attempting to retrieve URL entries using Google Apps Script. I have tried using the <??> tag to enclose the code, but it only displays the function name rather than its purpose. <a id="a1" href="https://docs.google.com/forms/d/1tC7hfPCbELEcY ...

Generate an additional element for each element when clicked, triggering an error warning

When creating a form, I want to display an error message next to each invalid element when the submit button is clicked. Although I am close, the issue is that it adds the span tag twice after the element if two elements are invalid. I need it to be added ...

Tips for configuring <link> in NextJs to only activate on a single click

I am currently utilizing the Flickity-React-Component to create a swappable Carousel and I have included NextJs <Link> in its children. However, the issue arises when I click and swap the carousel - after releasing the mouse click, it automatically ...

Resolving Issues: AngularJS Service Utilizing GET JSON Data

I've been working on a basic AngularJS project that reads data from an external JSON file. Despite multiple attempts, I'm unable to figure out why the application isn't functioning properly. Any suggestions or insights would be greatly appre ...

Encountering an issue while attempting to make changes and test a copied GitHub library - npm ERROR! version cannot be located

I'm new to the world of Github forking and pull requests. My goal is to fork a repository, make some changes, and test them out on a project before submitting a pull request. I've already forked the repository and made modifications, but I' ...

What is the method for utilizing Jquery to target the width value of an inline property?

I am struggling with selecting the "style=:width: 10%" value using jquery for a progress bar element in bootstrap. <div class="progress-bar progress-bar-info" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 10% ...

Modify a single field in user information using MySQL and NodeJS

I am currently working on developing a traditional CRUD (create, read, update, delete) API using NodeJS/Express and MySQL. One of the routes I have created is responsible for updating user information, which is functioning correctly. The issue: When I d ...

Decide whether to fulfill or deny a Promise at a later time in

When working on an Angular2/TypeScript project, a dialog is shown and the system returns a Promise object to the caller. This Promise will be resolved after the user closes the dialog. The interface of the Promise class does not include methods like resol ...