Local host interrupts data read with getJSON - javascript

I've saved a JSON file in my local direcotry. The current path is "application/data/file.json". I'm using getJSON to read this file but I keep getting an error saying "jquery-3.6.0.js:10109 GET http://127.0.0.1/data/history.json 404 (NOT FOUND)".
I'm trying to get the data from the json file as a part of building web application. In the html script, I set something like this and I wonder if the host url is interrupting the data read with JSON.
{% block script %}
<script type="text/javascript">
var host_api_url = "{{host_url}}"
</script>
<script src="static/script.js"></script>
{% endblock %}
I'm using json getJSON to read the data from the json file and create some html components in my js script like this:
$.getJSON("application/data/file.json", function(data) {
$.each(data, function(key, value) {
$("<div />", { "class":"group" })
.append($("<p />", {name:"title"+i, id:"title"+i, text: key }))
.appendTo(".output");
$("<div />", { "class":"group" })
.append($("<p />", {id:"content"+i, text: value }))
.appendTo(".output");
i++;
})
});
Is there any way to get the data from the local directory and resolve the error I specified above?

Just to be sure, you need to serve that file.json through a web server, in your case running on 127.0.0.1 since jQuery.getJSON() is using a HTTP GET request - it will not read a local file directly.
https://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success
The error message indicates that you likely misplaced the file in the wrong directory.
Note that you cannot read arbitrary local files from a browser environment programmatically (due to the browser sandbox principle).
If this JSON file is an end-user supplied file, you can ask the user to
drag and drop it into the browser and then use the FileReader API to read that file, see https://developer.mozilla.org/en-US/docs/Web/API/HTML_Drag_and_Drop_API or
ask the user to select a local file through an <INPUT> form element.
Starting point: https://developer.mozilla.org/en-US/docs/Web/API/File
Once you have the file read in, use data = JSON.parse(textcontent) to parse it as JSON and retrieve the JS object data.

Related

Get json from flask using an external js file

I have a flask server spitting out json data converted from pandas dataframe which look like:
[{'name': 'FBtr0075557',
'score': '164.00'},
{'name': 'FBtr0075557',
'score': '162.00'}]
The python code I'm using to convert the dataframe to json and serve in flask is:
result = df.to_json(orient="records")
parsed = json.loads(result)
return render_template('mirtar.html', targets=json.dumps(parsed))
When I use internal javascript, the data is parsed without any error:
<script type="text/javascript">
const targets = {{ targets|tojson }};
const entries = JSON.parse(targets);
console.log(entries);
</script>
However when I try to do the same using an external JS script, I get an error
Uncaught SyntaxError: Unexpected token { in JSON at position
From what I understand, the line const targets = {{ targets|tojson }}; in the external javascript doesn't behave the same way as in internal and the first '{' of the line is considered as an error.
I'm sure this is a very basic problem and there must be an easy way to do it that I have definitely missed.
Jinja syntax is only parsed in flask html templates, not externally loaded JS assets: because it's the python app doing the parsing, and in a deployed environment you'd typically serve static assets with a webserver like nginx.
The quickest way to sort this might be with this method where instead you use a data attribute within an HTML element. This appreciates that you're passing data to the template as an argument to render_template, so the data is present in the template at page load.
In your case this might look like
<!-- a hidden tag -->
<input type='hidden' id='targetid' data-thetargets='{{ targets|tojson }}' />
Then in your javascript load it up with:
var targets = JSON.parse(document.getElementById("targetid").dataset.thetargets);

Cannot pass server object from one jade file to another jade file

I have just started using jade and node. I am passing an object from node to jade template (parent.jade) and including the same jade file (parent.jade) to another file (child.jade). it is depicted as follows:
Node part:
res.render('parent.jade', {data: mydata});
Then in parent.jade I am receiving the data correctly:
doctype html
html
head
title parent
script(type="text/javascript" src="/resources/file_javascript.js").
var data_from_node = !{JSON.stringify(data)}; //getting the data in javascript file
body(data-title="parent")
div#header(class="wrap")
include header.pug
ul#list(class="nav nav-tabs")
footer(id="footer" class="footer")
include footer.pug
In child.pug I am including the parent file but could not get the data object. I have tried everything but nothing is working here I am including it in the following way:
doctype html
html
head
title child.pug
body(data-title="child")
div(class="wrap")
include parent.pug //here I am including parent.pug getting the content right
div#mydiv(class="tab-content")
include table.pug
footer(id="footer" class="footer")
include footer.pug
script(type='text/javascript').
var data = !{JSON.stringify(data)}; //getting null here
script(type = "text/javascript", src = "/resources/file_javascript.js")
Is there any way to get the "data object" in child.pug from parent.pug because I am getting null in child.pug?
Unfortunately not. When you call res.render in Node.js, the context variables you pass to that template are only remembered while that template is being rendered. If you want to let child.pug have access to that variable, you must actively pass it to that template, as well (when you call res.render("child.pug", {...})).

I have json file on local computer i want to use that file in javascript how can i use that in js

Following is the code snippet which i am trying
var json = require('dictonery.json'); //(with path)
console.log(json);
$.getJSON is asynchronous. See http://api.jquery.com/jQuery.getJSON/
You should do
$.getJSON("test.json", function(json) {
console.log(json);
// this will show the info it in firebug console
});
OK, so from your comments I assume you have the following scenario: You have a server somewhere running your code and you have a local machine where the JSON file is stored. That won't work, if the local machine is not running a web server allowing you to load the JSON to the machine running the code. You could do this in that case e.g. by using PHP's file() function or via an Ajax call. I'd rather recommend to upload it first, so all files are in the same file system.
If you create the JS from a PHP enabled file you could do the following:
var json = '<?php require('dictonery.json') ?>'; //(with path)
console.log(json);
var jsonObj = JSON.parse(json);
console.log(jsonObj);
The require loads the file holding your JSON data (given that it is accessible) and puts it into the js file so that it ends up in a string variable. The JSON.parse creates a Javascript object from this string, so that you can actually use the data.

passing data between views in express js

I'm brand new to express and node, so please bear with me :D
i have an index.ejs file. I need to pass a string from my index.ejs file, to my viewActivity.ejs file. That string will then be used in the javascript portion of my viewActivity.ejs file. I'm not really sure how to go about this though. Is what I want to do even possible? Or do I have to do this via another file and not just directly view to view ?
here is my code. I want to pass the "stringToPass" to another view when a button is clicked.
function getPosts() {
var query = new Parse.Query(Post);
query.find({
success: function(results){
for (var i in results) {
var title = results[i].get("activityTitle");
var stringToPass = results[i].id
}
}, error: function(error) {
console.log("Query Error:"+error.message);
}
});
}
So far I've learned that express acts as the request handler. E.g.: pass you the file or anything based on the given request.
As soon as the request has been finished being handled, express would not know what the client does with the given result. Hence, once it sent the html file or json file or other request has been responded, all the remaining activities will be handled by a client side script that talks back to the express server in other form of requests. UPDATE: you can make this client side script to extract a DOM element and pass it onto your follow up request (when a user click a submit button, etc) that is handled by a different route.

Sending JSON and HTML page together in node.js

I am sending my HTML file to the client in node.js as shown below
app.get('/get', function(req, res) {
res.render(index.html);
});
Here, index.html refers to a json file.
How can I send both together or refer the json file in the client?
If you don't want to request the JSON file from the client as an independent HTTP request you can do one of the following:
Full server side rendering:
Use a template technology like moustache or handlebars, and try to render that data inline with the response. For example if you your JSON file returns a name and an address the index.html could look like:
<div>
<span>Name: {{name}} </span>
<address>Address: {{address}} </span>
<div>
Then when rendering you could pass a js object with properties name and address to the template and you wouldn't need to ask for the JSON file separately. This example follows moustache guidelines just in case I wasn't explicit enough.
Inline object
A bit like the previous solution but less elegant, you can add the full JSON response as an object with within a script tag, and then use it however you see fit. Try to append a block to he HEAD of index.html like this:
<script>
var myObject = <contents of your JSON object>
</script>
The other possible solution was just described in another answer.
I hope this helps.
HTTP only sends one resource at a time. If your page is requesting a JSON file, it needs to be served as a second request.
Alternatively, you can render HTML with a <script> block that has a variable assignment with your JSON-encoded data as a value.
You can't send two types of files back in a single request, but you could either do an ajax call in the html to get the json you need:
<script type="text/javascript">
var json_data;
$.getJSON("URL_HERE", function(data) { json_data = data; });
</script>
or add the json to the html as a javascript object via a template engine (jade shown below):
script(type="text/javascript").
var json_data = #{ JSON.stringify(JSON_OBJECT_HERE) }

Categories

Resources