Search code examples
javascriptjquerybackbone.js

How to stop appending same url parameter to post a form in backbone


Am submitting a form and passing url parameter appending to it. for each click the parameter is appending to the same existing parameter.

This is how it is behaving, where am doing wrong. am new to backbone.

http://localhost:8080/abc?username=&password=?username=&password=  
http://localhost:8080/abc?username=&password=?username=&password=  
http://localhost:8080/abc?username=&password=?username=&password=?username=&password=  

HTML:

<form method="post" role="form" autocomplete="off" name="abc" id="abc"></form>

Model :

var signin = Backbone.Model.extend({
        defaults :{},
        url: '/abc'
});

View :

events: { 
    "click .sgIn" : "sigIn",
}

sigIn : function(evt){
    evt.preventDefault();
    var data = this.$el.find('#abc').serialize();
    this.model.set(data);
    this.model.url = this.model.url+"?"+data;
    this.model.save(this.model.toJSON(), {
      success: function(model, response) {},
      error: function(model, error) {}
   });
}

Solution

  • You're modifying the models url everytime sigIn is called:

    this.model.url = this.model.url+"?"+data;
    

    You can pass the url as an xhr option instead:

    sigIn : function(evt){
      evt.preventDefault();
      var data = this.$el.find('#abc').serialize();
      this.model.set(data);
      this.model.save(null, {
        url: this.model.url+"?"+data,
        success: function(model, response) {},
        error: function(model, error) {}
      });
    }
    

    However, sending stuff like username and password via GET like this is not a good idea. save() should be sending POST or UPDATE unless you haven't overridden something. Also save() will sent the model data by default, no need to pass this.model.toJSON() since you're setting the data to model before calling save()