kimjoar / writings

My blog posts
1.99k stars 121 forks source link

Let's use a model - error callback called #18

Closed stefek99 closed 11 years ago

stefek99 commented 11 years ago

In this stage: https://github.com/kjbekkelund/writings/blob/master/published/understanding-backbone.md#lets-use-a-model

Following code:

var Statuses = function() {};

Statuses.prototype.add = function(text) {
  var status = new Status();

  // DOCS: http://documentcloud.github.io/backbone/#Model-save
  status.save({text : text}, {
    success: function(model, data) {
      console.log("success callback");
      events.trigger('status:add', data.text);
    }, 
    error : function(model, xhr, options) {
      console.log("error callback");
      console.log(model);
      console.log(xhr);
      console.log(options);
    }
  });
};

Causes error callback to be called, not really sure why... Here is the full source: https://gist.github.com/stefek99/ccdb3dd2e40e5e656805

I know that this is just a step in a tutorial and probably can be skipped however I would really like to know why it isn't working at this stage.

Thanks for help in support, great piece of writing BTW :)

kimjoar commented 11 years ago

Ah, my bad.Save actually performs an Ajax request, so when you have no server running it will fail. You can see this for example in the Network panel in Chrome when you are running your code. The easiest way to get around this is to have a super simple server up and running.

So, the thing you need is a server which responds to /server with an object with a text key which contain the data you sent to the server, { "text": "what you POST-ed to /server" }:

stefek99 commented 11 years ago

Nailed it (using Fiddler): jQuery posts data in format: text=qwe Backbone models add some extra to it: {"text":"qwe"}

My super-duper backend was failing:

<?php
    $data = $_POST["text"];
    $arr = array('text' => $data);
    echo json_encode($arr);
?>

Replacing it with a dummy string allows me to complete this step of a tutorial:

<?php
echo '{"text":"qwe"}';
?>

Yeah, that was simple :)

kimjoar commented 11 years ago

Great stuff!