Greasemonkey AJAX post does not appear to work, even with @grant specified

pagliaccio picture pagliaccio · Jan 5, 2013 · Viewed 7.6k times · Source

My script does not work. The AJAX call is not happening. Why?

// ==UserScript==
// @name        prova
// @namespace   http://blogpagliaccio.wordpress.com/
// @description prova
// @include     http://*
// @version     1
// @grant       GM_xmlhttpRequest
// @require     http://userscripts.org/scripts/source/85398.user.js
// ==/UserScript==

// [........... other code]

    console.log('start ajax call...');
            GM_xmlhttpRequest({
                    method: "POST",
                    url: "www.prova.it",
                    data: {parametro:parametro},
                    onload: function(response) {
                            console.log(response.responseText);
                    },
                    onerror: function(reponse) {
                            alert('error');
                            console.log(reponse);
                    }
            });


I listed the API function in a @grant directive, but I do not see an AJAX call and response.

Answer

Brock Adams picture Brock Adams · Jan 5, 2013

See the documents for GM_xmlhttpRequest(). data takes only a string.

If you try to send non-string data to data, you will get an error like:

Component does not have requested interface
(113 out of range 67)

So, you must encode data into an appropriate string. Also, you will need to send the appropriate Content-Type header. The two main types/methods are:

  1. application/x-www-form-urlencoded
    And
  2. application/json

Encoding and sending the data looks like this for the two methods:

Form-encoded data:

GM_xmlhttpRequest ( {
    method:     "POST",
    url:        "www.prova.it",
    data:       "parametro=" + encodeURIComponent (parametro),
    headers:    {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    onload:     function (response) {
        console.log(response.responseText);
    },
    onerror:    function(reponse) {
        //alert('error');
        console.log("error: ", reponse);
    }
} );


JSON serialized data:

GM_xmlhttpRequest ( {
    method:     "POST",
    url:        "www.prova.it",
    data:       JSON.stringify ( {parametro:parametro} ),
    headers:    {
        "Content-Type": "application/json"
    },
    onload:     function (response) {
        console.log(response.responseText);
    },
    onerror:    function(reponse) {
        //alert('error');
        console.log("error: ", reponse);
    }
} );