11

I have some angular js code here.

<!DOCTYPE html>
<html lang="en">

  <head>
    <script src="Scripts/angular.min.js"></script>
        <body>    
      <div ng-app="">
        <form>
          Author:
          <input type="text" ng-model="author">
          <br>
          <br> Title:
          <input type="text" ng-model="title">
          <br>
          <br> Body:
          <input type="author" ng-model="body">
          <br>
          <br>
          <input type="submit" value="Submit">
        </form>
      </div>
    </head>
    </body>
</html>

and node js with MySQL code here. I am able to pass data to MySQL DB from this node code. How to go ahead with angular to node js? I am coming from a PHP background. I should be able to send data from angular js form to MySQL database. I am able to send data to MySQL database from node code here.

var mysql = require('mysql');

var connection = mysql.createConnection({
  host: 'localhost',
  user: '',
  password: '',
  database: 'copedb'
});
connection.connect();
var cope = {
  author: 'XYZXYZ',
  title: 'Testing Node',
  body: 'Node JS'
};
var query = connection.query('insert into cope set ?', cope, function(err, result) {
  if (err) {
    console.error(err);
    return;
  }
  console.error(result);
});
2
  • I should be able to send data from angular js to mysql Commented Feb 29, 2016 at 12:12
  • 1
    check $http service in angular docs.angularjs.org/api/ng/service/$http Commented Feb 29, 2016 at 12:20

4 Answers 4

19

It can be the stepping stone for you to getting started:

Index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <script src="Scripts/angular.min.js"></script>
   <script src="Scripts/app.js"></script>
</head>
<body ng-app="myApp">    
  <div ng-controller="myCtrl">
    <form>
      Author:
      <input type="text" ng-model="author">
      <br>
      <br> Title:
      <input type="text" ng-model="title">
      <br>
      <br> Body:
      <input type="author" ng-model="body">
      <br>
      <br>
      <input type="submit" value="Submit" ng-click="submit()">
    </form>
  </div>
</body>

Angular code app.js

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
   $scope.submit= function(){
      var data = $.param({
        book: JSON.stringify({
            author: $scope.author,
            title : $scope.title,
            body : $scope.body
        })
      });

      $http.post("/api/book/", data).success(function(data, status) {
        console.log('Data posted successfully');
      })
   }
});

server.js - Nodejs

var express = require('express'); 
var mysql = require('mysql');
var app = express();

var connection = mysql.createConnection({
     host: 'localhost',
     user: '',
     password: '',
     database: 'copedb'
});
connection.connect();

app.post('/api/book', function(req, res, next){
   var cope = req.body.params;
   var query = connection.query('insert into cope set ?', cope, function(err, result) {
     if (err) {
       console.error(err);
       return res.send(err);
     } else {
       return res.send('Ok');
     }
});
app.listen(8080);
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks . I have sever.js underlined in red. Is there any specific location I have put server.js file ? I am using webstorm with nodejs express project .
server.js is the entry file of your program. I don't know about Webstorm.
mysql underlined -module not listed package.json
fixed - ALT+Enter - add dependency.
This code is basic one. I did not even tested it. It is good to learn from this. Learn angularjs from this free course. codeschool.com/courses/shaping-up-with-angular-js
|
4

Anyways I have written actual working code here .

index.html

 <!DOCTYPE html>
 <html lang="en">
 <head>
 <script src="angular.min.js"></script>
 <script src="app.js"></script>
 </head>
 <body ng-app="myApp">
 <div ng-controller="myCtrl">
 <form>
    Author:
    <input type="text" ng-model="data.author">
    <br>
    <br> Title:
    <input type="text" ng-model="data.title">
    <br>
    <br> Body:
    <input type="author" ng-model="data.body">
    <br>
    <br>
    <input type="submit" value="Submit" ng-click="submit()">
  </form>
  </div>
  </body>
  </html>

app.js

 var app = angular.module('myApp', []);
 app.controller('myCtrl', function($scope,$http) {
 $scope.data = {};
$scope.submit= function(){
    console.log('clicked submit');
    $http({
        url: 'http://localhost:8080/blah',
        method: 'POST',
        data: $scope.data
    }).then(function (httpResponse) {
        console.log('response:', httpResponse);
    })
   }
 });

server.js

   var express = require('express');
   var bodyParser = require('body-parser');
   var mysql = require('mysql');
   var app = express();

    app.use(bodyParser.json({limit: '50mb'}));
    app.use(express.static('public'));

  var connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  password: '',
  database: 'copedb'
   });
   connection.connect();

    app.post('/blah', function(req, res, next) {
    var cope = req.body;
    console.log('request received:', req.body);
   var query = connection.query('insert into cope set ?', cope, function (err,     result) {
    if (err) {
        console.error(err);
        return res.send(err);
    } else {
        return res.send('Ok');
    }
    });
    //res.send('received the data.');
    });
    app.listen(8080);

Comments

2

First of all, create a RESTful service using Express/Restify which are npm modules, based on your needs which will in turn talk to your SQL database.

Once the service is up and running at the server-level, you are now ready to send/receive data to/from the server at the client-level.

Note: Make use of $resource instead of $http service of AngularJS for talking to the server.

https://docs.angularjs.org/api/ngResource/service/$resource

Comments

1

Easiest Answer for How to pass data from AngularJS frontend to Nodejs backend

AngularJs code with html

 <body>
 <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <div ng-app="app" ng-controller="myCtrl">
        <p>First Name: <input type="text" name="firstName" ng-model="firstName" required /></p>
        <p>Lirst Name: <input type="text" name="lastName" ng-model="lastName" required /></p>
        <button ng-click="SendData()">Submit</button>
        <hr />
        {{ PostDataResponse }}
    </div>
    <script>
        var app = angular.module("app",[]);
        app.controller("myCtrl", function($scope,$http){
        $scope.SendData = function() {
            var data = {
                    fName : $scope.firstName,lName : $scope.lastName
                }
            $http.post('/postFormAngular', data)
                .success(function (data, status, headers, config) {
                    $scope.PostDataResponse = data;
                })
                .error(function(data, status, header, config){
                    $scope.PostDataResponse = "Data: " + status;


                });
        };  
        });
    </script>
 </body>

Nodejs code

var express = require('express');
var multer  =   require('multer');
var mime    =   require('mime');
var mysql = require('mysql');
var app = express();
var bodyParser =    require("body-parser");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var connection = mysql.createConnection({
  host     : 'localhost',
  user     : 'root',
  port      : 3306,
  password : '',
  database : 'angular_db'
});

connection.connect(function(err){
if(!err) {
    console.log("Database is connected ... nn");    
} else {
    console.log("Error connecting database ... nn");    
}
});

app.get('/angular_html.html', function(req, res){
    res.sendFile(__dirname + '/' + 'angular_html.html');
    console.log("----------------");
});
app.post("/postFormAngular", function (req, res) {
        console.log(req.body.fName);
        res.send(req.body.fName);
});
app.listen(3000);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.