Search code examples
javascripttrie

how to get rid of Js Undefined from here?


enter image description heremy code is okay and output comes into console. but in my span tag result(firstname) shows undefined. i can't understand what is the problem. can anyone help me to solve this problem? how can i get rid of this problem?

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Search Baby name</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
    <script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>

</head>
<body>
<div class="first_div" id="div_id">
    <div><p> Baby Names</p></div>
    <div><p> HOW UNIQUE IS YOUR CHILD NAMES IS ?</p></div>
    Enter Full Name : <input type="text" id="input_id" class="input_class">
    <input type="button" class="btn_class" id="btn_id" value="search">
    </br>
    <span id="result">  </span>

</div>
</body>
</html>


<script>
    function insertWord(tree, string) {
        var keys = Object.keys(tree),
            result = keys.some(function (k) {
                    var i = 0;
                    if (string.substr(0, k.length) === k) {
                        string.slice(k.length);
                        return true;
                    }
                    while (k[i] == string[i] && i < k.length) {
                        i++;
                    }
                    if (i) {
                        var id = k.slice(0, i);
                        tree[id] = {
                            [k.slice(i)]: tree[k], [string.slice(i)]: 0
                        }
                        ;
                        delete tree[k];
                        return true;
                    }

                }
            );

        if (!result) {
            tree[string] = 0;
        }
    }

    $(document).ready(function () {
        localStorage.clear();
        $('#input_id').keyup(function (e) {
            fsname = $('#input_id').val();
            var data = fsname.trim();
            var msg = $('#result');
            msg.empty();
            var localdata = localStorage.getItem(data);
            if (data) {
                if (localdata == null) {
                    $.ajax({
                        url: "search.php",
                        method: "post",
                        data: {
                            input: data
                        },
                        dataType: "",
                        success: function (name) {
                            var getdata = JSON.parse(name);
                            var tree = {};
                            getdata.forEach(insertWord.bind(null, tree));
                            localStorage.setItem(data, JSON.stringify(tree));
                            console.log(JSON.parse(localStorage.getItem(data)));
                            console.log(getdata);
                            var s = getdata.length;
                            for (var j = 0; j < s; j++) {
                                if (getdata[j].surname) {
                                    var show = '<div id="result">' + getdata[j].firstname + " " + getdata[j].surname + '</div>';
                                    msg.append(show);

                                } else {
                                    var show1 = '<div id="result">' + getdata[j].firstname + '</div>';
                                    msg.append(show1);

                                }
                            }
                        }
                    });
                } else {
                    var getdata = JSON.parse(localdata);
                    var s = getdata.length;
                    for (var j = 0; j < s; j++) {
                        if (getdata[j].surname) {
                            var show = '<div id="result">' + getdata[j].firstname + " " + getdata[j].surname + '</div>';
                            msg.append(show);

                        } else {
                            var show1 = '<div id="result">' + getdata[j].firstname + '</div>';
                            msg.append(show1);

                        }
                    }
                }
            }
        })

    });
</script>

i want my firstname here. but it shows undefined. how can i solve this problem? In console my output is pretty okay. and data saved in localstorage.


Solution

  • Your code is invalid, appending multiple elements with the same id var show = '<div id="result">' + getdata[j].firstname + " " + getdata[j].surname + '</div>'; msg.append(show);

    Yet msg is the element with the id of result;

    • Note it is also invalid to have a span contain a block element such as a div.
    • Why include jQuery multiple times?
    • Implied global variables,
    • </br> is invalid,
    • fsname is global (undefined)
    • missing semi-colons,
    • Are you SURE you want keyup? in $('#input_id').keyup(function(e) { doing ajax on each keyup without throttle? What if I press the "a" key and hold it down? I get multiple "aaaaa" Perhaps use a 'change' event?
    • localStorage.clear(); in the document ready event handler indicates you MAY wish to use sessionStorage instead.
    • localStorage.setItem(data, JSON.stringify(tree)); is puzzling normally it would look like localStorage.setItem("mytree", JSON.stringify(tree)); or similar then use localStorage.getItem("mytree"); to access it
    • fsname = $('#input_id').val(); you are already in the event handler for that so use fsname = $(this).val();
    • $(document).ready(function () { better written as $(function () { as the recommended method https://api.jquery.com/ready/
    • rewrite your var show = '<div id="result">' + getdata[j].firstname + " " + getdata[j].surname + '</div>'; something like var show = '<span class="result">' + getdata[j].firstname + " " + (!!getdata[j].surname && !!getdata[j].surname)? getdata[j].surname :"" + '</span>';

    i.e. take this group of lines

    if (getdata[j].surname) {
         var show = '<div id="result">' + getdata[j].firstname + " " + getdata[j].surname + '</div>';
         msg.append(show);
     } else {
         var show1 = '<div id="result">' + getdata[j].firstname + '</div>';
         msg.append(show1);
     }
    

    rewrite as these two lines

     var showName = getdata[j].firstname + " " + (!!getdata[j] && !!getdata[j].surname)? getdata[j].surname :"";
     msg.append('<span class="result">'  + showName + '</span>');
    

    While you are at it, make your code more DRY.

    Put that last in a function and call it instead of putting it in twice conditionally.

    Make the span (result) a DIV if you want to use blocks (div) inside it instead.