When I use AJAX to load a PHP file, the function's content returns as [object HTMLDivElement]

Hello there,

When I use AJAX to load a PHP file, the content of my function returns [object HTMLDivElement], but if I load my function without loading the PHP file, it displays normally.

index.php

    <h1>API Football</h1>
    <nav>
      <ul>
        <li>INDEX</li>
        <li onclick="loadComponents()">Live fixtures</li>
      </ul>
    </nav>

    <h2>Live fixtures</h2>
    <div id="content">
    </div>

    <script src="javascript.js"></script>

javascript.js

var data = null;

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
    if (this.readyState === this.DONE) {

        let liveFixtures = this.responseText;
        let fixtures = liveFixtures.api.fixtures;
        let content = "";

        for (fixture of fixtures) {
            content += "<tr>";
            content += "<td>"+fixture.fixture_id+"</td>";
            content += "<td>"+fixture.homeTeam.team_name+" - "+fixture.awayTeam.team_name+"</td>";
            content += "</tr>";
        }

    }
});

xhr.open("GET", "https://api-football-v1.p.rapidapi.com/fixtures/live?timezone=Europe%2FLondon");
xhr.setRequestHeader("x-rapidapi-host", "api-football-v1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "e8118d13f1msh0edd004389b2d85p1b89c2jsn0cd40324ddec");

xhr.send(data);

//Load content.php
function loadComponents() {
  var xhttp = new XMLHttpRequest();

  xhttp.onreadystatechange = function() {

    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("content").innerHTML = this.responseText;
      document.getElementById("myDiv").innerHTML = content;
    }
  };
  xhttp.open("GET", "content.php", true);
  xhttp.send();
}

content.php

<div id="myDiv">
</div>
<p><strong>I loaded the content.php</strong></p>

Also available on .

Output from API Football

//let liveFixtures = {"api":{"results":18,"fixtures":[{"fixture_id":95187,"league_id":358,"league":{"name":"Serie B","country":"Brazil","logo":"https:\/\/media.api-football.com\/leagues\/358.PNG","flag":"https:\/\/media.api-football.com\/flags\/br.svg"},"event_date":"2019-11-08T22:15:00+00:00","event_timestamp":1573251300,"firstHalfStart":1573251300,"secondHalfStart":1573254900,"round":"Regular Season - 34","status":"Second Half","statusShort":"2H","elapsed":90,"venue":"Durival Britto e Silva, Curitiba","referee":null,"homeTeam":{"team_id":122,"team_name":"Parana","logo":"https:\/\/media.api-football.com\/teams\/122.png"},"awayTeam...

Answer №1

When using the

document.getElementById("myDiv").innerHTML = content;
function, it's important to note that you must define the content variable within the same function scope. If not, the JavaScript engine will search for a matching variable in the global scope. In this case, the global variable created implicitly by the existence of <div id="content"> is treated as an HTML element object rather than a string.

As content is an object, it will be converted to a string using the element's toString() method, which defaults to "[object HTMLDivElement]".

If you want a different value for content, make sure to define it properly in your code.

It's worth noting that you may have defined a content variable with let in another function scope, particularly if that function is asynchronous. For more information on handling asynchronous calls, check out this helpful resource: How do I return the response from an asynchronous call?

Answer №2

Directly loading data into Div using getAjax

function fetchData() {
let information = null;
let request = new XMLHttpRequest();
request.withCredentials = true;
request.addEventListener("readystatechange", function () {
    if (this.readyState === this.DONE) {
        console.log(this.responseText);
        let content = this.responseText;
        document.getElementById("getAjax").innerHTML = content;
    }
});
request.open("GET", "https://api-football-v1.p.rapidapi.com/v2/fixtures/live?timezone=Europe%2FLondon");
request.setRequestHeader("x-rapidapi-host", "api-football-v1.p.rapidapi.com");
request.setRequestHeader("x-rapidapi-key", "e8118d13f1msh0edd004389b2d85p1b89c2jsn0cd40324ddec");
request.send(information);
};

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

Looping through nested arrays in an array of objects with Angular's ng-repeat

I'm struggling to access an array within an array of objects in my AngularJS project. Here's the HTML: <li ng-repeat="ai in main.a2"> <div np-repeat="bi in ai.b"> <span ng-bind="bi"></span>b2 </div> </l ...

AngularJS - ng-repeat not updating when property array changes

I have a loop in my HTML using ng-repeat: <div class="row"> <div ng-repeat="item in model.painel track by item.codigoIncidente"> <strong>{{item.restante.horaMinutoSegundo}}</strong> </div> </div> In ...

Can you share a method in javascript that extracts href= and title values, similar to PHP's preg_match_all() function?

I received an HTML string as :var code; I am looking to retrieve all the values of href and title similar to how it is done using PHP's preg_match_all(). I have achieved a similar task in PHP with the provided example but now I am curious about how I ...

Easy jQuery Mobile and AJAX login solution

My current project involves creating a mobile app with user login capabilities using PhoneGap, jQuery Mobile, AJAX, and PHP. I am starting with a basic HTML and PHP structure as I am not an experienced programmer, but even my simple user login form is not ...

Developing a personalized logging service in NestJs: capturing logs without directly outputting them

I am currently working on developing a NestJs service that will enhance a Logger. However, I am facing issues with achieving the desired output (e.g., super.warn(); see below for more details). I have followed a tutorial from the nestjs site, but unfortuna ...

Using Node.js to implement GET, POST, and DELETE functionalities

I have embarked on the journey of learning Node.js and I find myself in a state of confusion. Could you please guide me on how to construct effective HTTP requests for the following scenarios: 1) Retrieve all galleries from the gallerySchema using a GET ...

Unclear reference to subscript by utilizing [indexPath.section][indexPath.row]

Upon updating to Xcode 7.2, an error message appeared indicating "Ambiguous use of subscript" in the code snippet below: func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableVie ...

Running several AJAX requests concurrently

I'm currently developing a Magento website and encountered an issue with the ajax cart feature. The problem is that only one request can be processed at a time, so if one product is being added to the cart, you can't add another simultaneously wi ...

Navigate to specific element from bootstrap navigation bar

I am in the process of creating a website for a small organization. The website is being constructed using bootstrap 4, and there is a navbar that connects to various flex-containers. I want these connections to smoothly scroll to their respective elements ...

Executing a function following the removal of an element

I am trying to remove an element after exiting a jQuery dialog. I have used the .remove() function, but the element is not accessible after executing .remove(). How can I "destroy" an object in JavaScript and allow it to be called again without refreshing ...

RadScheduler refresh rate

Currently I am incorporating RadScheduler into my project. The scheduler requires a regular update, so I have implemented a JavaScript function with an interval to call rebind() on the RadScheduler every 60 seconds. However, an issue arises when the user o ...

What is the reason behind my inability to console log the listening on port 3005?

I recently created a Node/Express API to connect to a PostgreSQL database. After setting up the configuration in index.js: const app = require('./src/app'); const pool = require('./src/pool'); pool.connect({ host: 'locahost&apos ...

Knockout JS: Choosing specific dropdown elements

My array doorsForSite contains a list of doors, each with its own set of schedules. Here is how it looks: var scheduleList = new[] { new { ScheduleId = "Schedule1",ScheduleName = "Always On" }, new ...

Positives and negatives images for accordion menu

I have successfully created an accordion list using HTML, CSS, and JavaScript. However, I would like to enhance it by adding a plus and minus picture in the left corner of the heading. Is there a way to achieve this functionality? I have two images that I ...

submitting a form including a file through ajax communication

For the past two weeks, I've been trying to find a solution to my unique problem. I've created a custom form that I need to upload along with one or more files. Our backend is running ruby on Rails, and the data must be formatted into a specific ...

Keep a vigilant eye on the peak utilization of memory within the Node.js process

I am in search of a way to effectively monitor the maximum memory usage in a Node.js process, regardless of whether there are memory leaks or not. The processes in question include both real applications and synthetic tests. My expectation is that it sho ...

Exclude certain packages from being processed in webpack

After setting up my webpack configuration, everything was running smoothly with the specified packages in the package.json: { "peerDependencies": { "react": "16.13.1", "react-dom": "16.13.1", ...

Tips for incorporating your personal touch while utilizing Snipcart

I have created an ecommerce platform with GatsbyJS and Snipcart, but I am struggling to override the default theme provided by Snipcart. When I try to change the main default CSS through gatsby-config.js, it does not seem to work. Does anyone have a soluti ...

The importance of utilizing local variables to securely store values passed from an Ajax call to a WCF method

Currently, I am experimenting with WCF and Jquery ajax for testing purposes. Although I am new to WCF, I encountered a problem with my "ProductsService" service that has four parameters being invoked from Jquery Ajax. Fortunately, I was able to resolve the ...

Context Provider executing SetInterval twice

For some reason, the below code in global.js is running twice when I run my react app, but I can't figure out why. I have used setInterval to test, and the intervals are always running two times. Perhaps I am not initializing correctly. Even after rem ...