Wikipedia:WikiProject User scripts/Guide/Ajax: Difference between revisions

Content deleted Content added
Fix: the result is on "data.edit.result", not on "data.result"
Edit a page and other common actions: Updated to use mw.user.tokens.get( 'editToken' ) from MW 1.18 instead of an extra API call
Line 28:
The code below shows how to edit a page, but it can easily be adapted to other actions by reading the [{{SERVER}}/w/api.php API documentation].
<source lang="javascript">
$.ajax({
url: mw.util.wikiScript( 'api' ),
dataType: 'json',
data: {
format: 'json',
action: 'query',
prop: 'info',
indexpageids: true,
intoken: 'edit',
titles: 'Whatever'
},
success: function( data ) {
if ( 'error' in data ) {
alert( 'API Error ' + data.error.code + '. ' + data.error.info );
} else if ( data.query && data.query.pages && data.query.pageids ) {
var token = data.query.pages[ data.query.pageids[0] ].edittoken;
doEditPage( token );
} else {
alert( 'The token query returned an unknown error.' );
}
},
error: function() {
alert( 'The ajax request failed. =(' );
}
});
 
// Edit page (must be done through POST)
function doEditPageeditPage( tokeninfo ) {
var mySandbox = 'User:' + mw.config.get( 'wgUserName' ) + '/Sandbox';
 
$.ajax({
url: mw.util.wikiScript( 'api' ),
Line 65 ⟶ 37:
format: 'json',
action: 'edit',
title: mySandboxinfo.title,
text: 'Cool! It works! :-) ~~' + '~~'info.text,
summary: info.summary,
summary: 'Trying to edit my sandbox [[Project:WikiProject User scripts/Guide/Ajax|using AJAX]]...',
token: tokenmw.user.tokens.get( 'editToken' )
},
success: function( data ) {
Line 82 ⟶ 54:
});
}
editPage({
var mySandbox =title: 'User:' + mw.config.get( 'wgUserName' ) + '/Sandbox';,
text: 'Cool! It works! :-) ~~' + '~~',
summary: 'Trying to edit my sandbox [[Project:WikiProject User scripts/Guide/Ajax|using AJAX]]...',
});
</source>