My App reads txt files even if they are deleted - javascript

I have developed an app that reads some data from a txt file.
jQuery.get('/mnt/sdcard/koinoxrista/File.txt',
function(data){
//do something
}
The strange thing is that since yesterday, even if I delete the txt file, my app still reads it...
The problem does not exist if I remove and reinstall my app.
How can I solve this issue?

Try to disable cache (docs)
jQuery.ajax({
url: '/mnt/sdcard/koinoxrista/File.txt',
cache: false,
success: function(data) {
//do something
}
});

It is stored in your app's cache memory every time you execute jQuery.get

Related

JSON call giving value that is not actually in the .json file

I am a little new when it comes to JSON and Javascript , so please excuse me if if this is a stupid question, but I have run into a problem that is starting to drive me insane.
On a webpage I am including two scripts; jQuery and a file called "scripts2.js". In the same directory as scripts2.js, I have a JSON file; "settings.json". From within my "scripts2.js" file I am running he following code inside of a function.
var settingsPath = settings.json;
jQuery.getJSON(settingsPath, function (data){
jQuery.each(data, function(index){
console.log("!"+data[index].name);
/*unrelated other stuff */
});
});
Previously the settings.json file looked like this
[
{"name":"Standard Black"},
{"name":"Gold"},
{"name":"Silver"}
]
So naturally when I looked in the Chrome Dev Console the log would print out
!Standard Black
!Gold
!Silver
However, when testing what would happen upon editing my settings.json file I changed "name":"Gold" to "name":"Test".
[
{"name":"Standard Black"},
{"name":"Test"},
{"name":"Silver"}
]
After the json updates I tried refreshing the page but my console log is still printing out
!Standard Black
!Gold
!Silver
...
I am at a loss. I have no idea why the data being retrieved with jQuery.getJSON() is sending the data of my old settings.json even after the changes has been saved. I have perused my .php file (which is generating the HTML) , as well as my included javascript and there is no other mention of another json file or any sort of clone of my json file in any related directory.
I really have no idea what is going on and I am starting to go insane. Does anyone have an idea of what the issue might be?
I dont know if it matters but I am running a XAMPP stack on my localhost. All files (index.php, scripts2.js, and settings.json) are in a directory located inside XAMPP's htdocs folder.
EDIT: Thank you all for the speedy and thorough answers, many of you answered the question I was a bout to ask next. I really appreciate it!
This is because the browser is caching the file from your first request. Simply clear the cache and run it again and the new data will be retrieved.
UPDATE:
To prevent the browser from caching this file, change your AJAX settings like so:
jQuery.ajaxSetup({ cache: false });
Before you make the getJSON call
Try clearing web cache and restart local servers if you have not already
When using jQuery.ajax() instead of the shorthand method, you can disable caching like this:
jQuery.ajax(settingsPath, {cache: false})
jQuery will append a timestamp parameter to your request URL which changes with every request and therefore keeps the browser from caching the response.
To force the browser to get a new version each time you can use cache: false in jQuery.ajax()
$.ajax({
dataType: "json",
url: settingsPath,
cache: false,
success: function (data){
$.each(data, function(index){
console.log("!"+data[index].name);
});
}
});
Pass additional parameter to your requested url which value will change with every request.So,your browser will consider it as new request every time and will not cache the data.
var random = Math.round(new Date().getTime())
var settingsPath = 'settings.json&time=' + random;
jQuery.getJSON(settingsPath, function(data) {
});
});
You can use any algoritham that generate random new value everytime for random for every request.
OR
you can have same things with jQuery#Ajax method
jQuery.getJSON is a shorthand Ajax function, which is equivalent to:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
So, set the optional parameter cache to false (this value by default is always true):
$.ajax({
dataType: "json",
url: url,
data: data,
cache: false, // If set to false, it will force requested pages not to be cached by the browser
success: success
});
Therefore, your getJson becomes:
var settingsPath = settings.json;
jQuery.ajax({
dataType: "json",
url: settingsPath,
data: data,
cache: false,
success: function(data) {
jQuery.each(data, function (index) {
console.log("!" + data[index].name);
/*unrelated other stuff */
});
}
});

How to get a JSON string result from a database for later use

I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.

Reading a CSV file with jQuery

I have a downloaded CSV file which I would like to parse and use to create JSON objects for each record. The file is on my local machine but I have read that JavaScript has security measures in place that prevent access to these files.
Some examples show using csv.js with the following:
$.ajax({
url: "G:\downloaded_files\filename.csv",
aync: false,
success: function (csvd) {
csv_as_array = $.csv.toArrays(csvd);
},
dataType: "text",
complete: function () {
// use the array of arrays (variable csv_as_array)
// for further processing
}
});
When running this it just creates a GET request in the console. I am treading on unfamiliar territory here so any explanations would be great.
If I was to do this using Ruby I would do this, which hopefully will give you an indication of what I am trying to achieve:
require 'csv'
class FileRead
csv_text = File.read('/home/richardlewis/Downloads/csvtest.csv')
csv = CSV.parse(csv_text, headers: true)
csv.each do |row|
hash = row.to_hash
puts(hash)
end
end
I'm hoping this makes sense and someone can point me in the right direction.
You cannot call local files (from hard dics) using Ajax, or by any means from a web browser. You will have to publish your file using some sort of server. If you are using Linux you should have an Apache server already installed.
You need a REST service that will return your file in some format. JSON is the best, because it's easy to manipulate JSON data on the front-end.
It would look like this:
$.ajax({
url: "http://localhost:8080/services/rest/get_file", // your rest address
...
});

How to clear the cache for JSON

I'm reading a JSON file with jQuery. If I update the file that .get() reads it still gets the old values when I read the newer file. Since I write and read the file every second, how can I solve this problem? Manually clearing the cache won't be a option.
function readEye() {
$.getJSON('output.json', function(data){
console.log(data);
});
}
use $.ajaxSetup settings
$.ajaxSetup({
cache:false
});
after that you can use your code like
function readEye() {
$.getJSON('output.json', function(data){
console.log(data);
});
}

Updating or Removing a JSON file

I am creating a Phonegap app which loads in information from vimeo using JSONp. I want to know if there is a way of creating a button that updates the feed either live or when a button is clicked. I have research all over for this answer but are yet to find an answer
I have be able to create a button that just runs the JSON request again, but this leads to there being duplicates of the JSON file in the DOM. So this leads me to my next question which is, is there a way to delete/remove an unwanted JSON file? This way I could add the new one and remove the old, hey presto JSON refreshed.
$('#jqt .info').click(function() {
refreshJSON();
});
function refreshJSON() {
//Vimeo .GET
$.ajax({
url: 'http://vimeo.com/api/v2/album/1751209/videos.json?callback=?',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data){
gotMeSomeJSON(data);
},
error: function(){
alert('Sorry unable to download data. You need a good wifi connection to run this app.');
}
});
In principle, to remove a js reference all you need to do is target it and use remove child, something like this for example:
var s = document.getElementsByTagName('script')[0]; //target the right one
s.parentNode.removeChild(s);

Categories

Resources