Using Backbone with the WordPress AJAX API

You need to override the Backbone.sync function to change the URL used for the AJAX call. You can learn from the plugin wp-backbone does this and more. Below you can see from it how it changes all the actions into either POST or GET, create the parameters, add the action parameter and more.

(function($) {
Backbone.sync = function(method, model, options) {

    var params = _.extend({
        type:         'POST',
        dataType:     'json',
        url: wpBackboneGlobals.ajaxurl,
        contentType: 'application/x-www-form-urlencoded;charset=UTF-8'
    }, options);

    if (method == 'read') {
        params.type="GET";
        params.data = model.id
    }

    if (!params.data && model && (method == 'create' || method == 'update' || method == 'delete')) {
        params.data = JSON.stringify(model.toJSON());
    }


    if (params.type !== 'GET') {
        params.processData = false;
    }

    params.data = $.param({action:'backbone',backbone_method:method,backbone_model:model.dbModel,content:params.data});

    // Make the request.
    return $.ajax(params);


};

})(jQuery);

Leave a Comment