-1

I have a XMLHttpRequest to communicate with an server side .php file (clientserver.php). The request is like,

    tablink = tab.url;
    $("#p1").text("Selected URL - "+tablink);
    var xhr=new XMLHttpRequest();
    params="url="+tablink;
    // alert(params);
    var markup = "url="+tablink+"&html="+document.documentElement.innerHTML;
    xhr.open("POST","http://localhost/WebExt/clientServer.php",false);
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhr.send(params);
    //alert(xhr.responseText);
    $("#div1").text(xhr.responseText);
    return xhr.responseText;

and the clientserver.php contains,

<?php
header("Access-Control-Allow-Origin: *");
$site=$_POST['url'];
$decision=exec("python test.py $site 2>&1");
echo $decision;
?>

When i executes above code it shows an error like

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience

How to resolve it? Is there any alternatives codes (Like fetch API) the complete this task (XMLHttpRequest)?

  • _"Is there any alternative...?"_ - Yes. Its already in your question: [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) – Andreas Nov 11 '21 at 15:46
  • 2
    The error message is only telling you that _synchronous_ requests are deprecated - so you don't necessarily need to switch the whole method to something else, but only make the request asynchronous instead. You explicitly specified that you want a synchronous request, by passing `false` as third parameter for the `open` method. – CBroe Nov 11 '21 at 15:52
  • [From the document by mozilla](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Synchronous_and_Asynchronous_Requests#example_http_synchronous_request) Just remove `false` from `request.open()`. – vee Nov 11 '21 at 15:56

1 Answers1

0

Synchronous XMLHttpRequest outside of workers is in the process of being removed from the web platform as it has detrimental effects to the end user’s experience. (This is a long process that takes many years.) Developers must not pass false for the async argument when current global object is a Window object. User agents are strongly encouraged to warn about such usage in developer tools and may experiment with throwing an "InvalidAccessError" DOMException when it occurs.

https://xhr.spec.whatwg.org/

If you would like to have some tasks to do after XMLHttpRequest then please use Promise instead because Synchronous XMLHttpRequest will be removed in the future.

Here is an example (test02.php):

<?php
$requestType = ($_GET['requestType'] ?? null);

if (isset($requestType) && $requestType === 'ajax') {
    sleep(1);
    echo 'hello';
    exit();
}
?>

<div id="response" style="border: 4px dashed #ccc;"></div>

<script>
    function ajaxRequest() {
        let promiseObj = new Promise(function(resolve, reject) {
            var xhr=new XMLHttpRequest();

            xhr.addEventListener('abort', (event) => {
                reject({'response': '', 'status': (event.currentTarget ? event.currentTarget.status : 'abort'), 'event': event});
            });
            xhr.addEventListener('error', function(event) {
                reject({'response': '', 'status': (event.currentTarget ? event.currentTarget.status : ''), 'event': event});
            });
            xhr.addEventListener('timeout', (event) => {
                reject({'response': '', 'status': (event.currentTarget ? event.currentTarget.status : 'timeout'), 'event': event});
            });
            xhr.addEventListener('load', function(event) {
                let response = (event.currentTarget ? event.currentTarget.response : '');

                if (event.currentTarget && event.currentTarget.status >= 200 && event.currentTarget.status < 300) {
                    resolve({'response': response, 'status': event.currentTarget.status, 'event': event});
                } else if (event.currentTarget && event.currentTarget.status >= 400 && event.currentTarget.status < 600) {
                    reject({'response': response, 'status': event.currentTarget.status, 'event': event});
                } else {
                    reject({'response': response, 'status': event.currentTarget.status, 'event': event});
                }
            });

            xhr.open("POST","test02.php?requestType=ajax");// use your URL.
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            // add your xhr options here.
            xhr.send();
        });

    return promiseObj;
    }
    ajaxRequest()
    .then((response) => {
        let responseElement = document.getElementById('response');
        responseElement.insertAdjacentHTML('beforeend', response.response + '<br>');
        responseElement.insertAdjacentHTML('beforeend', 'hi');
    });
</script>

This Asynchronous request will not freeze user's web browser and the task(s) after this still working fine as queue by then().

vee
  • 4,506
  • 5
  • 44
  • 81