'How to execute JS function after successfull ajax call?

I want to demonstrate my window in a full screen.

I have a working function, but I have a problem:

I'm sending an AJAX call after user's click on some button in UI, to get some data and prepare it, after this ajax call (on success I want to demonstrate my data in the full screen, but I can't do that, because it raises an error: Failed to execute 'requestFullScreen' on 'Element': API can only be initiated by a user gesture.

As you understand, I had user action - click on button, but it's not enough, if I' trying to execute fullscreen function in ajax call.

I was trying to use global variable too, to have a state(do I need to show fullscreen or not(it depends on result of response parsing(after AJAX call)), but it doesn't work too.I was trying in this way:

ISFULLSCREEN = false;

function get_ajax() {
    ajax_call ()
    .success(response) {
        if (response.fullscreen) {
           ISFULLSCREEN = true;
        }
    }
 }


function useFullscreen() {
    if (ISFULLSCREEN) {
        use_fullscreen();
    }
}

and my button looks like:

<button onclick="get_ajax();useFullscreen()" value="click me" />

but function useFullscreen runs faster, than the value of ISFULLSCREEN changes to true

Do somebody have any idea how to resolve this issue?

Thanks a lot!



Solution 1:[1]

Perhaps in your ajax request, use async: false to make the fetch synchronous, therefore keeping all the execution within the same event (from the user click).

The downside to this is that it may hang the page if it takes a long time

Solution 2:[2]

You can use callback function, a callback function is a function passed into another function as an argument, so you can utilize it, and it will execute after your awaited ajax response comes, see below example:

ISFULLSCREEN = false;

function get_ajax(useFullscreenCallback) {
    ajax_call ()
    .success(response) {
        if (response.fullscreen) {
           ISFULLSCREEN = true;
           useFullscreenCallback();
        }
    }
 }


function useFullscreen() {
    if (ISFULLSCREEN) {
        use_fullscreen();
    }
}

get_ajax(useFullscreen);

Reference: Callback Function Mozilla web docs

Solution 3:[3]

Does this help you?: Run a website in fullscreen mode

The answer basically says that you cannot force a fullscreen change without user interaction but there are some alternate suggestions

Solution 4:[4]

Add async : false to ajax call and call the function useFullscreen on ajax success and remove this from the button onclick event

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joseph Young
Solution 2 Accurate Design
Solution 3 Community
Solution 4 Jobelle