0

I have a problem(or problems) with my code, when I'm trying running the script in the developer kit trows the error

unexpected token u in JSON at position 0...

funciones.js

$(document).ready(function (){

      $("#btn1").click(function(){
      $.ajaxSetup({ cache: false });

          var url = "productos.json";

        var myData = JSON.parse(JSON.stringify(url.responseText || null, function(data){


              for (var team in data) {
                var html = []; //variable html
                html = '<div class="item"><b>Nombre: </b>' + data[team].producto.nombre + '<br/>[\n]';
                html += '<b>Precio: $</b>' +data[team].producto.precio + '<br/>';//precio
                html += '<b>Marca: </b>' +data[team].producto.marca + '<br/>';
                html += '<b>Presentación: </b>' + data[team].producto.presentacion + '<br/>';
                html += '<b>Contenido: </b>' + data[team].producto.contenido + '<br/></div>';
                $("#div1").append(html);
              }
            }));
      });
    });


   function block(){
   document.getElementById("btn1").disabled = true;
 }

productos.json

[
{
  "nombre":"Coca-Cola",
  "precio":30,
  "marca": "Cocacola",
  "presentacion":"Familiar grande",
  "contenido":"3Lt."
},
{
  "nombre":"Coca-Cola",
  "precio":25,
  "marca": "Cocacola",
  "presentacion":"Familiar",
  "contenido":"2.5Lt."
},
{
  "nombre":"Coca-Cola",
  "precio":15,
  "marca": "Cocacola",
  "presentacion":"individual",
  "contenido":"1Lt."
}
]

HTML

    <!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
  <script src="funciones.js" language="javascript" type="text/javascript"></script>
  <script type="text/javascript" src="productos.json"></script>
  <meta charset="utf-8">
  <title>jQuery Ajax</title>
  <link rel="stylesheet" href="stilo.css">
</head>
<body>
  <div>   
    <div>Prueba basica de archivos</div>
    <div id="div1"></div>
    <button id="btn1" onclick="block()" type="button">Team location</button>
  </div>
</body>
</html>

What is the problem here?
Thanks in advance

mhodges
  • 10,938
  • 2
  • 28
  • 46
Omega
  • 21
  • 1
  • 5
  • 2
    `url.responseText` is `undefined`, and so the error complains on the first character of that, i.e. the `u` of `undefined`. Look at how you defined `url` and notice how that does no have `responseText`. You are mixing up a lot of things there. You never make the ajax call, and so there is no response either. Then you define a callback function for the result, but pass it as callback function to `JSON.stringify`.... twisted. – trincot Nov 29 '16 at 18:41
  • 1
    `unexpected token u in JSON at position 0...` This can usually mean that you are trying to parse or access `undefined` hence the `u` at index 0 – Alex Szabo Nov 29 '16 at 18:42
  • `JSON.parse(JSON.stringify(url.responseText || null, function(data){` what.. JSON.stringify does accept a replacer callback, but... you don't seem to be using that function as such. – Kevin B Nov 29 '16 at 19:09

2 Answers2

0

There are several problems in your code. I have modified your code into a plunkr here You should visit the working plnkr to find what was corrected however I will put some snippets here also.

The line below does not do anything.

var myData = JSON.parse(JSON.stringify(url.responseText || null, function(data){

The actual ajax call was missing so I added it

$.ajax({
        url: url
    }).done(function(myData){
     //your code here
    }

Then the loop

html = 'Nombre: ' + data[team].producto.nombre + '
[\n]';

Here data is an array so it needs to be treated as an array. Further each array item itself is producto.

So this is corrected to

for (var i = 0; i < data.length ; i++) {
  var producto = data[i];
  var html = []; //variable html
  html = '<div class="item"><b>Nombre: </b>' + producto.nombre + '<br/>[\n]';
  html += '<b>Precio: $</b>' + producto.precio + '<br/>'; //precio
  html += '<b>Marca: </b>' + producto.marca + '<br/>';
  html += '<b>Presentación: </b>' + producto.presentacion + '<br/>';
  html += '<b>Contenido: </b>' + producto.contenido + '<br/></div>';
  $("#div1").append(html);
}
bhantol
  • 9,368
  • 7
  • 44
  • 81
0

There are several issues:

  • url.responseText is undefined, and so the error complains on the first character of that, i.e. the u of undefined. Look at how you defined url and notice how that does no have responseText.
  • There is no Ajax call in your code. Use $.getJSON for this.
  • Do not use JSON.parse nor JSON.stringify: they only make things worse. jQuery will have done the conversion for you already.
  • If html is supposed to be a string, then don't initialise it as an array with [].
  • the onclick attribute references a function block that is not in the global scope.
  • Either add a click handler via code, or via the onclick attribute, but not both. So combine the code in one single click handler via one method.
  • The property producto does not exist in your JSON, so all the references to it will fail. Remove that property from your code, unless your JSON is different from what you have in the question

Other remarks:

  • You mix jQuery and non-jQuery syntax. When you have jQuery, use it. So not document.getElementById().
  • [\n] is a strange thing to output. I would remove that.
  • The loop for (var team in data) can be written with of instead of in, that way team will be the object, not the index, which makes the rest of your code simpler.
  • A button element doesn't need a type="button" attribute

Here is code that corrects all these issues:

HTML:

  <div>   
    <div>Prueba basica de archivos</div>
    <div id="div1"></div>
    <button id="btn1">Team location</button>
  </div>

JavaScript:

$(document).ready(function (){
    $("#btn1").click(function(){
        $(this).disabled = true;
        $.ajaxSetup({ cache: false });
        $.getJSON("productos.json").done(function(data) {
            for (var team of data) {
                $("#div1").append(
                    $('<div>').addClass('item').append([
                        $('<b>').text('Nombre'), team.nombre, $('<br>'),
                        $('<b>').text('Precio: $'), team.precio, $('<br>'),
                        $('<b>').text('Marca: '),   team.marca, $('<br>'),
                        $('<b>').text('Presentación: '), team.presentacion, $('<br>'),
                        $('<b>').text('Contenido: '), team.contenido, $('<br/>')
                    ])
                );
            }
        });
    });
});
trincot
  • 317,000
  • 35
  • 244
  • 286
  • I try all the options, and now... my problem is this "jquery-2.1.0.min.js:4 XMLHttpRequest cannot load file:///C:/Users/Sol/Desktop/prueba/productos.json?_=1480970912134. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource." if i put the code in a server, i get the result... but if i try it without the server... i get that message – Omega Dec 05 '16 at 20:49
  • That is a different question. See [this Q&A](http://stackoverflow.com/a/10752078/5459839) for information on that. – trincot Dec 05 '16 at 20:58