A
A
AlexWebCoder2019-10-29 16:58:26
API
AlexWebCoder, 2019-10-29 16:58:26

JS - How to get data via api link IMMEDIATELY, and not on request?

Good day!
I'm learning js, now I wrote a mini "film search" from the lessons ...
Question: What should I rewrite in the code so that the information is displayed immediately, and not after entering the request into the form and clicking?
That is, immediately indicated the request at the end of the link, and when the page is loaded, the data output is immediately displayed.

const searchForm = document.querySelector('#search-form');
const movie = document.querySelector('#movies');

function apiSearch(event) {
    event.preventDefault();
    const searchText = document.querySelector('.form-control').value;
    const server = 'https://api.themoviedb.org/3/search/multi?api_key=***&language=ru&query=' + searchText;
    requestApi(server);
}

searchForm.addEventListener('submit', apiSearch);

function requestApi(url) {

    const request = new XMLHttpRequest();
    request.open('GET', url);
    request.send();

    request.addEventListener('readystatechange', function () {
        if (request.readyState !== 4) return;

        if (request.status !== 200) {
            console.log('error: ' + request.status);
            return;
        }

        const output = JSON.parse(request.responseText)

        let inner = '';

        output.results.forEach(function (item) {
            let nameItem = item.name || item.title;
            inner += `<div class="col-6">${nameItem}</div>`;
        });

        movie.innerHTML = inner;


    });

}

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question