Access a file with javascript - javascript

I have seen several examples of how to load a file with javascript, however most of those examples use the data from the file to display it in a html.
I need to keep accessing a file since the file keeps updating and use those values in javascript as variables.
I got the closest with this,
function test() {
$().ready(function(){
var url = 'output.txt';
$.get(url, function(data) {
// can use 'data' in here...
console.log(data);
});
});
}
It logs document to the console and I can collapse that.
There is really a lot of stuff (to much to list here). I only don't know in what kind of format it needs the data to be or how to access it. I do see stuff about xml-stylesheet, so can i even use this?
Changing the way I write the file is no problem for me.

I suggest using a JSON file. For example:
{
username: "Rocket",
realname: "Eric",
age: 23
}
To read this, you can use jQuery's $.getJSON method.
$.getJSON('/path/to/your/file.json', function(data){
var username = data.username;
});
You can also use XML, though I suggest using JSON (it's easier to get the data from it).
<?xml version="1.0" encoding="UTF-8" ?>
<item> <!-- XML needs a root element -->
<username>Rocket</username>
<realname>Eric</realname>
<age>23</age>
</item>
jQuery doesn't have a $.getXML method, so we have to use $.get.
$.get('/path/to/your/file.xml', function(data){
var username = $('item', data).find('username').text();
}, 'xml');

Try using the Jquery GetJson method: Something like this. May need some tweaking.
$.ajax({
url: 'http://www.yourfile.html',
dataType: 'json',
data: data,
success: function(data){
$('#yourdiv').html(data);
}
});

Related

Getting json data from url instead of local

I have a searchbox that is working with a local Json data (in the same file) using a var but now I would like to use with an external url json file in the same way that it works before.
What I have now:
var data1 = [{"test_id":"1","test":"test","test2":"test2"}];
What I'm trying:
var data = $.ajax({
dataType: "json",
url: 'myjsonurl',
data: data
});
I've tried with getJSON and with other some recommendations but are not working as I expect, in the image you can see that I'm having the data in both ways but quite different and is not working in the searchbox.
Image: https://i.stack.imgur.com/kWKkz.png
You can find the searchbox here:
https://www.js-tutorials.com/javascript-tutorial/live-search-json-objects-data-using-jquery/
Is there any idea to get same data as I have now from an external file and use it into a var as the searchbox do?
Any ideas?
Thanks in advance,
The way you are doing is, what you are getting is XHR Object.
To get proper JSON response and to work on it, you can write a success function and handle response data there or just use getJSON.
For example:
$.getJSON('https://gist.githubusercontent.com/GeekAb/027c70bd21d006027cd91f538ae4694e/raw/68fda14df1b9fbf6835a02639aa210e88826d19d/SampleJSON',
function( data ) {
console.log(data);
console.log(data[0]);
console.log(data[0]['employee_age']);
});
You can check this Bin link https://jsbin.com/cixezewisi/edit?html,js,console
First off, you have a lot of options when it comes to importing data from an external file (some easier than others). The following list is from another stackoverflow post:
ES6 import
Node.js Require
Ajax
jQuery
I suggest checking out the link, as the poster gave great detail on these options.
Anyways, it looks like you are trying to implement this with Ajax. You basically got it down correctly. Based off the image, what your issue is that using ajax has stringified your data, which is expected. All you have to do is:
var data = $.ajax({
dataType: "json",
url: 'myjsonurl'
});
var parsedData = JSON.parse(data)
This will parse your data into the JS array you are looking for.

Assign entire file to a var as a string using jquery

I'm trying to assign the contents of an xml file to a var, like so:
var testing = $.load('xx.xml');
$('#display').text(testing);
but it's not working. I tried the ".load" function as suggested in:
How to assign file contents into a Javascript var
and I had a look at the page they suggest form the jquery website, but I can't find something specific to assigning the contents of the .xml file to the var as a string.
I appreciate this is probably very obvious & I am arguably being lazy, but I have been trying random things for a while & cannot figure this out.
Thanks
EDIT! I was loading up the contents inside the load function, i didn't mean this, it's now edited.
Firstly, $.load isn't a defined function in the latest jQuery source, nor is it documented on the jQuery site.
Secondly, assuming you haven't modified jQuery's global AJAX settings, jQuery.fn.load and other request functions will be asynchronous, so you can't just assign the result to a variable because the function returns before the request has completed. You need to use callback handlers.
Try using $.ajax with a callback function instead:
var testing;
$.ajax('xx.xml', {
dataType: 'text',
success: function (data) {
testing = data;
$('#display').text(testing);
}
});
Since you want the data as text and the file appears to be XML, we're using dataType to tell jQuery to return the data as a string.
There is no $.load function. What you probably want is jQuery.get:
var xml;
$.get("xx.xml", function(data) {
xml = data;
});
As the file is retreived asynchronously, you need to assign the result to the variable inside the callback, which is executed when the request returns successfully. Note however that if you try and run code that depends on xml after the .get call, xml is going to be undefined because the callback won't have run yet. For example:
var xml;
$.get("xx.xml", function(data) {
xml = data;
//Do stuff with data here
});
console.log(xml); //Most likely undefined because asynchronous call has not completed
If you are trying to insert the results into a DOM element, then you can use the .load method:
$("#someElem").load("xx.xml");
if you are trying to get an xml from your server using ajax, you may try something like this -
function getXml()
{
var contents;
$.ajax({ url :'/website/method', type: 'GET', dataType :'xml', async : false,
cache : true, success : function(myXml){
contents = myXml;
}
});
return contents;
}

How do I auto-update an array in JQuery?

I am trying to add an item to the end of an array, kind of like an arraylist. I tried using the .push() but I can't get it working correctly reading from my xml. How could I "auto" update the array in jquery? (append to the end of it if you want to think of it that way)
Here is what my jquery looks like at the moment.
images = new Array();
$.ajax({
type: "GET",
url: strXMLURL,
dataType: "xml",
success: function(xml) {
$(xml).find("image").each(function() {
images.push($(this).attr("src"));
});
},
error: function() {
alert("Error reading the XML");
}
});
xml
<?xml version="1.0" encoding="utf-8" ?>
<gallery>
<image src="images/gallery/gallery1.jpg"/>
</gallery>
If you need any more information, I'll happily provide more.
Declare the images array inside the success function of the ajax call to ensure the scope remains correct then your function should work...

Parsing XML in Javascript getElementsByTagName not working

I am trying to parse the following XML with javascript:
<?xml version='1.0' encoding='UTF-8'?>
<ResultSet>
<Result>
<URL>www.asd.com</URL>
<Value>10500</Value>
</Result>
</ResultSet>
The XML is generated by a PHP script to get how many pages are indexed in Bing.
My javascript function is as follows:
function bingIndexedPages() {
ws_url = "http://archreport.epiphanydev2.co.uk/worker.php?query=bingindexed&domain="+$('#hidden_the_domain').val();
$.ajax({
type: "GET",
url: ws_url,
dataType: "xml",
success: function(xmlIn){
alert('success');
result = xmlIn.getElementsByTagName("Result");
$('#tb_actualvsindexedbing_indexed').val($(result.getElementsByTagName("Value")).text());
$('#img_actualvsindexedbing_worked').attr("src","/images/worked.jpg");
},
error: function() {$('#img_actualvsindexedbing_worked').attr("src","/images/failed.jpg");}
});
}
The problem I'm having is firebug is saying: 'result.getElementsByTagName is not a function'
Can you see what is going wrong?
Thanks
I actually just fixed it, what I was doing wrong was when I was trying to set the value of '#tb_actualvsindexedbing_indexed' I was not telling it to use the first entry of the xml, and was just passing it the entire object.
$('#tb_actualvsindexedbing_indexed').val($(result[0].getElementsByTagName("Value")).text());
Thanks for the help anyway.
result = xmlIn.getElementsByTagName("Result")[0];
$('#tb_actualvsindexedbing_indexed').val($(result.getElementsByTagName("Value")[0]).text());
element = element; elements = array of elements

How do I get the entire XML string from a XMLDocument returned by jQuery (cross browser)?

I have tried and failed to find out how to get the entire XML string from the XMLDocument returned by a GET. There are a lot of questions on SO on how to find or replace specific elements in the object, but I can't seem to find any answer to how to get the entire document as a string.
The example I'm working with is from here. The "do something with xml"-part is where I'm at at the moment. I get the feeling that this should be really trivial, but I fail to find out how. Is there an "xml.data()" or similar that can be used for this purpose?
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'xml',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
The use case is that I want to feed the xml to flash plugin and for that I need the actual XML as a string.
If you want both, get the response as XML Document and as string. You should be able to do
success: function(data){
//data.xml check for IE
var xmlstr = data.xml ? data.xml : (new XMLSerializer()).serializeToString(data);
alert(xmlstr);
}
If you want it as string why do you specify dataType:xml wouldn't then dataType:text be more appropriate?
I need the actual XML as a string
You want it as plain text instead of XML object? Change dataType from 'xml' to 'text'. See the $.ajax documentation for more options.
You can also easily convert an xml object to a string, in your java script:
var xmlString = (new XMLSerializer()).serializeToString(xml);
If you only need a string representing the xml returned from jquery, just set your datatype to "text" rather than trying to parse the xml back into text. The following should just give you raw text back from your ajax call:
$.ajax({
url: 'document.xml',
type: 'GET',
dataType: 'text',
timeout: 1000,
error: function(){
alert('Error loading XML document');
},
success: function(xml){
// do something with xml
}
});
Although this question has already been answered, I wanted to point out a caveat: When retrieving XML using jQuery with Internet Explorer, you MUST specify content-type to be "text/xml" (or "application/xml") or else you will not be able to parse the data as if it were XML using jQuery.
You may be thinking that this is an obvious thing but it caught me when using Mozilla/Chrome/Opera instead of IE. When retrieving a "string" of XML with a content-type of "text", all browsers except IE will still allow you to parse that data (using jQuery selectors) as if it were XML. IE will not throw an error and will simply not return any results to a jQuery selection statement.
So, in your example, as long as you only need the string-serialized version of the XML and will not expect jQuery to do any sort of selection on the XML DOM, you can set the content-type to "text". But if you ALSO need to parse the XML with jQuery, you will need to write a custom routine that serializes the XML into a string for you, or else retrieve a version of the XML with content-type "xml".
Hope that helps someone :)
You can get the native XMLHttpRequest object used in the request.
At the time i'm posting this answer, jQuery docs state a few ways to do so.
One of them is via the third argument of the success callback:
success: function(xml, status, xhr){
console.log(arguments);
console.log(xhr.responseXML, xhr.responseText);
console.log('Finished!');
}
For a complete example:
https://jsfiddle.net/44m09r2z/

Categories