0

I'm trying to do this thing:

I have a html input textbox, some php code that makes a query on my database and return a JSON element, and in the end some javascript that I cannot figure to work the right way.

I simply want to do a live search while user is typing, than select one of the record found from the live search and populate a form with data of this record.

Probably there is a very simple solution, but I'm a newbie.

This is my html and Javascript code:

<!doctype html>

<html lang="en">
<head>
    <meta charset="utf-8" />

    <title>InChiaro Ticket Admin</title>
    <meta name="description" content="The HTML5 Herald" />
    <meta name="author" content="SitePoint" />
    <link href="../assets/bootstrap/css/bootstrap.min.css" rel="stylesheet" />
    <link href="../assets/bootstrap/css/bootstrap-responsive.min.css" rel="stylesheet" />
    <link href="../assets/bootstrap/css/bootstrap-fileupload.css" rel="stylesheet" />
    <link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
    <link href="css/style.css" rel="stylesheet" />
    <link href="css/style-responsive.css" rel="stylesheet" />
    <link href="css/style-default.css" rel="stylesheet" id="style_color" />
    <link href="../assets/fullcalendar/fullcalendar/bootstrap-fullcalendar.css" rel="stylesheet" />
    <link href="../assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>

<body>
    <div id="main-content">
        <div class="wrapper-principale">
            <div class="input-append search-input-area">
                <input type="text" class="search-filter" id="searchcodiceCliente" name="codiceCliente" placeholder="Cerca un cliente..." /> <!-- text AREA CODICE CLIENTE-->
                <button class="btn" type="button"><i class="icon-search"></i> </button>
            </div>
            <div id="result" style="display:none">
                <table id="tablesearch"></table>
            </div>

            <form>
                <input type="text" id="CodiceCliente" />
                <input type="text" id="denominazione" />
            </form>
        </div>
    </div>
    <script type="text/javascript">
        $(function () {
            // We add the event on the class, which both inputs have
            $(".search-filter").keyup(function () {
                // Now we get the values from both inputs, using their ID's
                var codiceCliente = $("#searchcodiceCliente").val();
                //var fname = $("#searchfname").val();

                // Add both to the dataString (and URI encode the strings)

                var requestCodCliente = "get_codiceCliente_json"
                var json;
                // Check that at least one has any content
                if (codiceCliente != '')


                    $.ajax({
                        type: "POST",
                        url: "ajax_requests.php",
                        data: {
                            request: requestCodCliente,
                            searchCliente: codiceCliente
                        },
                        success: function (result) {
                            var x = document.getElementById("result");
                            x.style.display = "inline";
                            document.getElementById("tablesearch").innerHTML = '';
                            var th = "<tr><th></th><th>Codice Cliente</th><th>Denominazione</th><th>Indirizzo</th><th>Città</th><th>CAP</th><th>Numero Telefono</th></tr>";
                            document.getElementById("tablesearch").innerHTML += th;
                            function populateForm() {
                                document.getElementById("CodiceCliente").value = result[index].codiceCliente;
                            }
                            for (var index = 0; index < result.length; ++index) {

                                var t = "";

                                var tr = "<tr>";
                                tr += "<td><button id='select' class='btn'type='button' onclick='populateForm()'><i class='icon-search'></i></button></td>";
                                tr += "<td>"+result[index].codiceCliente+"</td>";
                                tr += "<td>"+result[index].denominazioneCliente+"</td>";
                                tr += "<td>"+result[index].indirizzo+"</td>";
                                tr += "<td>"+result[index].citta+"</td>";
                                tr += "<td>"+result[index].CAP+"</td>";
                                tr += "<td>"+result[index].numeroTelefono+"</td>";
                                tr += "</tr>";
                                t += tr;

                                document.getElementById("tablesearch").innerHTML += t;

                                }
                        }
                    });

            });
        });

    </script>
</body>
</html>

And this is some sample output that I hope explains what I mean:

Codice cliente denominazione 
c00106         Paolo re
c00116         viglino arturo 
c00126         sellaro giuseppe
c00146         accusani fabio 
c00161         franconi srl 

Thank You

1
  • So, what happens when you run this code? Btw, you're defining the function populateForm() inside the success callback, but you're not actually calling it anywhere. Why are you defining that function at all, instead of just calling the code inside directly? Commented Jul 23, 2017 at 22:29

1 Answer 1

1

The aspect you are struggling with most is the attachment of populateForm as a click handler. As it stands, onclick='populateForm() won't work because populateForm would need to be a global member, and it's good practice not to pollute the global namespace.

To overcome this, click handling can be delegated to ancestor element of the buttons'; the <table> element is the most obvious choice. Fortunately, jQuery has a very convenient syntax for event delegation.

In addition, there is an issue you are probably not aware of; namely that multiple quick-fire AJAX requests will not necessarily respond in the expected order. On the assumption that order matters, a simple mechanism is available to ensure that table entries are in the expected order. All you need to do is :

  • when each AJAX request is made, synchronously append a <tbody> element.
  • keep a reference to each appended <tbody> element (in a closure).
  • when each AJAX responses is received, append rows to the appropriate <tbody> element.

Your code should be something like this :

$(function () {
    // Delegate handling of button.btn clicks to the containing table element. 
    // This avoids having to attach the same click handler repeatedly to buttons in dynamically generated lines.
    $("#tablesearch").on('click', 'button.btn', function() {
        $("#CodiceCliente").val($(this).closest('td').next('td').text());
    });

    $(".search-filter").keyup(function() {
        var codiceCliente = $(this).val();
        if (codiceCliente != '') {
            var $tbody = $('<tbody/>').appendTo("#tablesearch"); // Synchronously append a <tbody> to receive two asynchrously generated <tr>s (see below).
            $.ajax({
                'type': 'POST',
                'url': 'ajax_requests.php',
                'data': {
                    'request': 'get_codiceCliente_json',
                    'searchCliente': codiceCliente
                },
            }).then(function (result) {
                $("#result").css('display', "inline");
                $("<tr><th></th><th>Codice Cliente</th><th>Denominazione</th><th>Indirizzo</th><th>Città</th><th>CAP</th><th>Numero Telefono</th></tr>").appendTo($tbody); // append to the correct <tbody> for this response
                for (var i = 0; i < result.length; ++i) {
                    $("<tr><td><button class='btn'><i class='icon-search'></i></button></td><td>" + 
                    result[i].codiceCliente + "</td><td>" + 
                    result[i].denominazioneCliente + "</td><td>" + 
                    result[i].indirizzo + "</td><td>" + 
                    result[i].citta + "</td><td>" + 
                    result[i].CAP + "</td><td>" + 
                    result[i].numeroTelefono + "</td></tr>").appendTo($tbody); // append to the correct <tbody> for this response
                }
            }, function() {
                $tbody.remove(); // ajax failed so no point keeping the <tbody> element (unless you want to display an error message in the table)
            });
        }
    });
});
Sign up to request clarification or add additional context in comments.

3 Comments

Hi! Thank you for the help! I edited my code to be like your, it returns me this error whenever I click on a button: Uncaught ReferenceError: populateForm is not defined at HTMLButtonElement.onclick
That error will not occur if the button HTML does not include onclick="populateForm()". Make sure you are using my code in its entirety.
Also, I can't guarantee that the code is bug-free as I have tested it only for syntax errors. Be prepared to do some debugging.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.