2

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

works like a charm thanks for correcting this very basic misunderstanding

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.