I have implemented a simple login system using Backbone.js.
I am attempting to pass the username and password using HTTP POST method to the Controller class which handles the user authentication.
public function sessions() {
if ($this->input->server('REQUEST_METHOD') == 'POST') {
$this->login();
} elseif ($this->input->server('REQUEST_METHOD') == 'GET') {
$this->index();
} elseif ($this->input->server('REQUEST_METHOD') == 'DELETE') {
$this->session->sess_destroy();
$this->index();
}
}
The Backbone.js code segment:
$(document).ready(function() {
var Session = Backbone.Model.extend({
url: function() {
var link = "http://<?php echo gethostname(); ?>/reddit/index.php/welcome/sessions";
return link;
},
defaults: {
username: null,
password: null
}
});
var model = new Session();
var DisplayView = Backbone.View.extend({
el: ".complete",
model: model,
type: 'POST',
initialize: function() {
this.listenTo(this.model, "sync change", this.gotdata);
},
events: {
"click #signin": "getdata"
},
getdata: function(event) {
event.preventDefault();
var username = $("input#username").val();
var password = $("input#password").val();
this.model.set({ username: username, password: password });
this.model.fetch();
},
gotdata: function() {
console.log(this.model.get('username'));
console.log(this.model.get('password'));
$("#base-nav").load(location.href + " #base-nav");
$("#signin-form").load(location.href + " #signin-form");
}
});
var displayView = new DisplayView();
});
I have used the type
attribute currently to define the HTTP method type POST. But this does not seem to work as only GET requests can be observed using the developer console.
It has to be noted that when I remove event.preventDefault();
which prevents page reload upon clicking a link (Preventing full page reload on Backbone pushState) the POST request seems to be successfully delivered to the back-end although the page reload prevents the intended target behavior.
How do we easily send data using POST request with Backbone.js?