0

I tried:

GM_xmlhttpRequest({
    method: "GET",
    url: "...",
    onload: function(response) {
        r = response.responseText;

    }});
alert(r); //undefined 

How do this?

Brock Adams
  • 90,639
  • 22
  • 233
  • 295
The Mask
  • 17,007
  • 37
  • 111
  • 185
  • Duplicate of [GreaseMonkey: GM_xmlhttpRequest return value to calling function](http://stackoverflow.com/questions/7196772/greasemonkey-gm-xmlhttprequest-return-value-to-calling-function) – Brock Adams Aug 28 '11 at 00:14

1 Answers1

1

Why this is happening

By default, ajax requests using XMLHTTPRequest are asynchronous. This means that the call to method returns immediately and the main execution continues while the request proceeds in the background. When the request completes, the callback method will be invoked with the results of the request. Thus, your alert is executed before the (asynchronous) request ever completes.

Solution 1: Callbacks

You haven't provided context as to why you'd need the response text synchronously so it's possible you could rewrite your code to use callbacks and continue using the asynchronous behaviour - this is usually good practice.

Solution 2: Force synchronous requests

However, if find that you absolutely must make requests synchronously, you'll find that you can request that the ajax request be made synchronously. With Greasemonkey, you should use the option synchronous: true when invoking GM_xmlhttpRequest, as documented here. Note that the docs say that

Be careful: The entire Firefox UI will be locked and frozen until the request completes. In this mode, more data will be available in the return value.

With XHR objects in the browser, you'd achieve the same results by passing false as the second parameter to XMLHTTPRequest#open.

If you're working with an older version of Greasemonkey, the answers to this SO question might prove useful: How to make synchronous AJAX calls in greasemonkey?

Community
  • 1
  • 1
no.good.at.coding
  • 20,221
  • 2
  • 60
  • 51