This question already has an answer here:
how to make Correctly a javascript if exist (folder) command?
(1 answer)
Closed 8 years ago.
Hello stackoverflow users
I have been trying for some time to design a script.
In this script I will look for commands with an if query whether a folder exists.
I do this by using a variable make so shall he find the path using the variable.
So as follows "backgrounds /" + variable;
Here's my script:
var mapname = "dolls";
$.get( "backgrounds/" + mapname )
.done(function() {
var eld = mapname ;
}).fail(function() {
var eld = "default";
})
I'm using JQuery version 1.3.2.
I get the following error in the JS Console
Uncaught TypeError: Object #<XMLHttpRequest> has no method 'done'
does anyone know how I write this code right?
thanks ahead...
Your code will attempt to do a GET-request to the URL you specified, which doesn't necessarily mean that it is a folder. If you try this on your local machine without a web server and provide a folder name, the browser will look for "index.html" or "index.htm" in that folder. If it finds one, it will succeed, which is not really what you're after..
About actual filebrowsing. Javascript does not allow file browsing for security purposes.
JQuery 1.3 ajax GET request would look something like this
var mapname = "dolls";
var eld;
jQuery.ajax({
type: "GET",
url: "backgrounds/" + mapname,
success: function(response) {
eld = mapname;
},
error: function(msg) {
eld = "default";
}
});
Here's the Fiddle
Related
I'm trying to make a website and all I want is to have an array in my javascript file that has the names of every file in my "images/" folder.
I've tried everything. I've scoured stackoverflow over and over again and nothing has worked. I've tried ajax and php functions, and I've tried using MAMP and XAMPP as my local web server (I'm on mac, by the way, in case that's important). Whenever I try to load images and just log the file name to the console, nothing happens. I have no idea what to do.
I'm fairly certain the problem is that access to my directories is blocked, and it's the local web server that's not working, not the code (though I could be wrong).
Here are some more specific examples of solutions I've tried that haven't worked:
Attempt 1
index.php:
...
<?php
$images = array_values(array_diff(scandir($dir), array('..', '.')));
$imagesJS = json_encode($images);
?>
<script type="text/javascript">
var images = "<?= $imagesJS ?>";
</script>
</script src="js/bodyScript"></script>
...
bodyScript.js:
console.log(images); // returns null on attempt
Attempt 2
bodyScript.js:
var folder = "images/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
images.push(val); // add file name to array (doesn't work)
console.log(val); // log to console for debugging purposes (also doesn't work)
}
});
}
});
Attempt 3
bodyScript.js:
$.ajax({
url : "images/",
success: function(data){
$(data).find("td > a").each(function(){
console.log($(this).attr("href")); // nothing gets logged
});
}
});
Thank you
pseudo code
JavaScript:
$.ajax({
url : "http://mysite/getdirectories.php",
success: function(data){
console.log(data);
}
});
PHP (getdirectories.php)
$images = array_values(array_diff(scandir($dir), array('..', '.')));
exit(json_encode($images))
This question already has answers here:
Get absolute path of file on content
(5 answers)
Closed 6 years ago.
I'm trying to resolve the root url for the application in javascript using the following code:
var rootUrl = '#Url.Content("~")';
But the above code gives rootUrl as /.
What should I do to get the url as http://localhost:8000 on which my application is running.
You can get It directly from JavaScript:
var rootUrl = window.location.href;
alert(rootUrl);
The location property points to an object that contains information
about the URL of the currently loaded page.
You will get the same results with: window.location, location, location.href
Read more about window.location here
I also needed something similar a while back. My solution might not be the correct way of doing it but it was all that could find at the time. It worked for me and can work for you as well.
var rootUrl = "#Url.Content("~")";
Using the above code will give you this result:
var rootUrl = "/";
For what you are looking for you need to change your code to this:
var rootUrl = "#(new Uri(Request.Url, Url.Content("~")))";
Using the code above will give you the following result:
var rootUrl = "http://localhost:8000/";
I hope this helps.
#Url.Content("~/") is used to get your current application folder.
#Request.Url.Authority is used to get current host (with port)
So in able to get what you want you may want to mix them:
#String.Format("{0}://{1}{2}",Request.Url.Scheme, Request.Url.Authority,Url.Content("~/"))
Hope this helps!
When I launch the page, I fire up the chrome dev tools and look in the sources window, load my file and I see
Uncaught TypeError: $(...).kendoNotification is not a function
Im trying to modify an existing application ive been given which uses Kendo UI. I just want to add in a notification popup.
Referring to the docs, a common cause of this is not including all required javascript resources, but they all seem to be there. jquery, kendo.all.min and were also using kendo.modernizr
Its obviously its my problem, since all the other kendo widgets work fine.
Im trying to follow this example
http://code.tutsplus.com/tutorials/adding-application-notifications-with-kendo-ui-core--cms-20989
Something is getting initialized correctly, im just not sure where/what it could be.
The page itself is rather large, but the notification is just
<span id="popupNotification"></span>
... more html
<script>
....more stuff
$.ajax({
...
success: function (result) {
var popupNotification = $('#popupNotification').kendoNotification({
appendTo: "#SalesGrid", autoHideAfter: 5000, width: 400
}).data('kendoNotification');
var d = new Date();
popupNotification.show({ time: kendo.toString(d, 'HH:MM:ss.') + kendo.toString(d.getMilliseconds(), "000") }, "time");
}
})
</script>
[update]
I just realized i was trying to show the notification from within an ajax call, so I found a more relevant example here.
[update 2, full source of function being called ]
function postBatch(e) {
//alert('made it');
$.ajax({
url: '#Html.Raw(#Url.Action("SalesAction", "SalesController"))',
data: { batchID: e, status: "POSTED" },
async: false,
dataType: "json",
type: 'POST',
success: function (result) {
var statementBatchDS = $('#SalesGrid').data().kendoGrid.dataSource;
statementBatchDS.data(result.Data);
// *** FAILS HERE *** note: SalesGrid is a KendoUI grid
var popupNotification = $('#popupNotification').kendoNotification({
appendTo: "#SalesGrid", autoHideAfter: 5000, width: 400
}).data('kendoNotification');
var d = new Date();
popupNotification.show('Batch post error, please review', 'error');
}
});
}
Where/which script source within Kendo UI is the KendoNotificaiton widget defined? Im using kendo.all.min.js, so I was assuming that included everything. Yet, when I call the notificaiton show method (see above), the error seems to indicate it cant construct the notification..which leads me to think the source isnt being included, yet the kendo.all.min.js file is clearly being pulled in as I inspect the source in Chrome's dev tools.
So off to Telerik I go, and I read these
http://docs.telerik.com/kendo-ui/intro/installation/what-you-need
http://docs.telerik.com/kendo-ui/intro/supporting/scripts-general
Yet, the "all" version is whats in the reference
http://demos.telerik.com/kendo-ui/notification/index
I had this same problem and solved removing the kendo call from inside the AJAX snippet with a function:
success: function(data){
notify();// here i call a function to send the notification
clean();//another function to clear form data.
},
...
function notify(){
var popupNotification = $("#popupNotification").kendoNotification().data("kendoNotification");
popupNotification.show("Some notification", "success");
}
Turns out it was just a matter of upgrading the version of the Kendo libraries I was using. At least im past the point of the Notification widget not being loaded.
This question already has answers here:
How do I load the contents of a text file into a javascript variable?
(8 answers)
Closed 2 years ago.
I'm trying to load a very simple text file (eg: 0 online: or 1 online: Username or 2 online: Username, Username), from a server I control, that changes based on the number of users on a minecraft server, into a javascript var, so that I can eventually load it onto my Pebble and have it more or less live update. (read: no jquery) (also read: I have little to no idea what I'm actually doing, and if there's a better way to do it, lemme know.).
I've done a lot of googling which mostly points me to using JSON and XMLHTTPRequests (edit: XMLHTTPRequests are probably necessary) but they seem overly complex for what I need (which is to take the contents of the text file served up via HTTP, stuff it in a var, and have the Pebble spit it out on the screen.)
How can I, without JQuery, and maybe even without JSON, load the contents of a text file into a javascript var?
Some notes:
The server is eventually going to be accessed via Hamachi, but if I can get it working even locally I'll be pretty thrilled.
Following this answer, I get this result. Ditto for local IP.
This is very easy to do, just include this wrapper for the XmlHttpRequest at the beginning of your script (it makes it easier to use):
var xhrRequest = function (url, type, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
callback(this.responseText);
};
xhr.open(type, url);
xhr.send();
};
And then call it like this:
xhrRequest(url, 'GET', function(responseText) {
console.log("This is the content you got: " + responseText);
});
If you format your content in JSON it will actually make things easier for you because you will not have to parse the file and you can use JavaScript to parse it for you automatically:
For example if the reply is:
{ onlineCount: 42, usernames: [ "Alice", "Bob", "Charlie", "etc" ] }
Then you can process it like this:
xhrRequest(url, 'GET',
function(responseText) {
// responseText contains a JSON object
var json = JSON.parse(responseText);
// Now you can process this as a JavaScript dictionary
console.log("Number of online players: " + json.onlineCount);
console.log("First player: " + json.usernames[0]);
// And send messages to Pebble
Pebble.sendAppMessage({ 0: json.onlineCount });
}
);
For a complete example and the C side (on Pebble), you should take a loot at Step 3 of the Pebble Tutorial, it does exactly this with weather data.
The simplest approach would be to format the text file as a js file:
var playerinfo = "1 online: Username";
and include the script like a usual js:
<script type="text/javascript" src="http://localhost/mytextfile.js"></script>
Then the page would have a variable playerinfo for your js code to use.
In my ASP.net web project, I've written the following Javascript code in a .js file:
function getDeviceTypes() {
var deviceTypes;
$.ajax({
async: false,
type: "POST",
url: "Controls/ModelSelectorWebMethods.aspx/getDeviceTypes",
data: '{ }',
contentType: "application/json;",
dataType: "json",
success: function(response) {
deviceTypes = response.d;
},
error: function(xhr, status) {
debugger;
alert('Error getting device types.');
}
}); // end - $.ajax
return deviceTypes;
}
It was working great until I tried to load this .js file into a page in a subdirectory.
Let's suppose that the name of my project is widget.
When I use this code in the main virtual directory, Javascript interprets Controls/ModelSelectorWebMethods.aspx/getDeviceTypes to mean https://mysite.com/widget/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes and all is well. However, from the page in a subdirectory, Javascript interprets it to mean https://mysite.com/widget/subdirectory/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes and it doesn't work.
How can I write my Javascript code so that the AJAX web method can be called from pages in any directory in my application?
You've got two options:
Build a configuration/ preferences object in JavaScript which contains all your environment specific settings:
var config = {
base: <% /* however the hell you output stuff in ASPX */ %>,
someOtherPref: 4
};
and then prefix the AJAX url with config.base (and change the value for config.base whether you're on a dev/ testing/ deployment server.)
Use the <base /> HTML tag to set the URL prefix for all relative URL's. This affects all relative URL's: image's, links etc.
Personally, I'd go for option 1. You'll most likely find that config object coming in handy elsewhere.
Obviously the config object will have to be included in a part of your site where server-side-code is evaluated; a .js file won't cut it without configuring your server. I always include the config object in the HTML <head>; its a small config object, whose contents can change on each page, so it's perfectly warrented to stick it in there.
As long as you don't care about asp.net virtual directories (which makes it actually impossible to figure out from script, you'll have to pass something from the server) you can look at the URL and parse it:
function baseUrl() {
var href = window.location.href.split('/');
return href[0]+'//'+href[2]+'/';
}
then:
...
url: baseUrl()+"Controls/ModelSelectorWebMethods.aspx/getDeviceTypes",
...
... and now I see from your comments above that virtual directories are a problem. I usually do this.
1) In your masterpage, put code to inject a script somewhere, preferably before anything else (I add it directly to HEAD by adding controls instead of using ScriptManager) to make sure it's run before any other script. c#:
string basePath = Request.ApplicationPath;
// Annoyingly, Request.ApplicationPath is inconsistent about trailing slash
// (if not root path, then there is no trailing slash) so add one to ensure
// consistency if needed
string myLocation = "basePath='" + basePath + basePath=="/"?"":"/" + "';";
// now emit myLocation as script however you want, ideally in head
2) Change baseUrl to include that:
function baseUrl() {
var href = window.location.href.split('/');
return href[0]+'//'+href[2]+basePath;
}
Create an app root variable...
var root = location.protocol + "//" + location.host;
And use an absolute URI (instead of relative) when you are making AJAX requests...
url: root + "/Controls/ModelSelectorWebMethods.aspx/getDeviceTypes"
I think this function will work... it is to get a relative path as "../../../"
so if you invoke this function in each page, this will return a relative path format.
function getPath() {
var path = "";
nodes = window.location. pathname. split('/');
for (var index = 0; index < nodes.length - 3; index++) {
path += "../";
}
return path;
}
You can import the namespace at the beginning: System.Web.Hosting.HostingEnvironment
<%# Master Language="VB" AutoEventWireup="false" CodeFile="Site.master.vb" Inherits="Site" %>
<%# Import namespace="System.Web.Hosting.HostingEnvironment" %>
and on js:
<script type="text/javascript">
var virtualpathh = "<%=ApplicationVirtualPath %>";
</script>
Could you use window.location.pathname?
var pathname = window.location.pathname;
$.ajax({
//...
url: pathname + 'Controls/...', // might need a leading '/'
//...
});