Monday 15 July 2013

javascript read from a txt file and inject text into form -



javascript read from a txt file and inject text into form -

i apologize in advance total beginner. have pre-existing html form text fields. need have button allow me upload txt file (since when trying reply this, learned javascript can't access file pc without me actively uploading it). need values txt file inserted text fields (for example, form has: name, lastly name, phone etc - , file fill out info).

i going crazy trying collect bits , pieces other people's questions. help appreciated!

it depends on how have handled, there 2 options:

file upload , page redirect

you provide file upload form upload textfile, redirect same page via form submission, handle info on serverside (e.g. parse file , values out of it) , allow server inject values default properties form file returned browser

xmlhttprequest file upload

in modern browsers, native xhr object supports upload property, send file via upload property. has sent serverside script parses file , returns values in fitting format, e.g. json (which this: {'name':'somename', 'lastname':'someothername'}). have register eventlistener on completion of upload (e.g. onload) , set these values on javascript side.

check out xmlhttprequest upload (better solution in opinion): https://developer.mozilla.org/en-us/docs/web/api/xmlhttprequest/using_xmlhttprequest#submitting_forms_and_uploading_files

edit: well, easiest solution provide textfield , paste content of file field, nail button , content parsed. wouldn't rely on network traffic or serverside handling, javascript, e.g. this: dom:

<textarea id="tf"></textarea> <button id="parse">fill form!</button>

js:

var tf = document.getelementbyid("tf"); document.getelementbyid("parse").addeventlistener("click", function(){ var formdata = json.parse(tf.value); //if textfile in json format, formdata object has values });

edit: link posted in comments:

<!-- html --> <input id="the-file" name="file" type="file"> <button id="sendfile">send</button>

and

document.getelementbyid('sendfile').addeventlistener("click", function(){ var fileinput = document.getelementbyid('the-file'); var file = fileinput.files[0]; var formdata = new formdata(); formdata.append('file', file); var xhr = new xmlhttprequest(); // add together event handlers here... xhr.open('post', '/upload/path', true); xhr.onreadystatechange = function(){ if(xhr.readystate == 4 && xhr.status == 200){ var values = json.parse(xhr.responsetext); //these input elements want fill! formnameinput.setattribute('value', values.name); formfirstnameinput.setattribute('value', values.firstname); } } xhr.send(formdata); });

as said, serverside has parse file , respond json

javascript

No comments:

Post a Comment