0

I'm using backbone to post a login form to my server. After it queries the database it will flip a boolean value allowing me to retrieve GET responses from the server. The problem is that it tries to fetch (i think) before my login is validated. Given this code:

   App.Login.add(newContact);
   var out = newContact.save();
   App.Contacts.fetch();

How do i write a callback to have it first finish newContact.save() before fetching Contacts?

This is what I have so far, but it never succeeds:

     login: function(event) {
  App.Browser.navigate('contacts');
   event.preventDefault();
    var $form = this.$('.login form');
   var newContact = new App.Models.Login({
     userName: $('input.userName', $form).val(),
     passWord: $('input.passWord', $form).val(),
  });

   App.Login.add(newContact);
    newContact.save({userName:"Frank"},{
    wait: true,
    success: function(model, response){
      console.log('success');
    },
    error: function(){
      console.log('error');
    }
  });
seasick
  • 1,094
  • 2
  • 15
  • 29
  • I tried that piece of code and although my save method is sent to the server and my network monitor shows an OK response, it never calls the function afterwards – seasick Dec 25 '13 at 07:43
  • Maybe this answer http://stackoverflow.com/questions/5757555/how-do-i-trigger-the-success-callback-on-a-model-save will help you. – Evgeny Samsonov Dec 25 '13 at 07:44

1 Answers1

0

Model.save() accept callback to handle success or failure . which the code like:

    App.Login.add(newContact);
    var out=newContact.save(attributes,{
        wait: true,// wait for the sever response finish
        success:function(model, response,options){
          App.Contacts.fetch();
        },
        error:function(model, xhr, options){
          app.error(model);//custom handle for error
        }
    });
garrygu
  • 46
  • 3
  • My function never succeeds - look at the top, I posted the entire thing. Do i have the wrong handle to something? – seasick Dec 25 '13 at 08:09
  • Have you checked the returned value of server? When use backbone.save , the server should return a JSON such like {success:true,code:200,msg:"success"} – garrygu Dec 25 '13 at 09:12
  • garry - that was partly it. I was returning a JSON response, when I should have requested text. I still did not get the function to work, so i'm using jquery $.post at the moment. – seasick Dec 25 '13 at 09:46
  • Since I can only see part of your code , And I didn't see any server set for your model ,such as "url" attributes .That's is very important for your save function to work. And I don't think its necessary to fetch after each model save , The data returned by server after save will also update the model attributes .So fetch is useless. – garrygu Dec 25 '13 at 12:10