Search code examples
javascriptphpbackbone.js

backbone.js model.fetch sends no data to php


I'm just starting to play around with backbone.js to learn more about it for a project where I use Javascript for client side code an PHP on the server side.

To find out how communications between backbone and the server actually works (can't really find any good documentation about it. I just made a small example for fetch():

var NavigationElement = Backbone.Model.extend({
    initialize: function() {},
    defaults:   {
                    text: 'Home',
                    link: '/',
                    category: 'Main'
                },
    url: 'ajax.php'

});
var forum = new NavigationElement( { text: 'Forum', 
                                     link: '?q=Forum'});
var login = new NavigationElement( { text: 'Login', 
                                     link: '?q=Login', 
                                     category: 'User'});

forum.fetch();

Now, Backbone should send some GET data to the server to identify the data it has to send. And indeed, $_SERVER[ 'REQUEST_METHOD' ] says there is a GET-Request, but $_GET remains empty.

For save() I had a similar problem and learned, that I could find the data in php://input for all POST and PUT Requests. Is there a similar stream for GET Requests?

And how can I tell Backbone to send a GET-Request like '.../ajax.php?model=NavigationElement&text=Login' ?


Solution

  • By default, model.fetch will use the first available in

    • the url attribute passed in the options to fetch
    • what is set by model.url
    • model.urlRoot with /id appended if the id attribute exists
    • model.collection.url with /id appended if the id attribute exists

    You can provide a custom url method on NavigationElement to set a different endpoint. For example:

    var NavigationElement = Backbone.Model.extend({
        initialize: function() {},
        defaults: {
            text: 'Home',
            link: '/',
            category: 'Main'
        },
        url: function() {
            return 'ajax.php?model=NavigationElement&text='+encodeURIComponent(this.get('text'));
        }
    });
    

    A demo : http://jsfiddle.net/nikoshr/ygdbxn1q/

    or if you just want to pass additional parameters on read operations, you can override fetch and pass the data as an option:

    var NavigationElement = Backbone.Model.extend({
        initialize: function() {},
        defaults: {
            text: 'Home',
            link: '/',
            category: 'Main'
        },
        url: 'ajax.php',
        fetch: function(options) {
            options = options || {};
            options.data = _.extend({
                model: 'NavigationElement'
            }, this.pick('text'));
            return Backbone.Model.prototype.fetch.call(this, options);
        }
    });
    

    http://jsfiddle.net/nikoshr/ygdbxn1q/1/