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

Bind the prototype to the JavaScript object

Consider this scenario where I have JSON data containing person objects. [ { "name": "Alice", "age": 28, }, { "name": "Bob", "age": 33 } ] Upon parsing, an array with two JavaScript objects is obtained. Suppose I want to add a ...

Is Meteor.js the solution for time-triggered server requests?

We are currently in the process of developing an application that matches users from a database every Wednesday and Friday. How can we achieve this using Meteor? In the server code, I am considering organizing this functionality within a timedserver.js fi ...

Incorrect media type linked to Gmail API attachment error

I need help sending a message via the Gmail API in JavaScript, including a JPEG file attachment. My code so far looks like this: $.ajax({ type: "POST", url: "https://www.googleapis.com/upload/gmail/v1/users/me/messages/send?uploadType=multipart", he ...

Make the browser interpret XHR response as gzip encoding

I am currently working on a client-side JavaScript application that is responsible for downloading relatively large JSON datasets for visualization. My goal is to compress these datasets in advance using gzip to conserve space and decrease bandwidth consum ...

Leverage the Nuxeo client SDK with Angular 6 for seamless integration with RESTClient in

Looking to integrate the Nuxeo ClientSdk with my Angular 6 client to consume its REST API, but facing issues due to the lack of typescript definitions for this JavaScript package. Tried importing the library into my project using the following code snippe ...

How to retrieve a value from an Angular form control in an HTML file

I have a button that toggles between map view and list view <ion-content> <ion-segment #viewController (ionChange)="changeViewState($event)"> <ion-segment-button value="map"> <ion-label>Map</ion-label> & ...

Maintain modifications in AngularJS modal even after closure

I have an HTML file with some AngularJS code for a modal window. <div ng-controller="ModalDemoCtrl"> <script type="text/ng-template" id="myModalContent.html"> <div class="modal-header"> <h3>I'm a modal!</h3> ...

What is the best way to send variables from one page to another using jQuery or Javascript?

Is there a way to use POST with jQuery/Javascript to send data to another page and then redirect to that page? Instead of using GET... Using Javascript window.location = 'receivepage.php?variable='+testVariable; Once it's received by PHP ...

What is the correct way to use fitBounds and getBounds functions in react-leaflet?

I'm struggling with calling the fitBounds() function on my Leaflet map. My goal is to show multiple markers on the map and adjust the view accordingly (zoom in, zoom out, fly to, etc.). I came across an example on How do you call fitBounds() when usi ...

Hover over or click to automatically focus on the input field

I have an icon that triggers focus on an input field when hovered over. I also want the same functionality to occur when the user clicks on the icon. if(!mobile){ $('#search-icon').hover( function(){ if($('.sear ...

"Optimizing the Placement of jPlayer for Your Website

Struggling to properly position jPlayer on my webpage. After consulting jPlayer's documentation, I learned that it is supposed to be absolutely positioned by default. However, it seems to be flowing with the rest of the page content rather than being ...

Ways to engage with a fixed html page generated by an Express router?

Let me start by mentioning that I am relatively new to working with NodeJs. Currently, I am dealing with a situation where I need to render a static HTML web page (which includes JavaScript code) as a response to a post request. Below is the relevant snipp ...

Tips for sending a file rather than a json object in nextjs

Is there a way to send a file from either route.ts or page.ts, regardless of its location in the file-system? Currently, I am using the following code in my back-end python + flask... @app.route("/thumbnail/<string:filename>") def get_file ...

Syntax error is not caught - why are there invalid regular expression flags being used?

I'm attempting to dynamically create rows that, when clicked, load a view for the associated row. Check out my javascript and jquery code below: var newRow = $('<tr />'); var url = '@Url.Action("Get", "myController", new ...

Creating a dynamic input box that appears when another input box is being filled

I have a form set up like this: <FORM method="post"> <TABLE> <TR> <TD>Username</TD> <TD><INPUT type="text" value="" name="username" title="Enter Username"/><TD> </TR> <TR> <TD>A ...

Updating the status of a 2D array with N elements in React: A step-by-step guide

Before I dive into the topic, I must acknowledge that I have come across questions similar to this one before but was unable to find a solution on my own. Updating React state as a 2d array? Let's imagine this as my state object state = { graph ...

ACTUAL preventing a component from losing its focus

I have been exploring ways to effectively stop a DOM element from losing focus. While researching, I came across different solutions on StackOverflow such as: StackOverflow solution 1 StackOverflow solution 2 StackOverflow solution 3 However, these sol ...

Storing JSON strings in PHP differs from storing them in JavaScript

Using JavaScript, I can save a cookie using JSON.stringify(), which saves the cookie directly like this: '[{"n":"50fb0d0cc1277d182f000002","q":2},{"n":"50fb0d09c1277d182f000001","q":1},{"n":"50fb0d06c1277d182f000000","q":1}] Now, I am sending this t ...

Is there a way to prevent the window.status from appearing?

I currently have the following code snippet: <a class="button accessLink" id="loginLink" href="#" data-action="Login" data-dialog="access" data-disabled="false" data-entity="n/a" ...

AngularJS dynamic data presents challenge in reloading Jquery data tables

Hey there, I'm currently using jQuery DataTable with AngularJS. You can find the reference site here: https://codepen.io/kalaiselvan/pen/rLoVkE While it works fine for static data, I encounter issues when trying to bind data from a database. T ...