Book Image

Node.js By Example

Book Image

Node.js By Example

Overview of this book

Table of Contents (18 chapters)
Node.js By Example
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Creating a record in the database


Let's continue and handle the situation where the user presses the Create button. After the user performs this action, we have to get the content of the text areas and submit a request to the backend. So, we need a new model. Let's call it Pages.js and save it under the models directory:

// frontend/js/models/Pages.js
var ajax = require('../lib/Ajax');
var Base = require('./Base');
module.exports = Base.extend({
  data: {
    url: '/api/pages'
  },
  create: function(formData, callback) {
    var self = this;
    ajax.request({
      url: this.get('url'),
      method: 'POST',
      formData: formData,
      json: true
    })
    .done(function(result) {
      callback(null, result);
    })
    .fail(function(xhr) {
      callback(JSON.parse(xhr.responseText));
    });
  }
});

We already talked about the FormData interface in the previous chapter. The API endpoint that we are going to use is /api/pages. This is the URL where we will send a POST request.

Now...