Change prefix of URL in GET request - url

I'm making a get with a relative URL with YAHOO.util.Connect.asyncRequest.
Example:
var myurl = "newpagetotest?something="something");
var myCallback = {
success: function(data) {
console.log("success");
},
};
var transaction =
YAHOO.util.Connect.asyncRequest('GET', myurl, callback);
And this makes, for example, get to the
localhost:8080/share/page/newpagetotest
But if I want to change the "localhost:8080/share/page", i.e., the prefix of URL absolute. How can I change? It's possible? Or how can I get this prefix for example, for one variable?
Thanks in advance.

I made this by using location.pathname.
It solves the problem.

Related

Still having ddl redirect issues

I am still having issues. I think what I am trying to do is simple. I have a viewbag droplist - which is working fine. I just want to redirect on selection it redirect just like: #Html.ActionLink("Branch", "Employees", new { Branch = item.Branch }) | (but with the selection from the droplist) Should this be difficult?
#Html.DropDownList("Branches", ViewBag.Branches as SelectList, "Select a Branch", new { #id = "ddlBranch" })
<script>
$(function () {
$("#ddlBranch").on("change", function () {
var deptId = $(this).val();
var routeVal = { Id: deptId };
var url = '#Url.Action("Department", "Home")';
$.ajax({
url: url,
type: 'POST',
data: routeVal
}).done(function (result) {
window.location.href = result.newUrl;
})
})
})
</script>
From a comment on the question above:
So now I just need to redirect to: #Html.ActionLink("Branch", "Employees", new { Branch = item.Branch }) but Item.Branch would be $(this).val(). Can this be done?
There may be a more elegant way, but an approach I've always taken is something like this:
let url = '#Html.ActionLink("Branch", "Employees", new { Branch = "REPLACEME" })';
url = url.replace('REPLACEME', $(this).val());
window.location.href = url;
On the client-side this turns into something like:
let url = '/Brand/Employees?Branch=REPLACEME';
url = url.replace('REPLACEME', encodeURIComponent($(this).val()));
window.location.href = url;
Which would look silly to anybody examining only the client-side code, I'm sure. But since the Branch parameter might be in the query string or might be in the route, and since it's the ASP.NET MVC Framework's responsibility to manage that, generating the URL and putting the client-side value into the URL are two separate responsibilities here.
So we use the server-side code to generate the URL with a placeholder (can be any string, "REPLACEME" was an arbitrary choice) and then use the client-side code to dynamically replace that placeholder with the desired value.
This essentially replaces whatever you're trying to do with AJAX in the original question. Unless you need to invoke a server-side operation to get a result not known to the client-side code in order to build the URL, you can just omit the AJAX entirely and build the URL directly.

Remove all URL query parameters with normalize-url

I'm trying to remove all query parameters from a URL with normalize-url package but getting some strange results.
I'm using the removeAllQueryParameters option as follows:
if (options.removeAllQueryParameters) {
for (const key of urlObj.searchParams.keys()) {
urlObj.searchParams.delete(key);
}
}
And using it as follows when calling the method to add the URL to the database:
{
let url = normalizeUrl(model.article.url,{removeAllQueryParameters: true});
callServerMethod({
name: 'addNewPost',
data: {
title: model.article.title,
url: url,
},
For the example URL: https://example.com?utm_source=test&utm_medium=test&utm_campaign=test
I'm getting the following result:
https://example.com?utm_campaign=test
Interestingly for the second example URL: https://example.com?utm_source=test
The result is https://example.com - correct.
The function is skipping the last parameter in a situation where there are more than 1 parameters to be removed.
Thanks in advance for any hints.
searchParams.keys() returns Iterator and it's bad idea to modify the source object while iterating it.
Simply make copy of keys into an array and iterate over it instead:
for (const key of [...urlObj.searchParams.keys()]) {
urlObj.searchParams.delete(key);
}
The following approach worked for me, however, I'm not sure if setting the urlObj.search like that is a good practice:
if (options.removeAllQueryParameters) {
urlObj.search = '';
}

give dynamic action name in Url.action javascript

I want to give dynamic action name in Url.action through javascript.
// I want to change Index name by dynamic
$.ajax({
url: '#Url.Action("Index", "Home")',
type: "Post",
data: { Surveyid: surveyid, Category: catcode },
success: function (data) {
window.location.href = data.Url
}
like
var x="xxxx";
#Url.Action(x,"Home") -> not working throws error
#Url.Action(x.toString(),"Home") -> not working
then how can i ?
Url.Action is server generated, whereas it seems you want to change the action on the browser. What you can do is tokenize the Action, get Url.Action to generate the tokenized URL, and then substitute this in js:
var jsUrl = '#Url.Action("##", "Home")'; // ## is the token
$.ajax({
url: jsUrl.replace('##', someDynamicAction),
...
(You may need to do the same for the controller)
Edit
My conscience has gotten the better of me - doing this isn't a good idea, given that any invalid action name (or a change in the Controller or Action names) will only be picked up at run time e.g. with 404 errors.
The number of controllers and actions that you need to ajax to should be finite, and T4MVC has already solved this kind of issue.
You can create the urls to the various links:
var urlToIndex = '#Url.Action(MyControllerAssembly.Index.Home())))';
var urlToOtherAction = ...
... etc for all actions needed in the 'switch' for ajax call.
and then choose the appropriate URL for your ajax call. (T4MVC also has methods Url.JavaScriptReplacableUrl and Ajax.ActionLink although for slightly different scenarios)
Best way to use urls in your mvc application is that you define a global app_url in layout page like following:
_Layout.cshtml
<script>
var app_root = '#Url.Content("~/")';
</script>
and use in content page
any_page that inherited from _Layout.cshtml
$.ajax({
url: app_root + 'Home/Index', // or url: app_root + 'Home/' + x
something odd in your example, but I believe what you are trying to do is this
function axajThis(numberthing,path) {
var newUrl = "htttp://somplace/"+path;
/* and what ever the number x is doing */
$.ajax({
url: newUrl,
type: "Post",
data: ....
});
};
}
axajThis(x,"Home");
Little more info needed on what 'x' is.

Extjs 4 - How can I get the complete url with params from a currently loaded grid's store?

I have a grid loaded, I want to get the current stores URL which loaded the json data to it , and pass an extra param to it, and load this URL as a pdf, or xls. But how can I get the url?
Get the proxy and ExtraParams:
var url = grid.getStore().getProxy().url;
var params = grid.getStore().getProxy().extraParams;
Then, build the url:
var newUrl = url + '?' + Ext.Object.toQueryString (params);
And the newUrl will be something like this:
your_url_data.json?param1=value1&param2=value2
I don't think that exists a proxy method that do this but you can extend an existing proxy, as follows:
Ext.define ('MyProxy', {
extend: 'Ext.data.proxy.Ajax' ,
buildInternalUrl: function () {
return this.url + '?' + Ext.Object.toQueryString (this.extraParams);
}
});
And then:
var newUrl = grid.getStore().getProxy().buildInternalUrl ();
Result is the same ;)
Here's you can find the doc of proxies: Ajax Proxy
you can get the stores url by yourGrid.getStore().getProxy().url

How to add campaign tracking data to any url automatically?

I get a bunch of different URL from my sources and what I would like is to redirect to the same URL, but with campaign data added to URL (to track the referred clicks).
For example I have these URLs:
www.example.com/category/product/name.html
www.example.com/id_product=5
I want to add at the end the following: utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN
And the URLs to become
www.example.com/category/product/name.html?utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN
www.example.com/id_product=5&utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN
How to I correctly check and cover all the cases if a URL string has parameters, and add mine?
I want to do it in node.js
Thank you
Elaborating on #snkashis, a similar but arguably more elegant solution, again using node's url module, is:
var addQueryParams = function (cleanUrl) {
var obj = url.parse(cleanUrl, true, false);
obj.query['utm_source'] = 'SOURCE';
obj.query['utm_medium'] = 'MEDIUM';
obj.query['utm_campaign'] = 'CAMPAIGN';
delete obj.search; // this makes format compose the search string out of the query object
var trackedUrl = url.format(obj);
return trackedUrl;
};
This works, because url.format first looks for search and, if it can't find it, it composes the query string from the query object
(taken from node url module documentation http://nodejs.org/api/url.html#url_url_format_urlobj )
search will be used in place of query
query (object; see querystring) will only be used if search is absent.
Here is a example showing different scenarios using Node's URL module.
var url = require('url');
var exurls = ["www.example.com/category/product/name.html","www.example.com/id_product=5?hasparam=yes"]
var to_append = "utm_source=SOURCE&utm_medium=MEDIUM&utm_campaign=CAMPAIGN";
for (i=0;i<exurls.length;i++) {
var parsedobj = url.parse(exurls[i],true,false);
//Below checks if param obj is empty.
if (Object.keys(parsedobj.query).length!==0) {
var newpath = parsedobj.href+"&"+to_append;
}
else {
var newpath = parsedobj.href+"?"+to_append;
}
console.log(newpath);
}
Connect will help you:
var connect = require('connect');
var app = connect();
app.use(connect.query());
app.use(function (req, res, next) {
console.log(req.query);
res.end(JSON.stringify(req.query));
});
app.listen(3000);

Resources