location.path() not redirecting to page - angularjs

In node this is how I define my details route (render as jade and send).
app.get('/details', function(req, res){
jade.renderFile('details.jade', function(err, html){
if(err){
console.log(err);
}
res.send(html);
});
});
In jade with 'blah' is clicked then calls navigateToPath function with params.
a(ng-click="navigateToPath(date_obj_key, part)") blah
In angular, this function should go to this path. The url path changes in the browser but it does not REDIRECT to the page. Help (yes I am injecting the location service)
$scope.navigateToPath = function(date, part){
var path = '/details?date='+date+'&part_type='+part;
$location.path('/details').replace(); //also tried $location.url(path)
$scope.apply(); //also tried $scope.$apply and $rootScope.$apply as func
console.log($location.path());
}

I am using Fire Fox developer tools(F12) and put a break point on where I used $window.location in my project and looked at the values in $window.location and this what it shows:
It seems like this would work. for both a location in the same folder or sub-folder as well as going to a completely different web site.
$window.location = $window.location.origin + path
or
$window.location = <whatever website you want to go to>
In my case I was just using the $window.location to call a rest service to download a file that the user selected from a ui-grid while still staying on the same page. and this may have worked for me because my scenario is a bit different then what yours is I think. so all I had to do was
$window.location = "../../services" + "<path to my rest service>" + $scope.shortCode + "/" + $scope.wireInstSelectedRow.entity.fileName;
#shapiro I am not sure why this does not work
$location.path('/details').replace();
I tried the same thing originally in my project and based on the documentation: https://docs.angularjs.org/api/ng/service/$location It seems like that would work and what its supposed to be used for but what I noticed is it would put a '#' character in the url before it put the path I wanted it to take which was preventing it from going to that page. Anyhow for me it seems like as long as you are going to an html page that is in the same folder or sub-folder just doing
$window.location = <the path you want to go to>;
is a good solution... at least it did the trick for me. Hope this helps.

Related

Why ajax works only for homepage?

I have baked new project. My simple ajax function inserted to ..\templates\Pages\home.php:
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "myTest.txt", true);
xhttp.send();
}
My myTest.txt is in ..\webroot\ location.
Why this works for homepage, but not for any other created site in project? For all sites except homepage cakePHP can not find my text file. I have tried various locations for this file.
You should use "/myTest.txt" for the URL to open. Without the / on the front, it is interpreted as a relative URL, so if you're at something like /page/2, then it will look for /page/myTest.txt, which doesn't exist.
Take HTTP_ROOT as constant in bootstrap.php holding the base url(site name without sub path).
define the <base href="<?= HTTP_ROOT;?>" /> on the layout->head section. this will help to hit the site without sub-path on ajax request.
you can take a further constant eg-"siteURL" in javascript inline code on the layout's <head> OR a hidden input holding the base path.
Use the constant if you need.
siteURL+(if any further dir under webroot)+'myTest.txt'

(Angular) Js embedding an MS Word doc using AJAX return data as the URL

[Update] there is a 50 point bonus, which I will up to 200 for a working fiddle
[Update] while I prefer an AngualrJs solution, I will also accept plain JS - just anything to get me over this impasse ... a GET call to my server returns a URL and I want to embed that document into my HTML
With reference to my previous question, #MaximShoustin 's answer seemed perfect, but I am having problems.
The URL in that solution there is hard coded, but I want to get mine by AJAX. When I do, the document is not embedded, but I see no error in the developer console.
I made this fiddle, where I added these lines
to the HTML
<iframe ng-src="{{cvUrlTrusted_2}}"></iframe>
and, to the controller
app.controller('Ctrl', function($scope, $sanitize, $sce, $http) {
added , $http
and
// new stuff follows
var url = 'http://fiddleapi.rf.gd/getDocuemntUrl.php';
/* The URL contains this code ...
<?php
echo('https://d9db56472fd41226d193-1e5e0d4b7948acaf6080b0dce0b35ed5.ssl.cf1.rackcdn.com/spectools/docs/wd-spectools-word-sample-04.doc');
?>
*/
$http.get(url)
.success(function(data, status, headers, config)
{
var cvTrustedUrl_2 = 'http://docs.google.com/gview?url=' + data.trim() + '&embedded=true';
$scope.cvTrustedUrl = $sce.trustAsResourceUrl(cvTrustedUrl_2);
})
.error(function(data, status, headers, config)
{
alert('Urk!');
});
If you invoke the API at http://fiddleapi.rf.gd/getDocuemntUrl.php you will see that it returns the same document URL as was hard coded in the solution.
Please, first check my code, lest I have made a mistake.
Long description, short question : how can I embed a document who's URL is returned from an AJAX API into an HTML document using AngularJS? Free free to fork the fiddle.
Your fiddle doesn't work because of cross domain problem: http://fiddleapi.rf.gd/getDocuemntUrl.php
So I loaded simple JSON file with content:
{
"val":"https://d9db56472fd41226d193-1e5e0d4b7948acaf6080b0dce0b35ed5.ssl.cf1.rackcdn.com/spectools/docs/wd-spectools-word-sample-04.doc"
}
and:
$http.get('data.json').then(function (resp){
var cvTrustedUrl_2 = 'http://docs.google.com/gview?url=' + resp.data.val + '&embedded=true';
$scope.cvUrlTrusted_2 = $sce.trustAsResourceUrl(cvTrustedUrl_2);
});
Demo Plunker
It works fine so the problem is in your http://fiddleapi.rf.gd/getDocuemntUrl.php because this URL doesn't work in Postman too. I get:
This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support
be sure you configured it well

Implementing google custom search in angularjs

I am trying to implement google custom search in an angular js website.
When I click on the search button it does not display me anything, but the url is updated to the url.
I have followed the steps mentioned in the documentation by google.
I am not sure what I am doing wrong?
My search bar is located on the home page as -
<gcse:searchbox-only enableAutoComplete="true" resultsUrl="#/searchresult" lr="lang_en" queryParameterName="search"></gcse:searchbox-only>
my search result has -
<gcse:searchresults-only lr="lang_en"></gcse:searchresults-only>
Any input is much appreciated.
Thanks,
You may have more than one problem happening at the same time...
1. Query Parameter mismatch
Your searchresults-only does not match the queryParameterName specified on gcse:searchbox-only.
Index.html
<gcse:searchresults-only queryParameterName="search"></gcse:searchresults-only>
Search.html
<gcse:searchresults-only queryParameterName="search"></gcse:searchresults-only>
2. Angular.js is blocking the flow of Google CSE
Under normal circumstances, Google Search Element will trigger an HTTP GET with the search parameter. However, since you are dealing with a one-page application, you may not see the query parameter. If that suspicion is true when you target resultsUrl="#/searchresult", then you have two options:
Force a HTTP GET on resultsUrl="http://YOURWEBSITE/searchresult". You may have to match routes, or something along those lines in order to catch the REST request (Ember.js is really easy to do so, but I haven't done in Angular.js yet.)
Use JQuery alongside Angular.js to get the input from the user on Index.html and manually trigger a search on search.html. How would you do it? For the index.html you would do something like below and for the results you would implement something like I answered in another post.
Index.html
<div>GSC SEARCH BUTTON HOOK: <strong><div id="search_button_hook">NOT ACTIVATED.</div></strong></div>
<div>GSC SEARCH TEXT: <strong><div id="search_text_hook"></div></strong></div>
<gcse:search ></gcse:search>
Index.js
//Hook a callback into the rendered Google Search. From my understanding, this is possible because the outermost rendered div has id of "___gcse_0".
window.__gcse = {
callback: googleCSELoaded
};
//When it renders, their initial customized function cseLoaded() is triggered which adds more hooks. I added comments to what each one does:
function googleCSELoaded() {
$(".gsc-search-button").click(function() {
$("#search_button_hook").text('HOOK ACTIVATED');
});
$("#gsc-i-id1").keydown(function(e) {
if (e.which == 13) {
$("#enter_keyboard_hook").text('HOOK ACTIVATED');
}
else{
$("#search_text_hook").text($("#gsc-i-id1").val());
}
});
}
(function() {
var cx = '001386805071419863133:cb1vfab8b4y';
var gcse = document.createElement('script');
gcse.type = 'text/javascript';
gcse.async = true;
gcse.src = 'https://cse.google.com/cse.js?cx=' + cx;
var s = document.getElementsByTagName('script')[0];
s.parentNode.insertBefore(gcse, s);
})();
I have a live version of the index.html code, but I don't make promises that will be permanently live since it is hosted in my NDSU FTP.

What URL to be used in viewer.js in Box API?

I would like to know what is the URL used in Viewer.js.
<div class="viewer" style="height: 100%"></div>
<script type="text/javascript">
var viewer = Crocodoc.createViewer('.viewer', { url: 'url/to/crocodoc/assets/' });
viewer.load();
</script>
I have uploaded document using view-api.box.com/1/documents
This give me document ID.
Then I created a session using view-api.box.com/1/sessions
This give me Session ID.
I wrote viewer.js at my server and gave it URL view-api.box.com/view/{session} but this didn’t work. I am sure in am wrong here.
I would like to know how will I get URL which need to be put in Viewer.js
To use viewer.js currently, you must download the converted assets to your own server to host them. There isn't a URL to point to on the View API itself. This is outlined in the README, but the basic steps for using viewer.js are:
Download the documents assets to your server with GET /documents/content.zip
Unzip the assets on your server (let's call the unzipped directory /yourmachine/assets
Initialize viewer.js by pointing it to /yourmachine/assets i.e.
var viewer = Crocodoc.createViewer('.viewer', {
url: '/yourmachine/assets'
});
Edit: You can also use sessions with viewer.js. The URL format is:
https://view-api.box.com/1/sessions/THE_SESSION_ID/assets
Good answer Seanrose, however I was still struggling because your example didn't work. I tried
var viewer = Crocodoc.createViewer('.viewer', {
// Replace this URL with the path to the converted document assets
url: '/var/www/wordpress/wp-content/themes/themename/crocodoc/assets'
});
No combination of "//" in the beginning and "/" at the end worked
So I moved everything to a subdirectory of the index.html and .js and .css files and this worked...
var viewer = Crocodoc.createViewer('.viewer', {
// Replace this URL with the path to the converted document assets
url: 'assets'
});
Finally!! I realised it really was a URL, not a file location that was needed and experimented a bit more. The final (correct) answer is:
var viewer = Crocodoc.createViewer('.viewer', {
// Replace this URL with the path to the converted document assets
url: '//yourdomain.com/subdirectories/assets'
});
So a relative reference works (but not recommended in WordPress), however a full URL minus the HTTP: is fine, so long as "//" is at the front and not "/", and there should be no "/" at the end.

Node.js/Express Routing to a static file URL

I don't have a problem as such as I have a work-around. However the process of understanding and developing the work-around has highlighted what seems to me a fundamental gap in my knowledge (as a self-taught programmer, this happens a lot ;-) !) and I can't seem to find the answer to plug it anywhere.
Standard node.js/express setup with for example:
app.get('/index.htm', function (request, response) {
console.log("/index.htm");
});
app.get('*', function (request, response) {
console.log("*");
});
Why when the user connects directly to index.htm (by typing in the URL although I've not tried clicking on a link) does nothing fire ? The page is served no problem. The obvious use-case for this is to check if the user is authenticated prior to serving the static page.
FYI the workaround is to pass the user to a route such as "/authenticated" (which matches fine), do the check and then redirect and basically block everything else.
Thanks for educating me in advance ;-)
N
UPDATE to Raynos' question - yes (ignore the server/app variable name discrepancy).
// CREATE SERVER
var server = express.createServer();
server.configure(function() {
server.use(express.static(__dirname + '/public'));
server.use(express.logger());
server.use(express.errorHandler({dumpExceptions: true, showStack: true}));
// start of session stuff
server.use(express.cookieParser());
server.use(express.session({store: sessionStore, secret: 'secret', key: 'express.sid'}));
});
I've now found that the routing matches fine once you delete the static file i.e. in the original example, deleting index.htm means that the console will now log "/index.htm".
N
Just to bring some closure to this question:
Express static handler if it finds the file it will serve it and it won't let the other handlers to be called. If you remove it, then app.get('/index.htm' handler will be called. If you want to have a callback on all URLs just add server.use(function(req, res, next) {...}) before everything and that function will be called on all routers, make sure you call next if you want other middlewares or route handlers to be called.

Resources