Fabio Manniti February 2016

AngularJs doens't communicate with Servlet

I'm writing a vary simple web page that should take two input and insert into a database but I'm trying to use AngularJs. If I don't use Angular, I can communicate with Servlet and it works perfectly, but I can't do it with angular. I give you here all the details of my project. Project name: AngularDb

index.html

<body data-ng-app="noteApp">
<div>
    <form data-ng-control="noteCtrl" ng-submit="addNote()">
        <div class="nameContainer">
        Inserisci il nome: <input type="text" name="nome" data-ng-model="nome"><br>
        </div>
        <div class="noteContainer">
        Inserisci qui una nota: <textarea rows="5" cols="50" name="note" data-ng-model="note"></textarea>
        <br>
        <button>Invia dati</button>
        </div>

    </form>
</div>

controller.js

var app=angular.module('noteApp', [])
app.controller('noteCtrl', function ($scope, $http){
 $scope.myNote = function() {}
 $scope.addNote = function () {
 $http({
   method: 'POST',
   url: 'http://localhost:8080/AngularDb/WebAppDbServlet',
   data: {"nome":$scope.nome, "note":$scope.note}
  })
 }
})

Servlet is inside a (default package) RegisterServlet.java

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/WebAppDbServlet")
public class RegisterServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

       // JDBC driver name and database URL
       static final String JDBC_DRIV        

Answers


Babajide Fowotade February 2016

Try this

<form data-ng-control="noteCtrl">
 <div class="nameContainer">
    Inserisci il nome: <input type="text" name="nome" data-ng-model="data.nome"><br>
 </div>
 <div class="noteContainer">
    Inserisci qui una nota: <textarea rows="5" cols="50" name="note" data-ng-model="data.note"></textarea>
    <br>
 </div> 
 <button ng-click="addNote(data)>Invia dati</button>
</form>

Then in your Controller

 $scope.addNote = function (data) {
   //data should return an object of $cope.nome and $scope.note all in one object
   $http.post('/AngularDb/WebAppDbServlet', data,
    headers: {'Content-Type': 'application/json'})
   .then(
    function(response) { 
     console.log('success if post worked', response) 
    },
    function(error) { 
     console.error('error if error processing post', error);
    });
  }

Post Status

Asked in February 2016
Viewed 3,759 times
Voted 7
Answered 1 times

Search




Leave an answer