Utilize AJAX to retrieve data in JavaScript without the need for an "onClick function"

Looking for a way to retrieve data using AJAX without an onclick function? Most examples I found use the onclick function. Here is an HTML example where I successfully retrieved data using an onclick function.

<!doctype html>
<html lang="en">
<head>
   <meta charset="utf-8" />
   <title>New document</title>

   <script type = 'text/javascript' src='js/jquery-2.2.0.js'></script>

<script type ='text/javascript' src='js/testScript.js'></script>

<?php
include_once("database_conn_getOffers.php");
?>
</head>
<body>
   content goes here
   <aside id="offer" onclick ="loadDoc('getData.php',myFunction)">
        &nbsp; click here
        </aside>
</body>

here is the script

function loadDoc(url, cFunction) {
  var xhttp;
  xhttp=new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      cFunction(this);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
function myFunction(xhttp) {
  document.getElementById("offer").innerHTML =
  xhttp.responseText;
}

Now, instead of using the onclick function, I want the data to be displayed when the HTML page is opened. Can someone guide me on how to achieve this?

Answer №1

There is no need for body onload. You can simply utilize the window.onload function in JavaScript.

JavaScript

window.onload = function() {
  loadDoc('fetchData.php',myFunc)
};

Answer №2

To execute the function in a different location, you simply need to invoke it elsewhere. One method is to trigger it when the window has finished loading.

window.onload = loadDocument('fetchData.php',displayResults)

Answer №3

One way to implement this is by utilizing

<body onload="loadDoc('fetchData.php',executeFunction);">

Answer №4

Another potential fix is incorporating a fresh DOMContentLoaded event to dispatch the query once the browser finishes rendering the page.

An example implementation would look like:

document.addEventListener('DOMContentLoaded', sendRequest);

Answer №5

Your ajax call is currently bound to the onclick event, but you actually want it to happen on page load. To fix this, simply change the attribute from onclick to onload.

<!doctype html>
<html lang="en">
<head>
   <meta charset="utf-8" />
   <title>New document</title>

   <script type = 'text/javascript' src='js/jquery-2.2.0.js'></script>

   <script type ='text/javascript' src='js/testScript.js'></script>

<?php
include_once("database_conn_getOffers.php");
?>
</head>
<body>
  content goes here
   <aside id="offer" onload ="loadDoc('getData.php',myFunction)">
    &nbsp; click here
   </aside>
</body>

Answer №6

Here is a code snippet that should work well if it's on the same domain:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html lang="en">
<head>
   <meta charset="utf-8" />
   <title>New document</title>

   <script type = 'text/javascript' src='js/jquery-2.2.0.js'></script>

<script type ='text/javascript' src='js/testScript.js'></script>
<script type ='text/javascript'>
$(document).ready(function(){
$( "#offer" ).load( 'getData.php' );
});
</script>

<?php
include_once("database_conn_getOffers.php");
?>
</head>
<body>
   content goes here
   <aside id="offer" >
        &nbsp; click here
        </aside>
</body>

Answer №7

Opt for calling your function within the window.onload event rather than using onclick

<!doctype html>
<html lang="en">
<head>
   <meta charset="utf-8" />
   <title>New document</title>

   <script type = 'text/javascript' src='js/jquery-2.2.0.js'></script>

<script type ='text/javascript' src='js/testScript.js'></script>

<?php
include_once("database_conn_getOffers.php");
?>
</head>
<body>
   content goes here
   <aside id="offer">
        Your function has been executed onload of document
        </aside>
</body>

This is the provided script:

window.onload = function loadDoc(url, cFunction) {
  var xhttp;
  xhttp=new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      cFunction(this);
    }
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
function myFunction(xhttp) {
  document.getElementById("offer").innerHTML =
  xhttp.responseText;

};

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

Can Fields Be Concealed Based on the User's Choice?

Can options be dynamically hidden in a select field based on user input using Javascript or jQuery? I am working on a complex and lengthy form and I'm trying to minimize the number of HTML elements to avoid confusion with conditional logic. The user ...

No default export function available on this page

Recently delving into Nextjs, I'm currently in the process of setting up a MongoDB connection using middleware configuration. Let me showcase my code: import type { NextApiRequest, NextApiResponse } from 'next' import { connectMongoDB } fro ...

What is the correct way to specify the type in my functional component?

I was trying to define the type in my component in a different way, I know it can be done using classes but is there a way to achieve this with functional components without exporting the interface? Despite my extensive research, I couldn't find any r ...

Transmitting data via POST method within datatables ajax call

I am facing an issue while attempting to execute a simple ajax call in datatables that relies on a post array of IDs from a form on a previous page. The error I encounter is: Invalid JSON Response This indicates that the JSON array being returned may be ...

Strategies for Dynamically Updating Django ChoiceField Options Based on Another ChoiceField's Selection

I have a Django form that includes fields for the user's country and state or region. The form presents a list of countries in a ChoiceField named 'country' using a Select widget, which is pre-populated from a specified list. If the user sel ...

Tips for implementing resizable Material-UI Dialogs

I'm working on a project that involves creating a dialog box that can be resized and dragged. While I found steps in the Material-UI Dialog documentation on how to make it draggable, I'm still looking for information on how to make it resizable. ...

Enter a keyword in the search bar to find what you're looking

I am working on a form where users can select their occupation from a list that is stored in a separate .js file. The list includes various occupations like 'AA Patrolman' and 'Abattoir Inspector'. var occupationSelect = "<select id ...

What is the best way to customize multiple checkboxes in React Native?

I need help with implementing checkboxes in my app using react-native-check-box. I have tried creating 4 checkboxes, but the text inside them is not aligning properly. The boxes are rendering one above the other instead of staying on the same line. I want ...

Tips for patiently waiting for a function that is filled with promises

Consider the following function: const getData = () => { foo() .then(result => { return result; }) .catch(error => { return error; }); }; Even though getData does not directly return a promise, it internally handles asynchro ...

Ways to append a number to the start or end of an array using JavaScript

Can you help me figure out why the function to order the "s" array from minor to major is adding the number at the end instead of the beginning? The if statement seems to be true (2 < 7 = true) but the logic is not working as expected. Any advice on how ...

How can I clear the div styling once the onDismiss handler has been triggered

Seeking assistance with resetting a div on a Modal after it has been closed. The issue I am facing with my pop-up is that the div retains the previous styling of display: none instead of reverting to display: flex. I have searched for a solution without su ...

Achieving both positive and negative styling in AngularJS with ng-class: A guide

I'm currently working on an application that requires indicating red for negative values and blue for positive values in a calculation. <td class="amount debit"> <input type="text" class="form-control" ng-model="vm.model.form.amount_debi ...

Receiving a null value in Action after an AJAX call in Struts 2

I have been working on sending AJAX requests to an Action in which I send a parameter from a JSP page. The issue I am facing is that my Action class receives the Ajax request, but the params being sent with the AJAX call are showing as null in the Action c ...

Ensuring proper functionality of "if else" statements in my Node file through Inquirer: a step-by-step guide

I am currently working on a code script to display a specific message on the screen based on the user's response to a question. The code is implemented in a node application using the Inquirer package. However, whenever the node application is execute ...

Unexpected date outcomes in JavaScript when using a similar date format

Why is it that the first input produces the correct result, while the second input displays a time that is 5 hours behind? new Date("2000-1-1") Sat Jan 01 2000 00:00:00 GMT-0500 (EST) new Date("2000-01-01") Fri Dec 31 1999 19:00:00 GMT-0500 (EST) How can ...

The code that functions properly in Internet Explorer and Chrome is not functioning as expected in Firefox

I created a jQuery function that is designed to allow only numbers and one decimal point in an input field of type text. While it works perfectly fine in Internet Explorer and Chrome, I've encountered an issue with Firefox where it doesn't seem ...

JavaScript and DOM element removal: Even after the element is removed visually, it still remains in the traversal

Our goal is to enable users to drag and drop items from a source list on the left to a destination list on the right, where they can add or remove items. The changes made to the list on the right are saved automatically. However, we are encountering an iss ...

The functionality to open the menu by clicking is experiencing issues

I'm attempting to replicate the Apple website layout. HTML structure: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" conte ...

Try utilizing querySelectorAll() to target the second item in the list

As I delve into the world of HTML and JS, I came across the document.querySelectorAll() API. It allows me to target document.querySelectorAll('#example-container li:first-child'); to select the first child within a list with the ID 'exampl ...

The Vue BlogCards Component is missing from the display

My web app is designed to display blog posts in a grid layout. However, the BlogCards component in the Home.vue file is not showing any content as expected. The data is stored in firebase, and when I navigate to /blogs, I can see the blogs displayed in a g ...