Get text file contents using JQuery in an external file - javascript

I have an external javascript file that I want to use to collect the contents of a number of text files. JQuery .get() seems the most obvious choice. I can make this work if the JQuery is in the page, but not when the JQuery is in the external file. I'm missing something hugely simple...and I am currently mixing normal javascript with JQuery in the same file which I fear is poor form.
All files I am trying to access are within the same file structure. Currently I have the following in my external .js:
function addPanels() {
// eventually loop over list of local HTML files
// and do some stuff with the results...
fileContents = readHTMLFile();
}
jQuery(function($){
readHTMLFile = $.get('../html/test.html', function(data) {
alert('Loaded something');
return(data);
});
});
My HTML page contains the following:
<script type="text/javascript">
$(document).ready(function(){
addPanels();
});
</script>
Pretty sure this is a RTFM moment so direction towards the right manual/tutorial would be great!
Dan

The jQuery.get is a asynchronous function, with a callback that executes when the server returns the requested document. Therefore, you cannot return any data from the method.
function addPanels() {
// will not work
fileContents = readHTMLFile();
}
...
readHTMLFile = $.get('../html/test.html', function(data) {
// will not work
return(data);
});
This however, will work:
var addPanelCallback = function(html) {
// append html (or something like that)
alert(html);
};
var addPanel = function(url) {
$.get(url, addPanelCallback);
};
addPanel('../html/test1.html');
addPanel('../html/test2.html');
Example: http://jsfiddle.net/FgyHp/

In your script "readHTMLFile" is not known by function "addPanels", you should put them in same level.
This script should works
<script type="text/javascript">
(function($){
var readHTMLFile = function(url){
var toReturn;
$.ajax({
url: url,
async: false
}).done(function(data){
toReturn = data;
});
return toReturn;
};
$.addPanels = function(url){
fileContents = readHTMLFile(url);
};
})(jQuery);
</script>
And in your page you can call it like that:
<script type="text/javascript">
$(document).ready(function(){
$.addPanels('../test/test.html');
});
</script>

Related

implementation of global variables in an HTML document with Javascript tags of different types

The situation : I use a script (a) in an HTML document to be able to use a particular SDK. Then I use a second script (b) basic to be able to create a Kendo UI table.
My problem : I try to pass data from script (a) to script (b) via global variables but it doesn't work, what can I do?
Info that might help you:
my document is a form framed by tags
I use Camunda. The first script allows me to use the SDK to retrieve the ID of the instance associated with the form being processed. (but I don't think this is the crux of the problem)
I assume that both scripts are read at the same time by the browser, and that's why script (b) can't read the variable simply because it is not yet created in script (a).
The code :
<script type="text/javascript" src="http://localhost:8080/camunda/app/tasklist/scripts/kendo.all.min.js"></script>
<script cam-script type="text/form-script">
var taskService = camForm.client.resource('task');
var processInstanceId = null;
var result = null;
taskService.get(camForm.taskId, function(err, task) {
//alert(JSON.stringify(task));
debugger;
processInstanceId = task.processInstanceId;
$.get("http://localhost:8080/engine-rest/process-instance/"+processInstanceId+"/variables", function(result) {
debugger;
window.alert("coucou");
console.log(result.JsonWeightSetpoints.value);
});
debugger;
console.log(result.JsonWeightSetpoints.value);
debugger;
});
</script>
<script type="text/javascript">
console.log(result.JsonWeightSetpoints.value);
//this is where I implement the Kendo UI grid
</script>
<div id="grid"></div>
I cannot read the content of the result variable in script (b) because it is not defined.
How do I do this?
Custom events solution:
<script type="text/javascript" src="http://localhost:8080/camunda/app/tasklist/scripts/kendo.all.min.js"></script>
<script cam-script type="text/javascript">
var taskService = camForm.client.resource('task');
var processInstanceId = null;
var result = null;
taskService.get(camForm.taskId, function(err, task) {
//alert(JSON.stringify(task));
debugger;
processInstanceId = task.processInstanceId;
$.get("http://localhost:8080/engine-rest/process-instance/"+processInstanceId+"/variables", function(result) {
debugger;
window.alert("coucou");
console.log(result.JsonWeightSetpoints.value);
// the value is available here, we now can trigger an event and send it
document.dispatchEvent(new CustomEvent("handler", {
detail: { value: result.JsonWeightSetpoints.value }
}));
});
debugger;
console.log(result.JsonWeightSetpoints.value);
debugger;
});
</script>
<script type="text/javascript">
console.log(result.JsonWeightSetpoints.value);
//this is where I implement the Kendo UI grid
// event listener, this would get executed only when we want
document.addEventListener("handler", function(event) {
// write you logic here
console.log(event.detail.value);
});
</script>
<div id="grid"></div>
useful resources:
MDN: Creating and triggering
events
Introducing asynchronous JavaScript

How to load images from a directory using jquery

I am toying with the following code trying to take images from a set directory, and preload them. I do not want to load the images into a div, but rather preload them in the memory using the normal:
new Image().src = "/wp-content/themes/NCHERM_Theme/images/home4-events.jpg";
I am rather new to jquery so looking for some help to finalize this:
window.onload = function($) {
var folder = "images/preload";
$.ajax({
url : folder,
success: function (data) {
//go through each item in folder
$.each(data, function(i,filename) {
//take each item and run into the normal preload method
setTimeout(function() {
// preload images
new Image().src = filename;
}, 1000);
});
}
});
};
running this in wordpress I get `403 forbbiden' on the url for the folder before i can even test if this is working
Make sure you have added reference of JQuery inside your <script> tag. JQuery Library is missing.
<script src="../../jquery.min.js" type="text/javascript"></script>
For your reference: $.ajax is not a function
Try this code if it work for you.
window.onload = function($) {
var folder = "images/preload";
$.ajax({
url : folder,
success: function (data) {
//go through each item in folder
$.each(data, function(i,filename) {
//take each item and run into the normal preload method
setTimeout(function() {
// preload images
var $img=$("<img />",{"src":filename});
$('#target_id').append($img);
}, 1000);
});
}
});
};
You can solve 403 error by adding:
Options +Indexes
On .htaccess file.

why am I getting same quote from jsonp result

I have the following jquery code, that pulls json data from a url; however, it is giving me the same quote over and over, instead of random. If I use url directly on browser it does randomize the quote. What am I missing? Thanks
$(document).ready(function() {
$("#getMessage").on("click", function(){
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=", function(a) {
console.log(a[0].content + " " + a[0].title)
$("#quote-content").html(a[0].content)
$("#quote-title").html(a[0].title)
});
});
You can either turn off AJAX cache for jQuery, like this:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
//...
});
Or you could change the url for every request (so it doesn't get cached), something like this could work:
$(document).ready(function() {
$("#getMessage").on("click", function(){
$.getJSON("https://quotesondesign.com/wp-json/posts?filter[orderby]=rand&filter[posts_per_page]=1&callback=&"+new Date().getTime(), function(a) {
//...
});
});
});
Also, I don't think you need the callback= parameter

Class is undefined in IE8

I have stupidly decided to support IE8 in my latest project, something which will no doubt go down in history as the dumbest idea of my life.
So the most fundamental problem I'm running into is that my main class variable is undefined. What I mean is I have a prototype set up in a file general.js that looks a bit like this:
var generalClass;
// jQuery Object
var $ = jQuery;
$(document).ready(function() {
// A general class for a general file.
generalClass = function() {
}
generalClass.prototype = {
}
new generalClass();
});
So the generalClass variable is filled up with my prototype/etc. I then include this in the head of my document and later on I call upon a function in that generalClass for something else, a bit like this:
<script type="text/javascript" src="general.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: ...,
data: {
},
success : function(data) {
// CALL MY FUNCTION:
generalClass.prototype.myFunction();
}
}
});
</script>
In every browser, from IE9 to Chrome this works. In IE8 this does not work, and generalClass is undefined. Why is it doing this to me?
I am not sure where you learned that pattern, but it should be more like this:
var generalClass;
// jQuery Object
//var $ = jQuery; <-- makes no sense $ should be jQuery already
$(document).ready(function() {
function GeneralClass() {}
GeneralClass.prototype = {
myFunction: function () {
alert("x");
}
};
generalClass = new GeneralClass();
});
and when you call it
generalClass.myFunction();

Organize JS code in MVC app

I have several JS code in several partials Views.
I think it would be good idea to put all these code in separated JS file to separate JS code from HTML code.
But how do you deal with MVC code inside JS?
The example below is JS code which I have in partial View. I would like to put in into JS file but the JS code has MVC code #Url.Action("ResultForm", "File") and it will not be executed in JS file.
Any suggestion?
Javascript Code
<script type="text/javascript">
var varTimerSpeed = 5000;
var varTimerInterval;
var onlyOneInstance = false;
startTimer();
function startTimer() {
onlyOneInstance = false;
varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
}
function loadResultForm() {
if (onlyOneInstance) return;
clearInterval(varTimerInterval);
onlyOneInstance = true;
$.ajax({
url: '#Url.Action("ResultForm", "File")',
data: '',
dataType: 'html',
success: function (data) {
$('#ResultForm').html(data);
startTimer();
}
});
};
</script>
I am assuming using a Razor partial for only the js code is not an option. In that case you could use this approach:
in your view.cshtml
<script type="text/javascript">
var Namespace.urlForModule = '#Url.Action("ResultForm", "File")';
</script>
<script type="text/javascript" src="customScript.js"></script>
in you customScript.js
$.ajax({
url: Namespace.urlForModule,
})
The idea is to separate out the Asp.Net MVC specific code from the js code.
The way you want to do that is upto you. As some one else suggested, you could attach data-* attributes to some div and read those. I prefer this, as it expresses my intent clearly.
A solution would be to create a meta tag or a data-* attribute with the desired dynamic value and catch it with JavaScript. This way you can separate the code entirely with minor changes.
You can add hidden field with url:
// View:
#Html.Hidden("LoadResultFormUrl", #Url.Action("ResultForm", "File"))
// js-file
function loadResultForm() {
url = $("#LoadResultFormUrl").val();
...
};
why dont you just create a partial view which contains nothing but js code
and do a renderpartial instead of adding a script tag?
Create a file "somescript.js" and put the code inside a unique public function, extract hard-coded external dependencies and replace them for parameters.
var startXyz = function(resultFormUrl) {
var varTimerSpeed = 5000;
var varTimerInterval;
var onlyOneInstance = false;
startTimer();
function startTimer() {
onlyOneInstance = false;
varTimerInterval = setInterval(loadResultForm, varTimerSpeed);
}
function loadResultForm() {
if (onlyOneInstance) return;
clearInterval(varTimerInterval);
onlyOneInstance = true;
$.ajax({
url: resultFromUrl,
data: '',
dataType: 'html',
success: function (data) {
$('#ResultForm').html(data);
startTimer();
}
});
};
};
Then, in your page you do:
<script>
$(function(){
startXyz('#Url.Action("ResultForm", "File")');
});
</script>
Now you have a modular function that will startup your page/partial and a script file that do not depends directly from server state and can be reused on the same or another page.
This approach is especially useful if a partial view is rendered more than once per page.

Categories