Search code examples
jsonblackberry-10

XMLHttpRequest ERROR in QML Blackberry 10


I'm trying to get movie data for BlackBerry 10 apps. I don't know where I'm making a mistake. Please, can you help me? Thank you all.

import bb.cascades 1.4

Page {

    onCreationCompleted: {
        sendRequest();
    }

    function sendRequest() {
        var data = "{}";

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

        xhr.addEventListener("readystatechange", function () {
                if (this.readyState === this.DONE) {
                    console.log(this.responseText);
                }
        });

        xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");

        xhr.send(data);
    }
}

Solution

  • You need to use the onreadystatechange EventHandler. Also, you don't need to pass data when making a GET request. I have removed the withCredentials line as it isn't needed in this example.

    You can learn more on XMLHttpRequest here : https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest

    onCreationCompleted: {
        sendRequest();
    }
    
    function sendRequest() {
        var xhr = new XMLHttpRequest();
    
        xhr.onreadystatechange = function () {
            if (xhr.readyState === XMLHttpRequest.DONE) {
                var json = JSON.parse(xhr.responseText);
                var results = json.results;
                var count = results.length;
    
                console.log("There are " + count + " results :");
                json.results.forEach((value, index) => 
                {
                  console.log(index + " - " + value.title);
                });
            }
        };
    
        xhr.open("GET", "https://api.themoviedb.org/3/search/movie?include_adult=false&page=1&query=hulk&language=en-US&api_key=YOUR_API_KEY_HERE");
        xhr.send();
    }
    

    Here's an example of using XMLHttpRequest I've made a long time ago : https://github.com/RodgerLeblanc/Markup/blob/master/assets/main.qml