User:Ketil3/IncrCounter.js

function mylog (t) { console.log(t); } $( function { 	// jQuery, executed after document has been fully loaded:	var urlprefix = "https://en.wikipedia.org";	var c; // the counter variable	// var URLtouse=mw.config.get('wgScriptPath') + '/index.php?title=User:' + mw.config.get('wgUserName') + '/' + counterfile;	$.ajax({		// type: "GET", // GET default url: urlprefix + "/w/index.php?title=User:Ketil3/Counter.js&action=raw", // raw, should try JSON later success: function ( response ) { mylog ( "Success: " + response); }, error: function ( response )  { mylog ( "Failure: " + response + " " + response.status + " " + response.statusText);} }).done( function( response ) { c = parseInt(response); c = c + 1; var editToken=-1; mylog ( "Counter: " + c); $.ajax({ // get an edit token (to use when writing the counter)			url: urlprefix + "/w/api.php?action=query&meta=tokens&format=json",			success:	function ( response ) { 				editToken = response['query']['tokens']['csrftoken']; 				mylog ("Edittoken: " + editToken); // last two +\ must be replaced (says doc)				mylog ("Edittoken: " + encodeURI(editToken)); // does not replace the + sign				mylog ("Edittoken: " + editToken.slice(0,-2) + "%2B%5C"); // this replaces both				// *** turns out: The POST below works only if we do NOT alter the editToken				$.ajax({ type: "POST", url: urlprefix + "/w/api.php", data: { action: "edit", title: "User:Ketil3/Counter.js", text: c, // this is the counter value (was incremented above) token: editToken // .slice(0,-2) + "%2B%5C" // against documentation ... },					success: function ( response ) { mylog ("POST to Counter.js success. Counter: " + c) }, error: function ( response )  { mylog ("Failure POST to Counter.js: " + response + " " + response.status + " " + response.statusText);} });			},		   error: function ( response )   { mylog( "Token failure: " + response + " " + response.status + " " + response.statusText);}		}); }); } );