API:Edit/Editing with Ajax
Appearance
< API:Edit
Examples
[edit]Editing via Ajax
[edit]Below is sample code for editing a page via an Ajax request:
function addNewSection( summary, content, editToken ) {
$.ajax({
url: mw.util.wikiScript( 'api' ),
data: {
format: 'json',
action: 'edit',
title: mw.config.get( 'wgPageName' ),
section: 'new',
summary: summary,
text: content,
token: editToken
},
dataType: 'json',
type: 'POST',
success: function( data ) {
if ( data && data.edit && data.edit.result == 'Success' ) {
window.location.reload(); // reload page if edit was successful
} else if ( data && data.error ) {
alert( 'Error: API returned error code "' data.error.code '": ' data.error.info );
} else {
alert( 'Error: Unknown result from API.' );
}
},
error: function( xhr ) {
alert( 'Error: Request failed.' );
}
});
}
You can also use the mw.Api object:
var api = new mw.Api();
function addNewSection( summary, content ) {
api.postWithToken( "edit", {
action: "edit",
title: mw.config.get( "wgPageName" ),
section: "new",
summary: summary,
text: content
} ).done( function( result, jqXHR ) {
mw.log( "Saved successfully" );
location.reload();
} ).fail( function( code, result ) {
if ( code === "http" ) {
mw.log( "HTTP error: " result.textStatus ); // result.xhr contains the jqXHR object
} else if ( code === "ok-but-empty" ) {
mw.log( "Got an empty response from the server" );
} else {
mw.log( "API error: " code );
}
} );
}
Remember to make sure the mediawiki.api.edit
module is loaded when using this methodology.