Load JSON file and store variable content

9

I have the following code:

<script type="text/javascript">
    $(document).ready(function(){
        $("form.loader").on('submit',function(e){
            e.preventDefault();
            $.ajax({
                url: "data.json",
                type: "POST",
                cache: false,
                success: function(data){
                    console.log(data);
                },
                error: function(data){
                    console.log(data);
                }
            });
        });
    });
</script>

<form class="loader" method="POST" enctype="multipart/form-data">
    <input type="file" name="data">
    <button type="submit">Cargar datos</button>
</form>

So, what I want is to be able to load the JSON from an input file and store all the JSON content in a variable. To apply modifications and again save the file:)

But for now I would just like to open the file to manipulate it.

  

In response to @json

Use load is great to show a file as such, but if I wanted to save the contents in a variable how should I do it?

  

And for some comments ...

Well, little use GET. Usually I always use POST. If I must use GET, I would like to know what the reason is:)

asked by Máxima Alekz 25.03.2017 в 07:31
source

5 answers

5

Depending on the side the file is in, you could proceed in two ways: by reading the file from the client's device (explained in A), or from the server (explained in B).

Your question:

  

If I must use GET, I would like to know what the reason is:)

I'll answer it in (C).

A. IF THE FILE IS ON THE CUSTOMER SIDE

You can do it using FileReader . The client must select the file by clicking on the button:

function leerArchivo(e) {
  var archivo = e.target.files[0];
  if (!archivo) {
    return;
  }
  var lector = new FileReader();
  lector.onload = function(e) {
    var contenido = e.target.result;
    mostrarContenido(contenido);
  };
  lector.readAsText(archivo);
}

function mostrarContenido(contenido) {
  var elemento = document.getElementById('contenido-archivo');
  elemento.innerHTML = contenido;
}

document.getElementById('file-input')
  .addEventListener('change', leerArchivo, false);
<input type="file" id="file-input" />
<h3>Contenido del archivo:</h3>
<pre id="contenido-archivo"></pre>

Note:

This method is compatible with:

  • IE 10 +
  • Firefox 3.6 +
  • Chrome 13 +
  • Safari 6.1 +

B. IF THE FILE IS ON THE SERVER'S SIDE

You can do it with jQuery. In the example, the url of the file is entered in the input and pressing the button requests the file from the server using the get method of Ajax If the answer is satisfactory, the file is displayed on a div.

<script   src="https://code.jquery.com/jquery-2.2.4.min.js"   integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="   crossorigin="anonymous"></script>

<script>
$(function() 
{
$("#button").click( function()
{
   alert('button clicked');
//       var TXT_URL = 'https://www.mozilla.org/media/MPL/2.0/index.815ca599c9df.txt';
   var TXT_URL = $("#input-url").val();

    $.ajax
    (
    	{
        	url : TXT_URL,
			dataType: "text",
			success : function (data) 
			{
            	$(".text").html("<pre>"+data+"</pre>");
			}
		}
	);
   });
});

</script>
Ingrese una url válida:<input type="text" id="input-url" size="50" value="https://www.mozilla.org/media/MPL/2.0/index.815ca599c9df.txt"></input>

<input type="button" id="button" value="Ver .txt"></input>
<div class="text">
  <hr />
  <h2>Texto:</h2>
</div>

C. WHAT METHOD TO USE?

In the first case none, since the server does not intervene at all. In the second case the GET method.

  

The fundamental differences between "GET" and "POST"

     

The HTML specifications technically defines the difference between "GET" and   "POST" so that former means that form data is to be encoded (by a   browser) into a URL while the latter means that the form data is   appear within a message body. But the specifications also give the   usage recommendation that the "GET" method should be used when the   form processing is "idempotent", and in those cases only. As a   simplification, we might say that "GET" is basically for just getting   (retrieving) data whereas "POST" may involve anything, like storing or   updating data, or ordering a product, or sending E-mail.

     

The HTML 2.0 specification says, in section Form Submission (and the   HTML 4.0 specification repeats this with minor stylistic changes):

     

If the processing of a form is idempotent (i.e. it has not lasting   observable effect on the state of the world), then the form method   should be GET. Many database searches have no visible side-effects and   make ideal applications of query forms.

     

If the service associated with the processing of a form has side   effects (for example, modification of a database or subscription to a   service), the method should be POST.

  

The fundamental differences between "GET" and "POST"

     

HTML specifications technically define the difference between   "GET" and "POST", so that GET means that the form data   must be encoded (by a browser) in a URL while POST   means that the form data must appear within the   message body. But the specifications also recommend that    The "GET" method should be used when the form processing is "idempotent", and only in those cases . As a simplification,   we could say that "GET" is basically used to obtain   (retrieve) data while "POST" can imply anything,   how to store or update data, order a product or send mail   electronic.

     

The HTML 2.0 specification says, in the Form section of   presentation (and the HTML 4.0 specification repeats it with changes   minor stylistics):

     

If the processing of a form is idempotent (that is, it does not have a lasting observable effect ...), then   The form method must be GET. Many basic searches of   data have no visible side effects and make applications   ideal consultation forms.

     

If the service associated with the processing of a form has side effects (for example, modification of a database or   subscription to a service), the method must be POST.

Source: link

    
answered by 29.03.2017 / 22:47
source
5

good if you want to show the content of a txt in a div would be more or less like this.

$(document).ready(function(){
  $("button").click(function(){
    $("#texto").load("archivo.txt");
  });
});

you put the div where you want it to be displayed and the button to execute the action.

<button>Cargar Contenido</button>
<div id="texto"></div>

I hope it helps.

    
answered by 25.03.2017 в 14:52
2

You could solve it using:

  • The API FileReader which allows you to dynamically read a file entered by the user.
  • The method JSON.parse which allows us to transform a string JSON to an object.

Example:

var input = document.getElementById('file'),
  code = document.getElementById('code');

input.addEventListener('change', function() {
  var file = input.files[0];
  
  var reader = new FileReader();
  reader.onload = function(e) {
    var json;
    // Aquí mostramos el texto que contiene el archivo
    code.value = e.target.result;

    // Aquí guardamos en una variable el resultado de parsear el JSON
    json = JSON.parse(e.target.result);
  };
  reader.readAsText(file);
});
<input id="file" type="file" accept="txt/json" /><br/>
<textarea id="code" name="code" rows="5" cols="50"></textarea>
    
answered by 29.03.2017 в 21:53
2

Once you upload the file, you can save the file in a SessionStorage or a LocalStoragge, both are very good, since it lets you store data on the client side with a maximum of 5mb approx. The difference between one and another is that Session is eliminated if you close the browser, the other does not.

This is invoked as follows

sessionStorage.setItem('variable', variableJson);
localStorage.setItem('variable', variableJson);

You pass the "variableJson to the variable of the session or local with the name" variable ", which is saved in the PC as a temporary file, if you need to rescue it, it should be done in the following way.

sessionStorage.getItem('variable');
localStorage.getItem('variable');

and if you need to delete, just

sessionStorage.removeItem('variable');
localStorage.removeItem('variable');

I hope it helps you.

And always better is post, since you get, it reveals the parameters that you send to your server through the url. And it is considered as "vulnerable" if it needed to attack your site, since that way I begin to understand how your server works and how I can bounce through this block.

Success in what you are working on: D

    
answered by 30.03.2017 в 17:34
2

Since the file is on the server, we would load it with .load () from jquery and store the content in a textarea so you can edit it and once placed, the comments or changes you want to make to the file, capture its content and send it to $. post to a php script to save the changes.

    $(document).ready(function(){
        //Cargamos el contenido  para el textarea
        $("id_load").click(function(){
            $("#id_textarea").load("demo_test.txt");
        });
        //Enviamos los datos por $.pos para el servidor para guardar los cambios 
        $("id_save").click(function(){
           //Capturamos los cambios hecho al contenido del fichero.
           var text_area = $("#id_textarea").val()
          $.post("script.php",{text_area:text_area},'json');
       });
    });

Form:

 <form class="loader" method="POST" enctype="multipart/form-data">
    <button type="button" id="id_load">Cargar datos</button>
    <textarea name="con_txt" id="id_textarea" rows="40"></textarea>
    <button type="button" id="id_save">Guardar datos</button>
</form>

in the script.php to add the content to the end of the file:

<?php 
//Capturamos el datos que viene del formulario con $_POST de php.
$contenido = $_POST['text_area'];
$f = fopen("demo_test.txt", "W");
fwrite($f,$contenido);
fclose($f);
?>
    
answered by 31.03.2017 в 18:22