GadgetGeekUK
GadgetGeekUK

Reputation: 1

Getting site URL from JavaScript in OrchardCore module

So I have a custom Orchard Core module which contains an endpoint. Also within the module I will have JavaScript that responds to click events and needs to POST to my module endpoint.

I can invoke via POSTMAN and confirm the endpoint works, but how can my JavaScript obtain the base URL/site URL in order to add the endpoint path?

Upvotes: 0

Views: 629

Answers (3)

GadgetGeekUK
GadgetGeekUK

Reputation: 1

In the web page I added the link:

<form id="myForm" name="postme" novalidate data-post-url="{{"~/MyModule/MyEndpoint" | href }}">

In Javacript I access using:

$.ajax({ url: $form["0"].dataset.postUrl, type: "POST", data: { ... }

Upvotes: 0

Hazza
Hazza

Reputation: 6591

When working within a CMS such as orchard I usually put API endpoints in data attributes. This means you can use URL helpers to create your URLs. So for example:

<div id="my-config" data-post-url="@Url.Action("MyAction", "MyController")"></div>

Then access this in your javascript:

var configElement = document.getElementById("my-config");
var postUrl = configElement.dataset.postUrl;

Upvotes: 1

Alex
Alex

Reputation: 21

You could do something like this:

var baseUrl = window.location.protocol + "//" + window.location.hostname;

This should give you only the protocol and domain name, without any paths or parameters added to it.

Upvotes: 0

Related Questions