I have placed some XML files under a directory. I need to populate a drop down using javascript to display all those XML file names. How do I do that?
You've been way too broad when it comes to circumstances and situation, so I'll be broad back with an answer.
Given the following:
The web-page with the <select> you need to populate is hosted on the same server as the file list.
The server has the ability to use a server-side language (e.g. PHP, ASP)
You don't mind, or can at least decipher jQuery code (makes what I'm about to post more about the concept than the practice)
You will need something like the following setup:
Create a server-side file that dumps a list of file names
You're going to need to look up some way to retrieve and dump the list of the files. This is so JavaScript & AJAX can go fetch this list and dump in in to the drop-down list. Example output of said script (which I'm aliasing as /server-side-file-list in the JavaScript below)
file-001.xml
file-002.xml
file-003.xml
file-004.xml
Setup the <select> on your page
<!-- Somewhere in the page -->
<select id="xml-file-list" name="xml-file-list"></select>
Setup the JavaScript/Ajax code
<!-- This should go in the <head></head> portion of your page with the select -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$.ajax({
url: '/server-side-file-list',
success: function(d){
$.each(d.split(/[\r\n]+/),function(i,e){
$('<option />',{ value: e }).text(e).appendTo('#xml-file-list');
});
}
});
</script>
Basic work-flow:
HTML page loads up with an empty <select>
jQuery takes over and fetches a list of files from that /server-side-file-list script using AJAX (behind the scenes)
The results are returned and placed in to the <select> as <option>s.
Done.
--
Food for thought:
A better method may be to load your file list in to the page at run time (if possible). That is to say, if the page you're working on is an ASP or PHP or other type of server-side language page, you can retrieve the file list when the page is called upon and load it at that time (and avoid using javascript altogether).
Assuming you're talking about local files, you need a browser that supports the W3C FileSystem API.
You can test for compatibility at www.html5test.com
If you're completely agnostic about the name of xml file you will need a server-side language to get a list of file of a server directory.
Otherwise, if you're in control of filenames, a workaround could be give them a progressive name (e.g. 1.xml, 2.xml...) and try to make some chained ajax HEAD calls.
If the ajax request of 1.xml returns a 200 server status, then ask for 2.xml and so on, until you get a 404 error. For each ajax call you can add the name to an array and then use it to create a dynamic select.
Of course, for a matter of performance, this should be intended only as a workaround and it's not reliable at all, since a 404 could occur even if the resource exists, so I strongly suggest to use a server side language
anyway this is a jQuery 1.5+ example explaining the workaround. Suppose you have 1.xml, 2.xml and 3.xml. The HTML is just an empty select
<select id="xmlfiles"></select>
Javascript/jQuery
<script>
$(document).ready(function() {
/**
* we need to only know if the resource exists or not
*/
$.ajaxSetup({ type : "head" });
/**
* Function reading xml file. When deferred has been resolved
* (when first 404 occurs) an array of filename is passed.
*/
function getXMLFile(path) {
var deferred = $.Deferred(),
xmlFiles = [];
(function getFile( i ) {
var url = [path, i, '.xml'].join('');
$.when($.ajax(url))
.done(function() {
xmlFiles.push(url);
getFile( ++i );
})
.fail(function() {
deferred.resolve(xmlFiles);
});
}(1));
return deferred.promise();
};
/**
* when we have read xmlfiles in "./" then for each file
* retrieved append an option
*/
$.when(getXMLFile('./')).then(function(file) {
var select = $('#xmlfiles');
/* create options */
$.each(file, function(i, filename) {
var option = $('<option></option>');
option.html(filename).attr('value', filename).appendTo(select)
})
});
});
</script>
and this shows a select with options
./1.xml
./2.xml
./3.xml
(Sorry for my verbosity)
Related
I have this JSON file I generate in the server I want to make accessible on the client as the page is viewable. Basically what I want to achieve is:
I have the following tag declared in my html document:
<script id="test" type="application/json" src="http://myresources/stuf.json">
The file referred in its source has JSON data. As I've seen, data has been downloaded, just like it happens with the scripts.
Now, how do I access it in Javascript? I've tried accessing the script tag, with and without jQuery, using a multitude of methods to try to get my JSON data, but somehow this doesn't work. Getting its innerHTML would have worked had the json data been written inline in the script. Which it wasn't and isn't what I'm trying to achieve.
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
You can't load JSON like that, sorry.
I know you're thinking "why I can't I just use src here? I've seen stuff like this...":
<script id="myJson" type="application/json">
{
name: 'Foo'
}
</script>
<script type="text/javascript">
$(function() {
var x = JSON.parse($('#myJson').html());
alert(x.name); //Foo
});
</script>
... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.
You have a short list of options to load your JSON from a remote file:
Use $.get('your.json') or some other such AJAX method.
Write a file that sets a global variable to your json. (seems hokey).
Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this "1997 mode")
Consult a voodoo priest.
Final point:
Remote JSON Request after page loads is also not an option, in case you want to suggest that.
... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src=""> is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.
Another solution would be to make use of a server-side scripting language and to simply include json-data inline. Here's an example that uses PHP:
<script id="data" type="application/json"><?php include('stuff.json'); ?></script>
<script>
var jsonData = JSON.parse(document.getElementById('data').textContent)
</script>
The above example uses an extra script tag with type application/json. An even simpler solution is to include the JSON directly into the JavaScript:
<script>var jsonData = <?php include('stuff.json');?>;</script>
The advantage of the solution with the extra tag is that JavaScript code and JSON data are kept separated from each other.
It would appear this is not possible, or at least not supported.
From the HTML5 specification:
When used to include data blocks (as opposed to scripts), the data must be embedded inline, the format of the data must be given using the type attribute, the src attribute must not be specified, and the contents of the script element must conform to the requirements defined for the format used.
While it's not currently possible with the script tag, it is possible with an iframe if it's from the same domain.
<iframe
id="mySpecialId"
src="/my/link/to/some.json"
onload="(()=>{if(!window.jsonData){window.jsonData={}}try{window.jsonData[this.id]=JSON.parse(this.contentWindow.document.body.textContent.trim())}catch(e){console.warn(e)}this.remove();})();"
onerror="((err)=>console.warn(err))();"
style="display: none;"
></iframe>
To use the above, simply replace the id and src attribute with what you need. The id (which we'll assume in this situation is equal to mySpecialId) will be used to store the data in window.jsonData["mySpecialId"].
In other words, for every iframe that has an id and uses the onload script will have that data synchronously loaded into the window.jsonData object under the id specified.
I did this for fun and to show that it's "possible' but I do not recommend that it be used.
Here is an alternative that uses a callback instead.
<script>
function someCallback(data){
/** do something with data */
console.log(data);
}
function jsonOnLoad(callback){
const raw = this.contentWindow.document.body.textContent.trim();
try {
const data = JSON.parse(raw);
/** do something with data */
callback(data);
}catch(e){
console.warn(e.message);
}
this.remove();
}
</script>
<!-- I frame with src pointing to json file on server, onload we apply "this" to have the iframe context, display none as we don't want to show the iframe -->
<iframe src="your/link/to/some.json" onload="jsonOnLoad.apply(this, someCallback)" style="display: none;"></iframe>
Tested in chrome and should work in firefox. Unsure about IE or Safari.
I agree with Ben. You cannot load/import the simple JSON file.
But if you absolutely want to do that and have flexibility to update json file, you can
my-json.js
var myJSON = {
id: "12ws",
name: "smith"
}
index.html
<head>
<script src="my-json.js"></script>
</head>
<body onload="document.getElementById('json-holder').innerHTML = JSON.stringify(myJSON);">
<div id="json-holder"></div>
</body>
place something like this in your script file json-content.js
var mainjson = { your json data}
then call it from script tag
<script src="json-content.js"></script>
then you can use it in next script
<script>
console.log(mainjson)
</script>
Check this answer: https://stackoverflow.com/a/7346598/1764509
$.getJSON("test.json", function(json) {
console.log(json); // this will show the info it in firebug console
});
If you need to load JSON from another domain:
http://en.wikipedia.org/wiki/JSONP
However be aware of potential XSSI attacks:
https://www.scip.ch/en/?labs.20160414
If it's the same domain so just use Ajax.
Another alternative to use the exact json within javascript. As it is Javascript Object Notation you can just create your object directly with the json notation. If you store this in a .js file you can use the object in your application. This was a useful option for me when I had some static json data that I wanted to cache in a file separately from the rest of my app.
//Just hard code json directly within JS
//here I create an object CLC that represents the json!
$scope.CLC = {
"ContentLayouts": [
{
"ContentLayoutID": 1,
"ContentLayoutTitle": "Right",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/right.png",
"ContentLayoutIndex": 0,
"IsDefault": true
},
{
"ContentLayoutID": 2,
"ContentLayoutTitle": "Bottom",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/bottom.png",
"ContentLayoutIndex": 1,
"IsDefault": false
},
{
"ContentLayoutID": 3,
"ContentLayoutTitle": "Top",
"ContentLayoutImageUrl": "/Wasabi/Common/gfx/layout/top.png",
"ContentLayoutIndex": 2,
"IsDefault": false
}
]
};
While not being supported, there is an common alternative to get json into javascript. You state that "remote json request" it is not an option but you may want to consider it since it may be the best solution there is.
If the src attribute was supported, it would be doing a remote json request, so I don't see why you would want to avoid that while actively seeking to do it in an almost same fashion.
Solution :
<script>
async function loadJson(){
const res = await fetch('content.json');
const json = await res.json();
}
loadJson();
</script>
Advantages
allows caching, make sure your hosting/server sets that up properly
on chrome, after profiling using the performance tab, I noticed that it has the smallest CPU footprint compared to : inline JS, inline JSON, external JS.
I have a problem and hope you can help.
Ii have a status.PHP file containing a js.
STATUS.PHP
<? ..stuff... ?>
<html>
<head>
<title>BCM Status Page</title>
<script src="jquery-3.3.1.min.js"></script>
<script src="updater.js"></script>
</head>
<body bgcolor="#305c57" onload='init();'>
As you can see in the html ihave included a JS, during "onload" i'm calling the init() function of the javascript called updater.js
Now in the UPDATER.JS
function init() {
setInterval(read, 2000)
}
function read() {
$.ajax({
type: 'POST',
url: 'readDB.php',
dataType: 'jsonp',
success: function (data) {
console.log(data);
var json_obj = $.parseJSON(data);
console.log(json_obj[0].gwnumber);
},
error: function () {
console.log("Error loading data");
}
});
}
I'm doing an ajax call to the readDB.php that is working as intended, infact i have the correct value in the json_obj.
My question is: how can i get the json_obj value and pass it to the status.PHP file that is the one who's including the JS too?
Hope you can help. TY
Ok, there is a lot to say in this argument, but i will be the briefiest possible.
first things first
php and Javascript are two different programming language with a completely different paradigm.
The first is a back-end focused programming language;
Javascript instead is more front-end focused, just for entirety i have to mention that JS is used also for the backend part with a special eviroment called Node.js
back to the problem, the things that you are trying to do is not impossible but is excactly as you asked, your're idea (if i got it) was to pass the data from the js to the php like a parameter in a function...
the thing is that the php is elaborate and renderizated before in the server and the javascript is executed in the client, in the client web page there is no more footprint the php. This process is described very well at this link: http://php.net/manual/en/intro-whatis.php
The possible solution is:
FRONT-END(js): make another ajax call(request) to the same page that you are displaying with all the data that you want to elaborate.
BACK-END(php): controll if this request has been made, then access the data with the global variables $_POST & $_GET (depending on the type of the request), then elaborate this data.
if I can I suggest you to make a check if the manipulation that you want to do on those data need to be done in the server-side and not by the js!
Consider the order of execution:
User visits status.php
Browser requests status.php
Server executes status.php and sends response to browser
JS requests readDB.php
Browser requests readDB.php
Server executes readDB.php and sends response to browser
JS processes response
Go To 4
By the time you get to 7, it is too late to influence what happens at step 2.
You could make a new Ajax request to status.php and process the response in JS, but since status.php returns an entire HTML document, that doesn't make sense.
You could use location to load a new page using a URL that includes status.php and a query string with information from the Ajax response, but that would making using Ajax in the first place pointless.
You should probably change readDB.php to return *all** the data you need, and then using DOM methods (or jQuery wrappers around them) to modify the page the user is already looking at.
The simpliest and fastest (maybe not the sexiest way) to do it :
create global variable var respondData; in STATUS.PHP
within you ajax request on success function assign your data callback to it
respondData = data;
Now you have an access to it from every place in your code even when the ajax request is done. Just bare in mind to ensure you will try to access this variable after the page will fully load and after ajax will process the request. Otherwise you will get 'undefined'
I have an html5 web page that allows users to drag-n-drop objects between divs. After a user has moved objects around, I would like to save the current DOM to a file on my web server.
I know I can get the current HTML DOM using javascript but of course, I cannot save to a file on my server using javascript. So I thought about passing the html to a PHP page to do the "save" function, but I cannot figure out how to get the html passed to a PHP page. I've tried sending it as an argument in the URL with URI encoding, but the PHP page is not properly getting the entire string from the URL.
Should this approach work? If so, what am I missing to get the html string passed correctly to a PHP page? Or should I be using some other method?
ajax is the way to go here. If you are not familiar with ajax, please google it and learn it well. Any modern web app needs to have ajax integration in some way.
Here is how you can use javascript to communicate with the server.
Please Note I'm using JQuery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".draggableDivs").mouseup(function(event){
var documentStructure = ''; // whatever js you use to get document structure
var d = {"document_structure": documentStructure};
$.ajax({
url: "test.php", //Your url both relative and fixed path will work
type: "POST", // you need post not get because you are sending a lot of data
data: d,
success: function(response) {
alert('saved');
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
on the server you would then do your php and save the data.
After you are done you can just respond with a json object if needed, if not just exit
you can use the approach like
after the drag and drop with javascript, show a button to save the dom.
on click event on the button, take the current dom in a variable.
use ajax to transfer your current dom to a php file(ajax file).
in the ajax file , save it into database.
Hello again StackOverflow.
I've been tasked with modifying a website that runs on Scala's Play! framework and Twitter Bootstrap. I've hit a roadblock concerning altering the DOM. I need to accomplish the following:
(The page being talked about takes user input and passes the server a Form, which if
valid writes the mapped Data in the Form to a database.)
Have the user choose a category from a drop-down. This particular drop-down has nothing to do with the Form.
Based on their choice, query the database for all objects of a certain type that relate to the chosen category via a foreign key.
Alter the DOM (that is, show without reloading the page) to display those objects for the user to select them. Their selections are added to the Form.
Submit the Form, write to the database, etc.
Questions:
Is this a good way to go about what I'm trying to accomplish?
If so, is there a way to alter the DOM via Scala/Play HTML templates without reloading the page?
If that's not possible, what ilk of manually written Javascript is necessary?
Admissions:
I have very little experience with web development other than Play.
I have very little experience with Javascript.
Resources I've been looking at:
This SO post
Play docs on Javascript routing
Scala.js
Thank you!
For anyone who might come upon this in future, the short answer is Javascript.
Long answer:
To do any AJAX work, you'll need a method like the following in your top-level Controller to set up Javascript routing:
def javascriptRoutes = Action { implicit request =>
Ok(
Routes.javascriptRouter("jsRoutes")(
SomeOtherController.someMethod // Returns a JsValue!
)
).as("text/javascript")
}
Then in the HTML template (*.scala.html) which will contain some AJAXy Javascript:
<script type="text/javascript" src="#routes.ApplicationController.javascriptRoutes"></script>
And finally in your actual JS file (assuming you're using jQuery):
$("someSelector").click(function() {
// Notice that this matches the method name that exists in Scala!
// Make sure to pass `someMethod` what it needs.
var req = jsRoutes.controllers.SomeOtherController.someMethod(...)
$.ajax({
url: req.url,
type: req.type,
success: function(json) {
// DOM manipulation, etc., here.
},
error: function(xhr, status, errorThrown) {
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
}
}); // ajax
}); // handler
Really sorry if this is a dumb question but I can't seem to get this to work. As the title says i am trying to load an external js file and assign it to a variable as plain text. The project is a simple js "compiler" that stitches together a number of js files and minifies them into one. I am currently using the $.get() method and appending the response to a string.
The problem is that the js file that handles the above also needs to be included in the final minified file. I can load in all the other files and stitch them together just fine but when i load this main file into itself sourcing a js file it seems to evaluate and overwrite itself and so stops the process.
For the time being i have got around the problem by loading in a copy as a .txt file but it means i have to keep two files up to date which isn't ideal.
I found this article but it refers to javascript loaded via script tags in the head.
Any help would be appreciated. I will happily post code but not sure which bits would be useful.
Update: I probably should have mentioned that the project needs to run entirely client side so i can't use PHP/.NET pages. All the files I'm loading in are on the same domain though.
Try to use Ajax.get() :
var script;
$.get('script.js', function(data) {
script = data;
});
for Ajax.get() it will work inside your domain, you can't call external domains, if your application requires loading external JS file then my guess is that you have to use PHP or another server-side language as:
var script;
$.get('getScript.php', {url: "http://test.com/script.js"}function(data) {
script = data;
});
in getScript.php you can use CURL or file_get_contents
Note that $.get() and $.post() and $.ajax() are all the same thing.
$.get and $.post are just shorthand versions of $.ajax() that come with presets (obviously, type: "GET" and type:"POST" for one...). I prefer using $.ajax because the format can be more structured, and therefore easier to learn/use.
Javascript/jQuery would look something like this:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
url: "loadmyfile.php",
data: 'filename=js/myscript.js',
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
$('#myhiddentext').val(whatigot);
} //END success fn
}); //END $.ajax
}); //END $(document).ready()
</script>
Important: Note that you would need to do all the post-AJAX processing inside the success function. See this link for some simple AJAX examples.
Note that you can send data across to the PHP file by specifying a data: parameter in the AJAX code block. Optionally, you can leave out that line and simply hard-code the filename into the PHP file.
The text of the retrieved js file comes back into the AJAX success function (from the PHP file) as a string in the variable specified as the function param (in this case, called 'whatigot'). Do what you want with it; I have stored it inside a hidden <input> control in case you wish to retrieve the text OUTSIDE the AJAX success function.
PHP would look something like this:
loadmyfile.php
<?php
$fn = $_POST['filename'];
$thefile = file_get_contents($fn);
echo $thefile;
References:
PHP file_get_contents