Ryan Cohan
Ryan Cohan

Reputation: 109

HTML Button click seems to call wrong function

I'm developing a web UI using bootstrap that calls a backend Java webservice to retrieve data from the database and display it in a table. I have a function that gets called as such:

<body onload="refreshVOI()">

This is working as expected. However, I also have a search button that shoots off another request with the search value as a parameter. For some reason, though, it seems that this button click is calling refreshVOI() again. See the snippets below:

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
var voiDataArray = [];

function makeHttpObject() {
    try {
        return new XMLHttpRequest();
    } catch (error) {
        alert("error");
    }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (error) {
        alert("error");
    }
    try {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } catch (error) {
        alert("error");
    }
    throw new Error("Could not create HTTP request object.");
}

function refreshVOI() {
    // Find a <table> element with id="VOITable":
    var VOITable = document.getElementById("VOITable");
    var tableRows = VOITable.getElementsByTagName('tr');
    var rowCount = VOITable.rows.length;
    console.log("Getting all alerts...");
    for (var r = 1; r < rowCount; r++) {
        VOITable.deleteRow(-1);
    }

    var request = makeHttpObject();
    var xmlDoc;
    var parser;
    var x, i;
    var vois, voi;
    request.open("GET", "http://localhost:8080/VehiclesOfInterestWebServices/webresources/model.vehicleofinterest", true);
    request.send();
    request.onreadystatechange = function () {

        if (request.readyState == 4)
        {
            console.log("data " + request.responseText.toString());
            parser = new DOMParser();
            vois = parser.parseFromString(request.responseText.toString(), "text/xml");
            voi = vois.documentElement.childNodes;

            for (i = 0; i < voi.length; i++)
            {
                var row = VOITable.insertRow(-1);

                // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
                var cell1 = row.insertCell(0);
                var cell2 = row.insertCell(1);
                var cell3 = row.insertCell(2);
                var cell4 = row.insertCell(3);
                var cell5 = row.insertCell(4);
                var cell6 = row.insertCell(5);
                var cell7 = row.insertCell(6);
                var cell8 = row.insertCell(7);

                // Add some text to the new cells:
                cell1.innerHTML = vois.getElementsByTagName("licensePlate")[i].childNodes[0].nodeValue;
                cell2.innerHTML = vois.getElementsByTagName("reason")[(i * 2) + 1].childNodes[0].nodeValue;
                cell3.innerHTML = vois.getElementsByTagName("make")[(i * 4) + 1].childNodes[0].nodeValue;
                cell4.innerHTML = vois.getElementsByTagName("model")[(i * 2) + 1].childNodes[0].nodeValue;
                cell5.innerHTML = vois.getElementsByTagName("vehYear")[i].childNodes[0].nodeValue;
                cell6.innerHTML = vois.getElementsByTagName("color")[i].childNodes[0].nodeValue;
                cell7.innerHTML = vois.getElementsByTagName("ownersName")[i].childNodes[0].nodeValue;
                cell8.innerHTML = vois.getElementsByTagName("ownersPhone")[i].childNodes[0].nodeValue;
            } // end of for loop
        }  // end of if statement
        request.close();

    }; // end of fucntion
} // end of refreshSales function

function searchVOI(search_val) {
    if (search_val.length > 0) {
        var form = document.getElementById('myInput');
        var search_val = form.elements.searchfield.value;
        console.log("Searching for VOI by license plate: " + search_val);
        // Find a <table> element with id="VOITable":
        var VOITable = document.getElementById("VOITable");
        var tableRows = VOITable.getElementsByTagName('tr');
        var rowCount = VOITable.rows.length;
        console.log("get table");
        for (var r = 1; r < rowCount; r++) {
            VOITable.deleteRow(-1);
        }

        var request = makeHttpObject();
        var xmlDoc;
        var parser;
        var x, i;
        var vois, voi;
        request.open("GET", "http://localhost:8080/VehiclesOfInterestWebServices/webresources/model.vehicleofinterest"+search_val, true);
        request.send();
        request.onreadystatechange = function () {

            if (request.readyState == 4)
            {
                console.log("data " + request.responseText.toString());
                parser = new DOMParser();
                vois = parser.parseFromString(request.responseText.toString(), "text/xml");
                voi = vois.documentElement.childNodes;

                for (i = 0; i < voi.length; i++)
                {
                    var row = VOITable.insertRow(-1);

                    // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
                    var cell1 = row.insertCell(0);
                    var cell2 = row.insertCell(1);
                    var cell3 = row.insertCell(2);
                    var cell4 = row.insertCell(3);
                    var cell5 = row.insertCell(4);
                    var cell6 = row.insertCell(5);
                    var cell7 = row.insertCell(6);
                    var cell8 = row.insertCell(7);

                    // Add some text to the new cells:
                    cell1.innerHTML = vois.getElementsByTagName("licensePlate")[i].childNodes[0].nodeValue;
                    cell2.innerHTML = vois.getElementsByTagName("reason")[(i * 2) + 1].childNodes[0].nodeValue;
                    cell3.innerHTML = vois.getElementsByTagName("make")[(i * 4) + 1].childNodes[0].nodeValue;
                    cell4.innerHTML = vois.getElementsByTagName("model")[(i * 2) + 1].childNodes[0].nodeValue;
                    cell5.innerHTML = vois.getElementsByTagName("vehYear")[i].childNodes[0].nodeValue;
                    cell6.innerHTML = vois.getElementsByTagName("color")[i].childNodes[0].nodeValue;
                    cell7.innerHTML = vois.getElementsByTagName("ownersName")[i].childNodes[0].nodeValue;
                    cell8.innerHTML = vois.getElementsByTagName("ownersPhone")[i].childNodes[0].nodeValue;
                } // end of for loop
            }  // end of if statement
            request.close();
        }; // end of fucntion
    }
}
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/* 
    Created on : Apr 20, 2020, 9:37:46 PM
    Author     : ryan
*/

body {
  padding: 0;
  margin: 0;
  background: #212121;
  color: #f5f5f5;
}
.table-dark {
    background: #212121;
}
.navbar {
    background: #424242;
}
.form-control {
    background: #424242;
    border: none;
    color: #212121;
}
.d-flex {
    margin-left: 10%;
    margin-right: 10%;
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>Vehicles of Interest</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="icon" 
              type="image/png" 
              href="assets/mdgov-fav-icon.png">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
        <script src="vehiclesOfInterest.js"></script>   
        <link rel="stylesheet" type="text/css" href="main.css"
    </head>

        <body onload="refreshVOI()">

            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <img src="./assets/mdgov-fav-icon.png" class="navbar-brand" href="#"></a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav mr-auto">
                        <li class="nav-item active">
                            <a class="nav-link" href="#" style="font-size: x-large">Dashboard<span class="sr-only">(current)</span></a>
                        </li>
                    </ul>
                    <form class="form-inline my-2 my-lg-0">
                        <input id="myInput" class="form-control form-control-md" type="search" placeholder="Search alerts..." aria-label="Search">
                        <button id="searchBtn" onclick="searchVOI()" class="btn btn-outline-info my-2 my-sm-0" type="submit">Search</button>
                    </form>
                </div>
            </nav>

            <br>
            <div class='d-flex justify-content-between'>
                <div>
                    <h2>Active Alerts</h2>
                </div>
                <div>
                    <div class='btn-group'>
                        <button onclick="refreshVOI()" type='button' class='btn btn-info'>Refresh</button>
                    </div>
                </div>
            </div>
            <br>
            <div class ="container container-fluid">
                <table class="table table-hover table-dark table-borderless" id="VOITable">
                    <thead>
                        <tr>
                            <th>License Plate</th>
                            <th>Reason</th>
                            <th>Make</th>
                            <th>Model</th>
                            <th>Year</th>
                            <th>Color</th>
                            <th>Owner</th>
                            <th>Owner Phone</th>
                        </tr>
                    </thead>
                    <tbody id="myTable" />
                </table>
            </div->
        </body>
</html>

For some reason, the page just seems to refresh and load all data as it does before. I don't see the log message from searchVOI() showing up in console at all. I'm wondering if refreshVOI() is being called somehow on button click and overwriting the search results.

Any help would be greatly appreciated!!!

Upvotes: 0

Views: 269

Answers (1)

Atul Rajput
Atul Rajput

Reputation: 4178

Your problem was related to page refresh on search button click as it was a submit type button, as you are calling a function on it, so you need to make it button type="button" not submit, just check if this is what you want.

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
var voiDataArray = [];

function makeHttpObject() {
    try {
        return new XMLHttpRequest();
    } catch (error) {
        alert("error");
    }
    try {
        return new ActiveXObject("Msxml2.XMLHTTP");
    } catch (error) {
        alert("error");
    }
    try {
        return new ActiveXObject("Microsoft.XMLHTTP");
    } catch (error) {
        alert("error");
    }
    throw new Error("Could not create HTTP request object.");
}

function refreshVOI() {
    // Find a <table> element with id="VOITable":
    var VOITable = document.getElementById("VOITable");
    var tableRows = VOITable.getElementsByTagName('tr');
    var rowCount = VOITable.rows.length;
    console.log("Getting all alerts...");
    for (var r = 1; r < rowCount; r++) {
        VOITable.deleteRow(-1);
    }

    var request = makeHttpObject();
    var xmlDoc;
    var parser;
    var x, i;
    var vois, voi;
    request.open("GET", "http://localhost:8080/VehiclesOfInterestWebServices/webresources/model.vehicleofinterest", true);
    request.send();
    request.onreadystatechange = function () {

        if (request.readyState == 4)
        {
            console.log("data " + request.responseText.toString());
            parser = new DOMParser();
            vois = parser.parseFromString(request.responseText.toString(), "text/xml");
            voi = vois.documentElement.childNodes;

            for (i = 0; i < voi.length; i++)
            {
                var row = VOITable.insertRow(-1);

                // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
                var cell1 = row.insertCell(0);
                var cell2 = row.insertCell(1);
                var cell3 = row.insertCell(2);
                var cell4 = row.insertCell(3);
                var cell5 = row.insertCell(4);
                var cell6 = row.insertCell(5);
                var cell7 = row.insertCell(6);
                var cell8 = row.insertCell(7);

                // Add some text to the new cells:
                cell1.innerHTML = vois.getElementsByTagName("licensePlate")[i].childNodes[0].nodeValue;
                cell2.innerHTML = vois.getElementsByTagName("reason")[(i * 2) + 1].childNodes[0].nodeValue;
                cell3.innerHTML = vois.getElementsByTagName("make")[(i * 4) + 1].childNodes[0].nodeValue;
                cell4.innerHTML = vois.getElementsByTagName("model")[(i * 2) + 1].childNodes[0].nodeValue;
                cell5.innerHTML = vois.getElementsByTagName("vehYear")[i].childNodes[0].nodeValue;
                cell6.innerHTML = vois.getElementsByTagName("color")[i].childNodes[0].nodeValue;
                cell7.innerHTML = vois.getElementsByTagName("ownersName")[i].childNodes[0].nodeValue;
                cell8.innerHTML = vois.getElementsByTagName("ownersPhone")[i].childNodes[0].nodeValue;
            } // end of for loop
        }  // end of if statement
        request.close();

    }; // end of fucntion
} // end of refreshSales function

function searchVOI(search_val) {
    if (search_val.length > 0) {
        var form = document.getElementById('myInput');
        var search_val = form.elements.searchfield.value;
        console.log("Searching for VOI by license plate: " + search_val);
        // Find a <table> element with id="VOITable":
        var VOITable = document.getElementById("VOITable");
        var tableRows = VOITable.getElementsByTagName('tr');
        var rowCount = VOITable.rows.length;
        console.log("get table");
        for (var r = 1; r < rowCount; r++) {
            VOITable.deleteRow(-1);
        }

        var request = makeHttpObject();
        var xmlDoc;
        var parser;
        var x, i;
        var vois, voi;
        request.open("GET", "http://localhost:8080/VehiclesOfInterestWebServices/webresources/model.vehicleofinterest"+search_val, true);
        request.send();
        request.onreadystatechange = function () {

            if (request.readyState == 4)
            {
                console.log("data " + request.responseText.toString());
                parser = new DOMParser();
                vois = parser.parseFromString(request.responseText.toString(), "text/xml");
                voi = vois.documentElement.childNodes;

                for (i = 0; i < voi.length; i++)
                {
                    var row = VOITable.insertRow(-1);

                    // Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
                    var cell1 = row.insertCell(0);
                    var cell2 = row.insertCell(1);
                    var cell3 = row.insertCell(2);
                    var cell4 = row.insertCell(3);
                    var cell5 = row.insertCell(4);
                    var cell6 = row.insertCell(5);
                    var cell7 = row.insertCell(6);
                    var cell8 = row.insertCell(7);

                    // Add some text to the new cells:
                    cell1.innerHTML = vois.getElementsByTagName("licensePlate")[i].childNodes[0].nodeValue;
                    cell2.innerHTML = vois.getElementsByTagName("reason")[(i * 2) + 1].childNodes[0].nodeValue;
                    cell3.innerHTML = vois.getElementsByTagName("make")[(i * 4) + 1].childNodes[0].nodeValue;
                    cell4.innerHTML = vois.getElementsByTagName("model")[(i * 2) + 1].childNodes[0].nodeValue;
                    cell5.innerHTML = vois.getElementsByTagName("vehYear")[i].childNodes[0].nodeValue;
                    cell6.innerHTML = vois.getElementsByTagName("color")[i].childNodes[0].nodeValue;
                    cell7.innerHTML = vois.getElementsByTagName("ownersName")[i].childNodes[0].nodeValue;
                    cell8.innerHTML = vois.getElementsByTagName("ownersPhone")[i].childNodes[0].nodeValue;
                } // end of for loop
            }  // end of if statement
            request.close();
        }; // end of fucntion
    }
}
/*
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
*/
/* 
    Created on : Apr 20, 2020, 9:37:46 PM
    Author     : ryan
*/

body {
  padding: 0;
  margin: 0;
  background: #212121;
  color: #f5f5f5;
}
.table-dark {
    background: #212121;
}
.navbar {
    background: #424242;
}
.form-control {
    background: #424242;
    border: none;
    color: #212121;
}
.d-flex {
    margin-left: 10%;
    margin-right: 10%;
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
    <head>
        <title>Vehicles of Interest</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="icon" 
              type="image/png" 
              href="assets/mdgov-fav-icon.png">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
        <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script>
        <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script>
        <script src="vehiclesOfInterest.js"></script>   
        <link rel="stylesheet" type="text/css" href="main.css"
    </head>

        <body onload="refreshVOI()">

            <nav class="navbar navbar-expand-lg navbar-dark bg-dark">
                <img src="./assets/mdgov-fav-icon.png" class="navbar-brand" href="#"></a>
                <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <ul class="navbar-nav mr-auto">
                        <li class="nav-item active">
                            <a class="nav-link" href="#" style="font-size: x-large">Dashboard<span class="sr-only">(current)</span></a>
                        </li>
                    </ul>
                    <form class="form-inline my-2 my-lg-0">
                        <input id="myInput" class="form-control form-control-md" type="search" placeholder="Search alerts..." aria-label="Search">
                        <button id="searchBtn" onclick="searchVOI()" class="btn btn-outline-info my-2 my-sm-0" type="button">Search</button>
                    </form>
                </div>
            </nav>

            <br>
            <div class='d-flex justify-content-between'>
                <div>
                    <h2>Active Alerts</h2>
                </div>
                <div>
                    <div class='btn-group'>
                        <button onclick="refreshVOI()" type='button' class='btn btn-info'>Refresh</button>
                    </div>
                </div>
            </div>
            <br>
            <div class ="container container-fluid">
                <table class="table table-hover table-dark table-borderless" id="VOITable">
                    <thead>
                        <tr>
                            <th>License Plate</th>
                            <th>Reason</th>
                            <th>Make</th>
                            <th>Model</th>
                            <th>Year</th>
                            <th>Color</th>
                            <th>Owner</th>
                            <th>Owner Phone</th>
                        </tr>
                    </thead>
                    <tbody id="myTable" />
                </table>
            </div->
        </body>
</html>

Upvotes: 1

Related Questions