gro
gro

Reputation: 53

Backbone.js sync - PHP return

I'm learning to work with Backbone.js and set up the following environment:

/* define the model */
var Login = Backbone.Model.extend({
    url:"api/index.php/login/"
});

/* the following code is contained in a view method */

var login = new Login({
    email: $("#email").val(),
    pass: $("#pass").val()
});

var result = Backbone.sync('create',login);
alert(JSON.stringify(result));

In the "index.php" on the server the correct method is called and the data is correctly available.

The alert just outputs: {"readyState":1}

Now my question: What should the server (index.php) return/output to answer the client? I'd like to transfer data back to the client to e.g. display it.

Upvotes: 2

Views: 1420

Answers (1)

Tomalak
Tomalak

Reputation: 338228

Backbone.sync() is an asynchronuous operation. You cannot do

var result = Backbone.sync('create', login);

because sync() does not return anything useful. It sends the request to the server and returns immediately, long before the server's response has arrived.

Use the options parameter and place success and error callback functions there.

Backbone.sync('create', login, {
  success: function () {
    // whatever you want to do when login succeeds
  },
  error: function () {
    // display an error message
  }
});

The error callback would be executed if the server returned an 401 Unauthorized response, for example; the success callback when the server returns 200 OK.

For documentation on how to use these callbacks and what other options you can use, read the jQuery.ajax() docs.

Upvotes: 2

Related Questions