The unusual interactions between JavaScript and QML

Encountering strange behavior with JavaScript. I am currently working on a basic example application using QT-QML and JavaScript.
Within this application, I have implemented HTTP Requests triggered by a button that sends the request through JavaScript.

Upon receiving the response from the HTTP request in the callback function, I attempt to check the state of the HTTP response in the following manner.

if( httpReq.readyState == 4 ) //Issue
{   
    if(httpReq.status == 200 )
    {
           ...

I aim to verify if readyState equals 4 (where 4 indicates completion)
However, the conditions fail to evaluate properly, always returning true regardless of the value of readyState.
For instance, even if readyState is 0 (0 == 4), the if statement still evaluates as TRUE which should not be the case.
What could be causing this unexpected behavior?

I have attempted the following:

 1. if( parseInt(httpReq.readyState) == 4 ) 
 2. if( Number(httpReq.readyState) == 4 )  
 3. if( httpReq.readyState == '4' )  

The above conditions yield the same results, evaluating to TRUE regardless of the actual value of readyState.
Could there possibly be an issue with my JavaScript Interpreter?

Thanks.

------UPDATE-----

The issue lies within having both the QML application (sending HTTP requests) and the HTTP server (serving these requests) within the same application/process. When separating the HTTP server and QML application into two distinct applications/executables, everything functions correctly. However, combining them into one executable causes problems. Combining both the HTTP server and QML application within one executable seems to disrupt the functionality of the QML JavaScript interpreter. The QML application runs in a Separate Thread before launching the Web server.

Answer №1

Have you attempted the following:

if( httpReq.readyState == 4 ) //Issue
{   
  console.log("Confirmed as true with: " + httpReq.readyState);

...

Did you verify that the condition was incorrectly confirmed as true with an incorrect integer?

Alternatively, considering this is used in QML, it could be related to how javascript is utilized with QML. Could you demonstrate how you call the javascript from the QML file?

Answer №2

An illustration showcasing the behavior described would be greatly appreciated.

Here is a piece of code that runs smoothly for me:

import QtQuick 1.0

Item {
    Component.onCompleted: {
        var req = new XMLHttpRequest();
        req.onreadystatechange = function() {
            console.log("readyState: " + req.readyState);

            if (req.readyState == XMLHttpRequest.DONE) { // 4 instead of 'XMLHttpRequest.DONE' works here too
                console.log("Request complete");

                if (req.status == 200) {
                    console.log("Status code: 200");
                    console.log(req.responseText.slice(0, 50) + "...");
                }
            }
        };

        req.open("GET", "http://stackoverflow.com/");
        req.send();
    }
}

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 could be causing this JavaScript if statement to consistently evaluate to true?

I'm facing an issue where I want to run a specific block of code when a div is clicked for the first time, and then another block when it's clicked for the second time. The problem is that even though my alert shows the variable being updated wit ...

JavaScript function issue with automatic tabbing

Encountered an issue while utilizing this in our asp.net application. The main goal is as follows: When in a textbox -> tab once MaxLength is reached When in a checkbox -> tab once the control is toggled with the keyboard (spacebar) Other than bu ...

Is it possible to enable autocomplete for JavaScript generated code in .proto files?

I recently created a basic .proto file with the following content: syntax = "proto3"; message Event { optional string name = 1; } After downloading and installing the protoc linux compiler (protoc-3.19.3-linux-x86_64.zip) on my local machine, ...

Instructions on utilizing sockets for transmitting data from javascript to python

How can I establish communication between my Node.js code and Python using sockets? In a nutshell, here is what I am looking for: Node.js: sendInformation(information) Python: receiveInformation() sendNewInformation() Node.js: receiveNewInformation( ...

Problem with Ionic 2 local storage: struggling to store retrieved value in a variable

Struggling to assign the retrieved value from a .get function to a variable declared outside of it. var dt; //fetching data this.local.get('didTutorial').then((value) => { alert(value); dt = value; }) console.log("Local Storage value: " ...

What is the best way to convert HTML into a React component?

This is the situation I am facing : 1) The application requests a CMS (Content Management System) for page contents. 2) The CMS responds with "<div>Hi,<SpecialButton color="red">My Button</SpecialButton></div>" 3) The applicat ...

The image tag in HTML is unable to display as an image within the jQuery object

After converting the object "suggestion" to a string, I have data stored in the "sugestion" variable like this: {"value":"<img src=\"http://localhost/erp/assets/images/product/123.jpg\"> 123123123 t-shirt","data":"ABC098765"} Unfortunatel ...

In Angular components, data cannot be updated without refreshing the page when using setInterval()

Here's the Angular component I'm working with: export class UserListComponent implements OnInit, OnDestroy { private _subscriptions: Subscription; private _users: User[] = []; private _clickableUser: boolean = true; constructor( priv ...

The React ternary operator within HTML does not display the correct HTML output

I'm currently learning React and facing a challenge with using a ternary operator. My goal is to display a minus sign by default, and then switch it to a plus sign when clicked. I implemented the ternary operator in my JSX and set the initial state of ...

The CSS files are not loading automatically in my React application using Vite

I am facing an issue with importing css and js files into a view in React using vite. The styles are not loading properly, and I have to keep commenting and uncommenting the imports in my code for them to be recognized when entering the view. Below is a s ...

Optimizing HTML/CSS performance: Comparing flexbox and tables for handling extensive datasets

Creating a React table component with hundreds of lines and variable cell widths can be complex. Would it be better to implement this using flexbox or a traditional table structure in HTML/CSS? ...

Versioning resources in Spring MVC with Thymeleaf

https://i.sstatic.net/ArllV.png Struggling with resource versioning in Spring Mvc 4 while using thymeleaf template engine. Despite the code provided, I am unable to see the new version URL when viewing the page source. What could be causing this issue? Wh ...

Expo's ReactNative camera feature fails to flip the camera view

Following the guidance provided in Expo Docs on how to use a camera, I have noticed that when I press the flip button, the state of the camera type changes from 0 to 1 and vice versa, but the camera always remains on the back side. This is my implementati ...

Implementing IBAN as the default option in Stripe's PaymentElement

The functionality of the react-stripe-js library's IbanElement includes various options such as supportedCountries and placeholderCountry: <IbanElement ... options={{ supportedCountries: ["SEPA"], placeholderCountry: "DE& ...

What is the mechanism by which sending data directly to the response object displays content to the user?

What exactly does the .pipe(res) segment of the code snippet from that article do at the end of the stream? fs.createReadStream(filePath).pipe(brotli()).pipe(res) I have a basic understanding that the first part reads the file and the second compresses i ...

Oops! You're trying to perform actions that must be plain objects. If you need to handle async actions

I have been struggling to implement Redux and pass an object into the store. Although I am able to fetch the correct object when I call the action, the store remains unchanged when I use store.dispatch(). It still only reflects the initial state. I've ...

The 'props.p' navigation in react-native is undefined

I have gone through various forums and discussions regarding this issue, but none of the solutions seem to work for me. For some reason, I am facing difficulties passing props to react-navigation when I attempt to navigate, resulting in the following erro ...

Different from SimplyScroll but with added functionalities

Searching for a replacement for the now deprecated SimplyScroll with specific features. I am in need of a continuous, automatic carousel of boxes/images that halts when hovering over with the mouse (a feature SimplyScroll possesses), and allows movement ...

TypeScript error: Unable to locate namespace 'ng'

I am attempting to utilize a tsconfig.json file in order to avoid having /// <reference tags at the beginning of multiple files. However, I keep encountering this error: [ts] Cannot find namespace 'ng'. any Here is my configuration within ...

When it comes to React, an unspoken truth is that undefined could potentially cause issues

I have been attempting to iterate through an array of data, following a guide without much success. The structure of the data file is as follows: import React, {Component} from 'react'; export default [ { id: 1, lk:593458, ld:18033, status: &ap ...