What is the best way to build a loopback URL for an AJAX call? Say I have a page at
http://www.mydomain.com/some/subdir/file.php
that I want to load with an AJAX call. In Firefox, using jQuery this works fine:
$.post('/some/subdir/file.php', ...);
Safari/WebKit tries to interpret this as a location on the local filesystem (so it ends up translating to 'file://some/subdir/file.php'). Not only does this not point to anything useful, it also results in a security error.
Is there a way to accomplish this without hard-coding the domain into the URL? I'd like to make this as domain-independent as possible.
Update
I ended up parsing out the base url from location.href and throwing it into an accessible jQuery function like this:
/**
* Retrieves the current root URL.
*
* #return string the root URL
*/
$.fn.rootUrl = function() {
var url = location.href;
return url.substring(0, url.indexOf('/', 7));
};
Wow, that's pretty poor of Safari/WebKit, IMO.
You could observe document.href, count the slashes, and add that many "../" to the beginning of your URL.
You could have the server insert its own URL as a javascript variable when it serves up the page, then use that variable as part of your Ajax calls. It would then be both secure and automatic.
Alternatively, you can assemble your URL as follows:
'http://'+document.domain
Related
my browser is receiving a # in a redirect url instead of a ? ie:
localhost/endpoint#code=12345
However everything after # gets removed before the server endpoint is called. Theerfore I need to replace the # with a ? to ensure that the querystring gets to the server.
How can I achieve this in the browser, using JS?
Thanks in advance.
EDIT:
Just a few more thoughts on how the calls are made:
1) Call made 3rd party Identity Server endpoint
2) 3rd party Identity Server then redirects back, via browser, with provided URL ie localhost/endpoint with payload ie code=12345 usually ?code=12345 but in this case #code=12345 so full URL is localhost/endpoint#code=12345
3) At present localhost/endpoint gets sent back to server as everything post # gets stripped off, hence this question as to how I can correct localhost/endpoint#code=12345 to be localhost/endpoint?code=12345 and then forward to server
I am sorry about the down points, but I am limited here with my options
just use var fixedUrl = yourUrl.replace("#","?")
to forward inbound url, use location.href. Rude ducttape fix would be
if(location.hash.indexOf("=")>0) location.href.replace("#","?");
You can use replace if I understand you correctly.
const url = "localhost/endpoint#code=12345";
const newUrl = url.replace('#', '?'); // Replace # with ?
More information can be found here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
Hi I have a project in Flash, which calls the AMFPHP for server side integration. Now I want the same connection with Angular JS or any Javascript. So is it possible to make this happen? Actually I don't want to change the Server, because of some issue. I can change the Client Side. So please let me know, if its possible. I tried http://www.bennadel.com/blog/2612-using-the-http-service-in-angularjs-to-make-ajax-requests.htm URL but no success.
I can provide you with a jQuery ajax call. It's almost as simple as this:
<script language="javascript">
function call(){
/**
* notes:
* - parameters here could be left empty, they are just here to make the code easier to adapt
* - $.post method here is used because amfPHP JSON plugin expects data as POST. So can't use more obvious getJSON
* - if you always use the same parameters, you can do without json2.js, by setting for example
* callData = '{"serviceName":"PizzaService", "methodName":"getPizza","parameters":[]}'
*/
var callData = JSON.stringify({"serviceName": "YourController", "methodName": "getSomething", "parameters": []});
$.post("../amfphp/?contentType=application/json", callData, onSuccess);
}
function onSuccess(data){
alert("pizza : " + data);
}
</script>
The important key notes here are:
?contentType=application/json
At the URL Query. That will tell AMF that you want it to return a JSON format instead of a AMF Request.
Now, since you're going with AngularJS, one more thing you should be aware is the fact that angular already sets ajax communication with applicatio/json. So I can't really tell you how amfPHP will handle this. Personally, I believe that if a jQuery call querying an application/json works successfully, your Ajax call from AngularJS will work automatically. If it doesn't, you can try to debug amfPHP and try to see if $_POST or $_REQUEST is being feeded.
You may find some additional information about angularJS and PHP here.
You should be able to use the library I linked above and
$httpProvider.defaults.transformRequest
$httpProvider.defaults.transformResponse
you can configure the $http provider in an angular config block. Something like
angular.module('myApp',[]).config(function($httpProvider){
$httpProvider.defaults.transformRequest = AMF.stringify;
$httpProvider.defaults.transformResponse = AMF.parse;
});
We've been working on a web application and we've just about got it finished up, but there's one thing that bothering us (although by no means is it going to stop production.)
When we call one of the pages (index.html), we sometimes have to pass it a variable in the URL (searchid). So we get a page like http://domain.com/index.html?searchid=string.
We'd ideally like to not show the ?searchid=string, but I'm not sure how we'd do that.
My group doesn't own the index.html page (but we are working with the group that does), so I don't know how much we'd be able to do with anything like .htaccess or similar.
I was thinking about POSTing the variable, but I don't know how to receive it with just HTML and jQuery. Another person in my group thought that after the page loaded we could remove it from the URL, but I assume we would need a page refresh which would then lose the data anyway.
I'm trying to avoid XY problem where the problem is X and I ask about Y, so what's the right way to remove the variable from the URL?
You can use the History API, but it does require a modern browser
history.replaceState({}, null, "/index.html");
That will cause your URL to appear as /index.html without reloading the page
More information here:
Manipulated the browser history
Your question seems to indicate that the target page is not and will not be powered by some server-side script. If that's the case, I'd suggest changing the querystring to a hash, which has the advantage of being directly editable without triggering a page-load:
http://yourdomain.com/page.html#search=value
<script type='text/javascript'>
// grab the raw "querystring"
var query = document.location.hash.substring(1);
// immediately change the hash
document.location.hash = '';
// parse it in some reasonable manner ...
var params = {};
var parts = query.split(/&/);
for (var i in parts) {
var t = part[i].split(/=/);
params[decodeURIComponent(t[0])] = decodeURIComponent(t[1]);
}
// and do whatever you need to with the parsed params
doSearch(params.search);
</script>
Though, it would be better to get some server-side scripting involved here.
It's possible to rewrite the URL using JavaScript's history API. History.js is a library that does this very well.
That being said, I don't think there's any need for removing the query-string from the URL, unless you're dynamically changing the contents of the page to make the current query-string irrelevant.
You could post the data, then let the server include the posted data in the page, e.g.:
echo "<script> post_data = ".json_encode($_POST)." </script>";
This works cross-browser.
In ASP.NET MVC 3 site, I open the following uri
http://myserver/incidents/supercompany/register
That page needs to make use of ajax JSON retrieval mechanism with the help of jQuery:
$.getJSON('/Incidents/[[COMPANY NAME GOES HERE]]/SearchPeople/' + request.term, function (data)
I am new to javascript. How can I obtain supercompany part of my current url to build the
/Incidents/supercompany/SearchPeople/ string?
Assuming your URLs follow a logical structure, you can do this
var URLparts = window.location.toString().substr(7).split('/');
And you can now access URLparts[1] to get the company name. Obviously, you need to be able to know that that will ALWAYS be there, but it's a solution if you can guarantee that (eg. with htaccess).
I made a bookmark that users can add and it sends them to my site capturing the referrer.
Bookmark
My problem is that for some reason the location.href part instead of printing http:// it prints: "http%3A//". I want to remove it and get just the domain.com
I have a similar code that maybe could be useful but I'm having a hard time figuring out how to implement it inside HTML.
// Function to clean url
function cleanURL(url)
{
if(url.match(/http:\/\//))
{
url = url.substring(7);
}
if(url.match(/^www\./))
{
url = url.substring(4);
}
url = "www.chusmix.com/tests/?ref=www." + url;
return url;
}
</script>
Thanks
In most browsers, the referrer is sent as a standard field of the HTTP protocol. This technically isn't the answer to your question, but it would be a cleaner and less conspicuous solution to grab that information server-side.
In PHP, for example, you could write:
$ref = $_SERVER['HTTP_REFERER'];
...and then store that in a text file or a database or what-have-you. I can't really tell what your end purpose is, because clicking a bookmark lacks the continuity of browsing that necessitates referrer information (like the way that moving from a search engine or a competitor's website would). They could be coming from a history of zero, from another page on your site or something unrelated altogether.
Like already stated in my comment:
Be aware that this kind of bookmarking may harm users privacy, so please inform them accordingly.
That being said:
First, please use encodeURIComponent() instead of escape(), since escape() is deprecated since ECMAScript-262 v3.
Second, to get rid of the "http%3A//" do not use location.href, but assemble the location properties host, pathname, search and hash instead:
encodeURIComponent(location.host + location.pathname + location.search + location.hash);