The body onload function fails to run upon the page loading

I'm having trouble with my body onload function not executing. When I load the page, I want to display all records that are selected in the drop_1 dropdown and equal to ALL. I have a script that sends values q and p to getuser.php. The values sent are from the drop_1 and tier_two dropdowns.

Combobox.php

        <script type="text/javascript">
$(document).ready(function() {
    $('#wait_1').hide();
    $('#drop_1').change(function(){
            if( $(this).val() == "ALL") {
            $("#wait_1").hide();
            $("#result_1").hide();
        }else{
      $('#wait_1').show();
      $('#result_1').hide();
      $.get("func.php", {
        func: "drop_1",
        drop_var: $('#drop_1').val()
      }, function(response){
        $('#result_1').fadeOut();
        setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
      });
      }
        return false;
    });
});

function finishAjax(id, response) {
  $('#wait_1').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
}
</script>

  <script> // AJAX Implementation
    function showUser() {
        str = document.getElementById("drop_1").value;
        str1 = document.getElementById("tier_two").value;
        if (str == "" || (str != "ALL" && str1 == "")) {
            document.getElementById("txtHint").innerHTML = "";
            return;
        }
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET", "getuser.php?q=" + str + "&p=" + str1, true);
        xmlhttp.send();
    }
    </script>
    <body>

<?php include('func.php'); ?>
<select name="drop_1" id="drop_1" onchange="showUser(this.value)" style="overflow:scroll;width:100px;">
        <option value="ALL" selected='ALL'>ALL</option>
        <?php getTierOne(); ?>
</select>

    <span id="wait_1" style="display: none;">
    <img alt="Please Wait" src="ajax-loader.gif" width="15px" height="15px"/>
    </span>
    <span id="result_1" style="display: none;"></span>
<div id="txtHint"></div>

    <script>
        showUser();
    </script>

func.php

<?php

function getTierOne()
{
    $mysqli = new mysqli("localhost", "root", "", "app");
    $result = $mysqli->query("SELECT * FROM app GROUP BY app_cn ORDER BY app_cn");
     while($row = $result->fetch_assoc())
        {
           echo '<option value="'.$row['app_cn'].'">'.$row['app_cn'].'</option>';
        }
}

if($_GET['func'] == "drop_1" && isset($_GET['func'])) {
   drop_1($_GET['drop_var']); 
}

function drop_1($drop_var)
{
    $mysqli = new mysqli("localhost", "root", "", "app");
    $results = $mysqli->query("SELECT * FROM app WHERE app_cn='$drop_var' GROUP BY app_plan_no ORDER BY app_plan_no");

    echo '<select name="tier_two" id="tier_two" onchange="showUser()">
          <option value=" " disabled="disabled" selected="selected">Choose one</option>';

          while($drop_2 = $results->fetch_assoc())
            {
            if($drop_2['app_plan_no'] != '')
            {
              echo '<option value="'.$drop_2['app_plan_no'].'">'.$drop_2['app_plan_no'].'</option>';
            }
            }
    echo '</select> ';
}
?>

Getuser.php

$mysqli = new mysqli("localhost", "root", "", "app");
$p = $_GET['p'];
$q = $_GET['q'];
$where = '';
if ( $q != 'ALL') {
    $where = " WHERE app_cn='$q' AND app_plan_no='$p'  ";
$result1 = $mysqli->query("
    SELECT *
    FROM app 
    $where 
    GROUP BY counter
")or die(mysqli_error());
echo'<table>'
........

Answer №1

In case the showUser() function isn't executing once the page is fully loaded, you can ensure it gets called by placing it within the document.ready() callback.

Answer №2

To effectively run your javascript function, you have two options: either insert it into the <body> tag

<body onLoad="executeFunction();">

or include it in your

<script type="text/javascript">
within the <head> tag.

window.onload = executeFunction();

At this moment, you don't have either of these setups except for a random call outside of your body. This could be causing another issue, so make sure to keep all relevant content inside your body tag.

Answer №3

Modify this section:

<script>
    showUser();
</script>

to the following:

<script>
    function addListener(event, obj, fn) {
        if (obj.addEventListener) {
            obj.addEventListener(event, fn, false);   // modern browsers
        } else {
            obj.attachEvent("on"+event, fn);          // older versions of IE
        }
    }

    addListener('load', window, showUser);
</script>

Additionally, include a console.log statement in your function to verify if it is being called. You can use something like this:

function showUser() {
    console.log('Function showUser() was called!!');

Check the browser console such as firebug or other tools.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the process for populating a checkbox with data from a configuration file using JavaScript?

I have a requirement where I need to populate a list of checkboxes with data from a configuration file. To elaborate, if my checkboxes are meant to select sports, within my JSON configuration file I have an array like this: sports: ["Tennis", "Rugby", "S ...

The issue with displaying inline block is that the divs are not appearing side by side on the

Two of my div elements, namely form-panel and data-panel, are currently not aligned on the same line. How can I use display:inline-block to align them in a single line? Please review the code provided below. I have already used display:inline-block on both ...

Storing user information in Angular after login and implementing JWT authentication

Is it advisable to save any user information other than JWT in local storage or cookies after a successful login? (The user profile object is already saved and encrypted in the JWT payload sub-part.) I need the user profile object ready before initializing ...

Do you require assistance with creating an image slideshow?

My first day working with HTML was a success as I successfully built a navigation bar that looks pretty cool. Take a look at it here. Next on my list is to incorporate a slideshow into my site, possibly using JavaScript or jQuery plugins. I'm aiming ...

Accessing data from arrays asynchronously using JavaScript

Update I have included actual code below, in addition to the concept provided earlier. Here is the async array access structure I am trying to implement: for (p = 0; p < myList.length ; p++){ for (k = 0; k < RequestList.length; k++){ i ...

Creating a new route in a Express JS server to specifically handle POST requests

Just starting to learn the ropes of Javascript, and I'm diving into express to create an application that will enable users to craft new recipes, explore existing ones, and view details about each recipe. To get things moving, I've launched my s ...

Enter key not triggering submission in jQuery UI autocomplete field

I'm currently working on implementing the autocomplete feature following a tutorial, and while it's functioning, I'm facing an issue with submitting the form when the user selects an item and hits enter. Below is the Coffeescript code that I ...

Using Sequelize to send data from the client-side to the server-side

I am currently developing a project for a fictional library database and website interface. I am facing an issue where only 2 out of the 4 new loan form inputs are being passed to the req.body. Even though all items have a name attribute, it seems like onl ...

Group a set of x elements together within a div, and then group a distinct number of elements together after every x-grouping

Is there a way to achieve a looping structure like this? For instance: Group every 2 divs into a new div, then (after every 2nd grouping) group every 3 divs together <div id="container"> <div></div> <div></div> ... </div& ...

Getting a URL to redirect after a successful login via an AJAX request in PHP

I've been trying to figure out how to redirect the URL after a successful login using an Ajax call in PHP. Can someone please review my code and point out any mistakes? Here is the content of the registration.php file located at http://localhost:8080 ...

Is there a way to remove a value from the search bar while updating the table at the same time?

Although I can successfully search the table based on the values in my search bar, I am having trouble with updating the state when deleting a value. To see my code in action, check out my sandbox here. ...

The jQuery serialize function encounters issues when used with Ajax in IE9

function getTime(){ var timestamp = new Date(); return timestamp.getTime(); } function displayValues() { var values = ($("#this").serialize()); $("#results").text(values); } $(":checkbox, :radio").click(displayValues); ...

Custom properties of an object are being erased when converting to JSON format within the canvas

I am working on a canvas project that involves multiple image objects, each with custom attributes. My goal is to save this canvas as a json object in a database, but the conversion process seems to strip away the custom attributes. Currently, I am using t ...

How can I combine multiple styles using Material-UI themes in TypeScript?

There are two different styles implementations in my code. The first one is located in global.ts: const globalStyles = (theme: Theme) => { return { g: { marginRight: theme.spacing(40), }, } } export const mergedStyle = (params: any) ...

calculating the duration between successive PHP form submissions

I am trying to calculate the duration between when a user submits a PHP form and when they submit it again. The form reloads on the same page, essentially refreshing it. Additionally, the user may enter the same data again. I want the timer to start runnin ...

Is there a method to automatically execute an 'onchange' function whenever a value is updated due to an AJAX response?

Many drop down menus are present on my page; <... onchange="callthisfunction(...)"...> While a manual change easily triggers the function, using ajax to load saved data does not register the value as changed and the function is not triggered. Is th ...

Why isn't it possible to send POST data to a JSON file using JQuery/AJAX?

I'm currently learning how to use JQuery/Ajax from a helpful tutorial on YouTube. To watch the video, simply click here. While I can successfully retrieve data from the order.json file, I encounter an error whenever trying to send POST requests. Bel ...

Tips for incorporating the "define" function into your Mocha testing

Starting my journey with JavaScript testing, I made the decision to use Mocha. The specific modules I am looking to test are AMD/RequireJS. However, it appears that Mocha only works with CommonJS modules. Consequently, when trying to run it, I encounter t ...

Creating a network of communication between API routes in NextJS

Can the fetch API be used within an API route in NextJs? I have a large handler and instead of having everything in one handler, I'd like to modularize it so that after completing a specific task (e.g., writing to a database), I can call another handl ...

Is it possible to determine if a selected date falls within the current week using JavaScript?

Currently facing an issue with JavaScript. I have multiple dates retrieved from a database, and I need to extract the date that falls within the current week. ...