Issue Storing File Paths in Javascript Array from C# - javascript

I am trying to store all of file paths from a string array in C# into a Javascript array and it works and stores them all in the array but the path's slashes are removed so the file path doesn't read as normal and produces an error. The file path is shown in the following and as you can see in the end of the path everything collides together because the slashes disappear.:
If the slashes were in there then the file path should be able to be read in my code sample I will include which I have tested with file paths. I was just wondering how to, in my code, have the slashes retained in javascript.
What my code does is pass in an array of strings seperated by a semicolon from c# razor code in MVC and then puts each one in an array in Javascript and this is where it strips the slashes. Then the image is displayed using URL.Content and the file path.
ANY HELP IS APPRECIATED!
Code
<!DOCTYPE html>
<html>
<head>
#model Tuple
<string, string[]>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>My ASP.NET Application</title>
<script src="//code.jquery.com/jquery-2.1.1.min.js" type="text/javascript"></script>
</head>
<body>
<div style="width:800px;height:400px;border:3px solid #000;margin:0
auto;margin-top:70px;position:relative;">
<img src="" style="width:100%;height:100%;" id="img" />
<p style="position:absolute;top:45%;font-
size:22px;color:#fff;left:10px;cursor:pointer;" id="left">
< </p>
<p style="position:absolute;top:45%;font-
size:22px;color:#fff;right:10px;cursor:pointer;" id="right">></p>
</div>
</body>
</html>
<script type="text/javascript">
var arr = [];
var first = "#Model.Item1";
counter = 0;
#foreach(string i in Model.Item2) {
<
text > arr.push("#i") < /text>
}
$('#right').click(function() {
if (counter == 0) {
} else {
counter--;
}
});
$('#left').click(function() {
if (counter == 0) {
} else {
counter--;
}
});
var image = document.getElementById("img");
image.src = "#Url.Content("~/Practice/Images / ")" + arr[0];
</script>

There is problem with the way you populate the arr object. Somehow javascript escape sequence removes the slashes. Remove this #foreach(string i in Model.Item2) loop and You can directly assign value to arr as below.
var arr = #Html.Raw(Json.Encode(Model.Item2));

Related

when i try to access array element by index it gives me undefined

i created an array and insert elements by array.push(). when i console.log(array) it gives me following out put output of console.log(array)
when i console.log(array[0]) it gives me undefined. why is happing and a blue i tag appear in picture which says "this value was evaluated on first expanding it may have changed since then in array javascript" what does means. please help me to understand the problem
here the full code
index.html =>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>zip reader</title>
</head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script type="text/javascript" charset="utf8" src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.3.3/jstree.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
<body>
<h3>Choose the local(s) zip file(s)</h3>
<input type="file" id="file" name="file" multiple /><br />
<div id="result_block" class="hidden">
<h3>Content :</h3>
<div id="result">
</div>
</div>
</body>
<script src="jszip.min.js"></script>
<script src="jszip-utils.min.js"></script>
<script src="app1.js"></script>
<script src="FileSaver.min.js"></script>
</html>
app1.js =>
var array = []
var contents = []
var $result = $("#result");
$("#file").on("change", function(evt) {
// remove content
$result.html("");
// be sure to show the results
$("#result_block").removeClass("hidden").addClass("show");
// Closure to capture the file information.
function handleFile(f) {
var $title = $("<h4>", {
text : f.name
});
var $fileContent = $("<ul>");
$result.append($title);
$result.append($fileContent);
var dateBefore = new Date();
JSZip.loadAsync(f) // 1) read the Blob
.then(function(zip) {
var dateAfter = new Date();
$title.append($("<span>", {
"class": "small",
text:" (loaded in " + (dateAfter - dateBefore) + "ms)"
}));
zip.forEach( function (relativePath, zipEntry) {
var y = zipEntry.name
array.push(y);
$fileContent.append($("<li>", {
text : zipEntry.name
}));
});
}, function (e) {
$result.append($("<div>", {
"class" : "alert alert-danger",
text : "Error reading " + f.name + ": " + e.message
}));
});
}
var files = evt.target.files;
for (var i = 0; i < files.length; i++) {
handleFile(files[i]);
}
console.log(array[0])
});
When you console.log an object (including arrays), it isn't being serialized, and only a reference is passed to a console. When you expand it, this reference is used to check the state of this object.
Most probably what's happening is the following sequence:
console.log(array) // passes array reference to a console
console.log(array[0]) // prints undefined immediately
array.push(...) // an actual array modification
you expand the object, and console checks the content of an array
PS.
It's reasonable to ask, what will happen, if the reference will become invalid due to any reason.
For browsers - it's simpler, since the console and JS program run under same parent process, browser is responsible for everything.
But if you'll ever try to debug Node process, which has the same API of passing the reference, you will face strange issues all over around, like this one: No debug adapter, can not send 'variables VSCODE

Creating a GET request to display images from JSON file

I'm new to Javascript and have been spinning on writing this piece of code in order to display a series of pictures on a page from an external source, sort of like an instagram feed, using a GET request through jQuery. I have been given a JSON file that contains an array of image URLs, some of which I want to exclude because they are broken.
Here is the code that I've written thus far - I've tested it and it doesn't work and I'm looking for some guidance on what aspects I may be missing in order to get my code to work:
$(document).ready(function () {
$('imagesFromJSON').click(function () {
$.getJSON("images.json", function (data) {
var arrItems = []; // The array to store JSON items.
$.each(data, function (index, value) {
arrItems.push(value); // Push values in the array.
});
for (let i = 0; i < arrItems.length; i++) {
if (arrItems[i].contains('fakeurl') === false) {
let img = document.createElement('img');
img.src = arrItems[i].Image
document.querySelector('.container').appendChild(image)
}
}
});
});
});
<html>
<head>
<meta charset="UTF-8">
<title>Feed Test</title>
<script type='text/javascript' src='feed.js'></script>
<script src="jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>FEED TEST</h1>
<p><input type="button" id= "imagesFromJSON" value="Show Images" /></p>
<div class="container"></div>
</body>
</html>

Having trouble parsing json file in my javascript..but I am getting "responseObject.weather[i].weatherresponseObject.weather[i].description"

Trying to parse data from a php file which is in json format to an html file using javascript to do so
I am getting responseObject.weather[i].weatherresponseObject.weather[i].description but I have a hunch its how the php file is formatted and perhaps the object I am using is not correct
I am trying to just pull the temperature and the description onto my html page.
Can someone give me a idea of where it is going wrong?
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="style.css" rel="stylesheet" type="text/css">
<script src="run.js"></script>
<title>Ajax Demo</title>
</head>
<body>
<h1 class="title">Todays Weather Forecast</h1>
<p class="sub">Click the button the check the local weather.</p>
<button class="demo-centered" type="button" onclick="loadPhp()">Check Weather</button><br><br>
<div id="content"></p>
</body>
</html>
function loadPhp() {
var xhr = new XMLHttpRequest();
xhr.onload = function() {
if (xhr.status === 200) {
responseObject = JSON.parse(xhr.responseText);
var newContent = '';
for (var i = 0; i < responseObject.weather.length; i++){
newContent += 'responseObject.weather[i].weather';
newContent += 'responseObject.weather[i].description';
}
document.getElementById('content').innerHTML = newContent;
}
};
xhr.open('GET', 'demo.php', true);
xhr.send(null);
}
{"coord":{"lon":-116.8,"lat":33.03},"weather":[{"id":802,"main":"Clouds","description":"scattered clouds","icon":"03d"}],"base":"stations","main":{"temp":293.73,"feels_like":289.89,"temp_min":289.26,"temp_max":295.93,"pressure":1016,"humidity":52},"visibility":16093,"wind":{"speed":5.7,"deg":260},"clouds":{"all":40},"dt":1589408840,"sys":{"type":1,"id":5686,"country":"US","sunrise":1589374130,"sunset":1589423903},"timezone":-25200,"id":5391832,"name":"San Diego County","cod":200}
You don't want the quotes in this code:
newContent += 'responseObject.weather[i].weather';
newContent += 'responseObject.weather[i].description';
With the quotes, you're making those literal strings. Instead:
newContent += responseObject.weather[i].weather;
newContent += responseObject.weather[i].description;
...though you probably want some markup around those, as they'll just be stuck together.
Three other things worth noting:
You never do anything with newContent. You need to do something to put it on the page (append elements with it, append it to existing elements, etc.).
Your code is falling prey to what I call The Horror of Implicit Globals — you need to declare responseObject.
It's fine to use XMLHttpRequest, but you might also look at the newer fetch instead. If you do, though, beware the fetch footgun.

how to create a dynamic array in javascript based on the number of files in same directory

I have a static page, which I'm using for viewing pictures, and the javascript does the slide show; however, I would like to dump the pictures in same directory and when page is opened, the javascript will create an array with all the pictures without me having to edit the array for every scenario.... is this possible?... I know javascript has some security restrains when it comes to read from local filesystem. here's the static page and javascript
<!doctype html>
<html lang="en">
<head>
<title>Picture Show</title>
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
<script type="text/javascript" src="slideshow.js"></script>
</head>
<body>
<!-- Insert your content here -->
<div id="container">
<div id="header">
<h1>Slide Show</h1>
<a id="link" href="javascript:slideShow()"></a>
</div>
<div id="slideShow">
<img name="image" alt="Slide Show" src="pics/0.jpg" />
</div>
</div>
</body>
</html>
javascript
//javascript code for slideshow
//pictures
var imgs = [ "pics\/0.jpg", "pics\/1.jpg", "pics\/2.jpg", "pics\/3.jpg", "pics\/4.jpg", "pics\/5.jpg" ];
var imgNum = 0;
var imgsLength = imgs.length-1;
var time = 0;
//changing images function
function changeImg(n) {
imgNum += n;
//last position of array
if (imgNum > imgsLength) {
imgNum = 0;
}
//first position of array
if (imgNum < 0) {
imgNum = imgsLength;
}
//console.log(images.tagName);
document.image.src = imgs[imgNum];
return false;
}
//slideshow function
function slideShow() {
var tag = document.getElementById('link').innerHTML;
if(tag == "Stop") {
clearInterval(time); //stoping slideshow
document.getElementById('link').innerHTML = "Start";
document.getElementById('link').style.background = "yellow";
}
else { //all other cases come here
time = setInterval("changeImg(1)", 4000);
document.getElementById('link').innerHTML = "Stop";
document.getElementById('link').style.background = "green";
}
}
window.addEventListener('load', slideShow);
It's not possible to automatically read a directory with in-browser javascript because of security issues. You have two options here:
Make a multiple file input and let the user select the images to display. He could just use "ctrl+a" inside a directory to select everything ... of course this is bad cuz it requires a file select for every slideshow.
or...
Make a server side application that will upload the files or a list with their path. This will do the trick just the way you want, but the application must be installed and running on the machine in order to work. This could be easily achieved with nodejs and I bet you will find a module that will help you.

Send javascript array to php array after loading and redirect user

I would like to redirect a user to a php page containing a form field after the user has viewed the three numbers after each other. I would like to also pass the index array to a php array for processing and storage.
Here's the code so far:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="keywords" content="">
<meta name="description" content="">
<title>Digit Span Backward</title>
<script src="jquery.min.js" type="text/javascript">
</script>
</head>
<body>
<p>Digit Span Backward - Javascript edition</p>
<script type="text/javascript" language="javascript">
function randomize(number)
{
var index = [];
for (var i = 0; i < number; i++)
{
index.push(Math.floor(Math.random()*10));
}
return index;
}
function showMessage(message)
{
$('p').html(message);
}
var i = 0;
function shuffle(list, i)
{
if (!(i >= 0))
{
i = 0;
}
setTimeout((function(msg)
{
i++;
return function()
{
if(i < list.length)
{
shuffle(list, i);
}
showMessage(msg);
}
})(list[i]), 1000);
}
</script>
<form>
<input type="button" onclick="shuffle(randomize(3))" value="Start Digit Span Backward">
</form>
</body>
</html>
Any ideas?
i am not a HTML 5 geek or a php professional but here is my suggestion
Can i suggest putting a hidden field in the page and then use the join method of the array to convert it to string splitted by what ever choice splitter like , and then set it to the hidden field value and pass it to the next page just give it a name
Example
JavaScript Function
function ArrayToStringSplitted(ary,splitter,hiddenfield)
{
var aryString= ary.join(spliter);
hiddenfield.value = aryString ;
}
HTML
just add the Hidden Field to the page
<input type='hidden' id="hdfld" name="hdfld" />
i think this will not work with the normal javascript redirection window.location = path
i think this will work with setting the form attributes the action to the location of the php page and the method to post
in there in the php page you can catch the hiddenfield value with $hiddenfield name and split it with the same splitter to return it to a array again
regards

Categories