SyntaxError: JSON.parse in $ (document) .ready ();

0

this error had already been given to me before and it was corrected, in this case now if I select an element of a select I must make a $ _POST so that it loads me what is related to that select that in this case would be a sub category the code is as follows

in my html I have this select

<div class="row center-align">
    <div class="input-field col s12 m6 l6 push-l2">
        <select name="categoria" id="categoria">
            <option value="" disabled selected>Elija una Categoria</option>
//lo que esta entre las llaves es codigo de un framework que se llama smarty
            {section name="cat" loop=$book_categoria.count}
            <option value="{$book_categoria[cat].id}">{$book_categoria[cat].texto}</option>
            {/section}
        </select>

    </div>

in the javascript file I have the following, unlike previous code in this case I have it within $(document).ready();

     $("select[name=categoria]").change(function(){

        var id_book_categoria =  $(this).val();
        $.post(".select_categoria_subcategoria.php", {id_book_categoria:id_book_categoria},
        function(response){
            console.log(response);
//aqui es cuando da el error JSON.parse
            response = JSON.parse(response);
            console.log(response);
            // $('#rta').html(response);
        });

    });

where you get the $_POST I have the following

$book_subcategoria = lista_book_subcategorias('',$conn);
// var_dump($book_subcategoria);
$sub_cats=[];
var_dump($_POST['id_book_categoria']);

for ($i=0; $i < $book_subcategoria['count']; $i++) { 
    if ($_POST['id_book_categoria'] == $book_subcategoria[$i]['id_book_categoria']) {
        if($book_subcategoria[$i]['status']!=66){
            $sub_cats[] = array(
                'id' => $book_subcategoria[$i]['id'],
                'texto' => $book_subcategoria[$i]['texto'],

            );
        }

    }
}
echo json_encode($sub_cats,JSON_FORCE_OBJECT);

what it is to print in the .PHP the JSON does it well I do not understand why it may be silly but I do not see the error because I have already done similar things.

Greetings.

    
asked by juank 30.08.2018 в 11:06
source

1 answer

3

Always write your JSON.parse as:

try {
    response = JSON.parse(response);
}catch(e){
    console.log(e, response);
    return false; // para evitar errores posteriores al parseo
}

This way you can control the error and see what it is.

Try catch JavaScript

    
answered by 30.08.2018 / 12:46
source