Read list from a text file js - javascript

Hello i'm trying to read this list from a file
this
this.testJson = {
list:[
{src:"x1.jpg",title:"x1",song:"x1.mp3"},
{src:"x2.jpg",title:"x2",song:"x2.mp3"},
{src:"x3.jpg",title:"x3",song:"x3.mp3"},
{src:"x4.jpg",title:"x4",song:"x4.mp3"}
]
}
to
this.testJson = {
list:[
// read x.txt or x.txt from a URL
]
}
and x.txt contain
{src:"x1.jpg",title:"x1",song:"x1.mp3"},
{src:"x2.jpg",title:"x2",song:"x2.mp3"},
{src:"x3.jpg",title:"x3",song:"x3.mp3"},
{src:"x4.jpg",title:"x4",song:"x4.mp3"}
as i do not have any java script experience , can somebody help me with this ?
thanks in advance

You have to expose that file from a web-server so your JavaScript can make an http request on that file.
To load resources from JavaScript you have to make an XMLHttpRequest or better known as AJAX request.
Actually this requires some setup so using a library would be easier. My favourite one is axios. It has a really simple API and handles response parse as well, so when you load axios on your web-site this is an approach you might follow :
axios.get('path-to-file').then(function(response){
this.testJson.list = response.data
});
Note that your x.txt does not seem like a valid JSON. It has to be a valid one so axios can parse it. If you decide to parse the file on your own you have to use JSON API.

Related

Making a local file hold a value to use by any user

I am trying to make a webpage that will be able to store a variable, using JavaScript, called heart-count (I was trying it with jQuery and JSON, but didn’t have any luck, I could access the number easily, but I couldn’t change it).
This variable should be easily accessed by the JavaScript and be able to be changed (or in my case incremented).
The way that I have it right now is in a local file called heart.json inside this file is the following code:
{
"hearts": 0,
"heartLog": []
}
I am accessing that file in my JavaScript like this:
$.getJSON("../js/heart.json", function(data) {
$("#num-hearts").text(data.hearts)
})
I was trying to use XMLHttpRequest (a way that was suggested to me):
var myJSON
$.getJSON("../js/heart.json", function(data) {
myJSON = data
setTimeout(() => {
myJSON.hearts++
console.log(myJSON)
console.log(data)
}, 2000);
})
var xhr = new XMLHttpRequest()
xhr.open("PUT","../js/heart.json",true)
xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8')
xhr.send(JSON.stringify(myJSON))
I can’t confirm that this doesn’t work, since the way that the webpage is set up I test it using some interesting methods (interesting, but required…), and those use localhost. The reason I say that I can’t confirm that it doesn’t work, is because when I test the previous code, it says that “PUT” isn’t a valid protocol.
If there are any suggestions or validations of my code, that would help a lot.
How ya doin? I'm sorry to say but you can not write to a file in server directly with jQuery or Javascript because Javascript is frontend language. It doesn't have the capability to do so.
However you can send or receive data with XMLHttpRequest, but you need a server side language/program to process your XMLHttpRequest.

Javascript (or angular) point variable to local file (json)

I am trying to used locally stored json files to pull in information, right now I am just hardcoding the json in a variable, but what I would like to do is point to some json files I have locally
something like -
var myData = "scripts/data/myData.json";
Is something like this possible?
Thanks!
You can do that in this way :
$http.get("scripts/data/myData.json").success(function(response) {
$scope.myData= response
}).error(function(err) {
alert(err);
})
Please see here working demo
http://plnkr.co/edit/dV1lHIZyoKYNDxbPwHNV?p=preview
I`m pretty sure that you can not make AJAX request to a file:// protocol.

Play Framework: How to implement REST API for File Upload

I'm developing a REST API with Play 2 and I'm wondering how to implement file upload functionality.
I've read the official Play documentation but it just provides a multipart/form-data example, while my backend does not provide any form... it just consists of a REST API to be invoked by a JavaScript client or whatever else.
That said, what's the correct way to implement such an API? Should I implement a PartHandler and then still use the mutipartFormData parser? How should I pass the file content to the API? Is there any exhaustive example on this topic?
Any help would be really appreciated.
You should look into BodyParsers: http://www.playframework.com/documentation/2.2.x/ScalaBodyParsers
What you are trying to do is not especially complicated, especially if you are only handling smaller files that would fit in memory. After all uploading a file is just about sending the file as a body of a POST or something like that. It is not any different from receiving some XML or JSON in a request.
Hope this helps
import org.apache.http.entity.mime._
import java.io.File
import org.apache.http.entity.mime.content._
import java.io.ByteArrayOutputStream
import play.api.libs.ws.WS
val contents ="contents string"
val file = File.createTempFile("sample", ".txt")
val bw = new java.io.BufferedWriter(new java.io.FileWriter(file)
bw.write(new_contents);
bw.close();
builder.addPart("file", new FileBody(file, org.apache.http.entity.ContentType.create("text/plain"), "sample"))
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
val entity = builder.build
val outputstream = new ByteArrayOutputStream
entity.writeTo(outputstream)
val header = (entity.getContentType.getName -> entity.getContentType.getValue)
val response = WS.url("/post/file").withHeaders(header).post(outputstream.toByteArray())
To pass your contents, depending on your client side, you can encode the contents to Base64 at client side to pass the contents as Json (You can use Json body parser). Then on the server side you can decode the contents using a Base64 decoder (e.g. Apache Commons) to get the byte array. It will be as simple as
Base64.decodeBase64(YourEncodedFileContent)
When you have the byte array you can simply write it on disk or save it into database etc. We are using this approach in production and it works fine however we only handle small file uploads.
OK, thank you all for your suggestions... here below is how I solved my issue:
object Files extends Controller {
def upload = SecuredAction[Files.type]("upload").async(parse.multipartFormData(partHandler)) { implicit request =>
future { request.body.files.head.ref match {
case Some((data, fileName, contentType)) => Ok(success(Json.obj("fileName" -> fileName)))
case _ => BadRequest
}}.recover { case e =>
InternalServerError(error(errorProcessingRequest(e.getMessage)))
}
}
...
private def partHandler = {
parse.Multipart.handleFilePart {
case parse.Multipart.FileInfo(partName, fileName, contentType) =>
Iteratee.fold[Array[Byte], ByteArrayOutputStream](
new ByteArrayOutputStream
) { (outputStream, data) =>
outputStream.write(data)
outputStream
}.map { outputStream =>
outputStream.close()
Some(outputStream.toByteArray, fileName, contentType.get)
}
}
}
}
I hope it helps.
while my backend does not provide any form... it just consists of a REST API to be invoked by a JavaScript client
Then your backend is not a REST API. You should follow the HATEOAS principle, so you should respond with links and forms along with data to every GET request. You don't have to send back HTML, you can describe these things with hypermedia json or xml media types, for example with JSON-LD, HAL+JSON, ATOM+XML, etc... So you have to describe your upload form in your preferred hypermedia, and let the REST client to turn that description into a real HTML file upload form (if the client is HTML). After that you can send a multipart/form-data as usual (REST is media type agnostic, so you can send data in any media type you want, not just in a JSON format). Check the AJAX file upload techniques for further detail...

Getting all of the .json files from a directory

I'm creating an android app which takes in some json data, is there a way to set up a directory such as;
http://......./jsons/*.json
Alternatively, a way to add into a json file called a.json, and extend its number of containing array data, pretty much add more data into the .json file this increase its size.
It could be by PHP or Javascript.
Look into Parsing JSON, you can use the JSON.parse() function, in addition, I'm not sure about getting all your JSON files from a directory call, maybe someone else will explain that.
var data ='{"name":"Ray Wlison",
"position":"Staff Author",
"courses":[
"JavaScript & Ajax",
"Buildinf Facebook Apps"]}';
var info = JSON.parse(data);
//var infostoring = JSON.stringify(info);
One way to add to a json file is to parse it, add to it, then save it again. This might not be optimal if you have large amounts of data but in that case you'll probably want a proper database anyway (like mongo).
Using PHP:
$json_data = json_decode(file_get_contents('a.json'));
array_push($json_data, 'some value');
file_put_contents('a.json', json_encode($json_data));

Passing JavaScript variable to Python

For example:
#!/usr/bin/python
print "This is python."
print "<script type="text/javascript">
var pass_to_python = new Number(7)
</script>"
the_number = pass_to_python???
How do I get the pass_to_python in python?
With pyv8 you can execute javascript from within Python.
import PyV8
class Global(PyV8.JSClass):
pass
with PyV8.JSContext(Global()) as ctxt:
the_number = ctxt.eval("var pass_to_python = new Number(7)")
see http://code.google.com/p/pyv8/
You can GET or POST to the Python script. If you need to do this dynamically, you can use AJAX.
Here is a good link: How are POST and GET variables handled in Python?
i am using flask and ajax to pass values from javacript to python
function pass_values() {
var pass_to_python = new Number(7)
$.ajax(
{
type:'POST',
contentType:'application/json;charset-utf-08',
dataType:'json',
url:'http://127.0.0.1:5000/pass_val?value='+pass_to_python ,
success:function (data) {
var reply=data.reply;
if (reply=="success")
{
return;
}
else
{
alert("some error ocured in session agent")
}
}
}
);
}
python:
#app.route('/pass_val',methods=['POST'])
def pass_val():
name=request.args.get('value')
print('name',name)
return jsonify({'reply':'success'})
HTTP is a simple request-response protocol, it doesn't let you pause mid-stream and wait for more information from the client — and since your JS runs in the browser (JS can run on the server, but most people wouldn't be attempting this if they didn't need the code to run in the browser, so I'm assuming that using server side JS is out of the question) and the Python runs on the server, that is what you need for your code to work (as well as fixing your broken quote nesting in the Python code).
You need to load the complete document, and then issue a new HTTP request.
This might involve having the JS set location.href (making sure you have a fallback for non-JS clients), it might involve using XMLHttpRequest to load new data asynchronously, it might be best using another technique (it is hard to say for sure as your example simplifies too much to tell what X is)
I think using JSON is the best way.you can create a JSON file as intermidiary between JavaScript and Python, both languages can access and modify JSON file

Categories