Greasemonkey AJAX request not sending data?

I run a GET request using Greasemonkey GM_xmlhttpRequest() :

 $(".getReview").click(function(){ var videoId = $(this).parents("li").find("a").attr("href"); alert(videoId); GM_xmlhttpRequest({ method: "GET", url: "http://www.amitpatil.me/demos/ytube.php", data: "username=johndoe&password=xyz123", headers: { "User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used. "Accept": "text/xml" // If not specified, browser defaults will be used. }, onload: function(response) { console.log(response); } }); 


and here is the ytube.php server code :

 <?php print_r($_REQUEST); print_r($_GET); echo "Hello friends".$_GET['vid']; ?> 

$_REQUEST => returns some data related to WordPress. $_GET => returns an empty array.

I can’t understand what happened. I even tried the POST method.

+4
source share
1 answer

The data parameter only works for POST methods. If you want to send data with a GET request, add it to the URL:

 GM_xmlhttpRequest ( { method: "GET", url: "http://www.amitpatil.me/demos/ytube.php?username=johndoe&password=xyz123", // Use no data: argument with a GET request. ... ... } ); 

But it is better to send data through POST for a number of reasons. To do this, you need to specify the encoding:

 GM_xmlhttpRequest ( { method: "POST", url: "http://www.amitpatil.me/demos/ytube.php", data: "username=johndoe&password=xyz123", headers: { "Content-Type": "application/x-www-form-urlencoded", "User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used. "Accept": "text/xml" // If not specified, browser defaults will be used. }, ... ... } ); 


If you are going to send a lot of data or complex data, use JSON:

 var ajaxDataObj = { u: username, p: password, vidInfo: [123, "LOLcats Terrorize City!", "Five stars"] }; var serializedData = JSON.stringify (ajaxDataObj); GM_xmlhttpRequest ( { method: "POST", url: "http://www.amitpatil.me/demos/ytube.php", data: serializedData, headers: { "Content-Type": "application/json", "User-Agent": "Mozilla/5.0", // If not specified, navigator.userAgent will be used. "Accept": "text/xml" // If not specified, browser defaults will be used. }, ... ... } ); 

Your PHP will access it like this:

 $jsonData = json_decode($HTTP_RAW_POST_DATA); 

Update:
Greasemonkey and Tampermonkey now require you to set @grant GM_xmlhttpRequest in the metadata block. Be sure to do it.

+5
source

Source: https://habr.com/ru/post/1397873/


All Articles